diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..42ceb9a --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +dist/ +lib/ +node_modules/ +jest.config.js diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..48214c7 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,68 @@ +{ + "plugins": ["import", "jest", "@typescript-eslint"], + "extends": ["plugin:github/recommended"], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "module", + "project": "./tsconfig.json" + }, + "rules": { + "i18n-text/no-en": "off", + "eslint-comments/no-use": "off", + "import/no-namespace": "off", + "import/no-named-as-default": "off", + "no-shadow": "off", + "no-unused-vars": "off", + "prefer-template": "off", + "@typescript-eslint/no-unused-vars": ["error", {"varsIgnorePattern": "^_"}], + "@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}], + "@typescript-eslint/no-require-imports": "error", + "@typescript-eslint/array-type": "error", + "@typescript-eslint/await-thenable": "error", + "@typescript-eslint/ban-ts-comment": "error", + "camelcase": "off", + "@typescript-eslint/consistent-type-assertions": "error", + "@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}], + "@typescript-eslint/func-call-spacing": ["error", "never"], + "@typescript-eslint/no-array-constructor": "error", + "@typescript-eslint/no-empty-interface": "error", + "@typescript-eslint/no-explicit-any": "error", + "@typescript-eslint/no-extraneous-class": "error", + "@typescript-eslint/no-for-in-array": "error", + "@typescript-eslint/no-inferrable-types": "error", + "@typescript-eslint/no-misused-new": "error", + "@typescript-eslint/no-namespace": "error", + "@typescript-eslint/no-non-null-assertion": "warn", + "@typescript-eslint/no-unnecessary-qualifier": "error", + "@typescript-eslint/no-unnecessary-type-assertion": "error", + "@typescript-eslint/no-useless-constructor": "error", + "@typescript-eslint/no-var-requires": "error", + "@typescript-eslint/prefer-for-of": "warn", + "@typescript-eslint/prefer-function-type": "warn", + "@typescript-eslint/prefer-includes": "error", + "@typescript-eslint/prefer-string-starts-ends-with": "error", + "@typescript-eslint/promise-function-async": "error", + "@typescript-eslint/require-array-sort-compare": "error", + "@typescript-eslint/restrict-plus-operands": "error", + "semi": "off", + "@typescript-eslint/semi": ["error", "never"], + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/unbound-method": "error" + }, + "env": { + "node": true, + "es6": true, + "jest/globals": true + }, + "settings": { + "import/parsers": { + "@typescript-eslint/parser": [".ts", ".tsx"] + }, + "import/resolver": { + "typescript": { + "alwaysTryTypes": true // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist` + } + } + } +} diff --git a/.github/workflows/check-dist.yml b/.github/workflows/check-dist.yml index 32fcfe4..e571511 100644 --- a/.github/workflows/check-dist.yml +++ b/.github/workflows/check-dist.yml @@ -16,18 +16,15 @@ on: - '**.md' workflow_dispatch: -permissions: - contents: read - jobs: check-dist: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 - name: Set Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v4 with: node-version-file: '.nvmrc' @@ -49,7 +46,7 @@ jobs: id: diff # If index.js was different than expected, upload the expected version as an artifact - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@v4 if: ${{ failure() && steps.diff.conclusion == 'failure' }} with: name: dist diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f00c141..d5f8615 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,16 +8,13 @@ on: - main workflow_dispatch: -permissions: - contents: read - jobs: build-test: name: Build & Test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: '.nvmrc' - run: npm ci @@ -28,7 +25,7 @@ jobs: - name: Upload test results if: ${{ !cancelled() }} - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: test-results path: __tests__/__results__/*.xml diff --git a/.github/workflows/dependabot-rebuild-dist.yml b/.github/workflows/dependabot-rebuild-dist.yml deleted file mode 100644 index 8d4f838..0000000 --- a/.github/workflows/dependabot-rebuild-dist.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: Rebuild dist for Dependabot - -on: - pull_request: - types: - - opened - - synchronize - - reopened - paths-ignore: - - '**.md' - -permissions: - contents: write - -jobs: - rebuild-dist: - if: ${{ github.actor == 'dependabot[bot]' && github.event.pull_request.user.login == 'dependabot[bot]' }} - runs-on: ubuntu-latest - - steps: - - name: Checkout Dependabot PR branch - uses: actions/checkout@v6 - with: - ref: ${{ github.event.pull_request.head.ref }} - - - name: Set Node.js - uses: actions/setup-node@v6 - with: - node-version-file: '.nvmrc' - - - name: Install dependencies - run: npm ci - - - name: Rebuild dist artifacts - run: | - npm run build - npm run package - - - name: Commit updated dist artifacts - run: | - if git diff --quiet -- dist/; then - echo "No dist changes to commit." - exit 0 - fi - - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add dist/ - git commit -m "chore: rebuild dist for Dependabot update" - git push diff --git a/.github/workflows/manual-run.yml b/.github/workflows/manual-run.yml index 417eae6..169c810 100644 --- a/.github/workflows/manual-run.yml +++ b/.github/workflows/manual-run.yml @@ -3,15 +3,12 @@ name: Manual run on: workflow_dispatch: -permissions: - contents: read - jobs: check-dist: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 - run: npm ci - run: npm run build - run: npm test diff --git a/.github/workflows/test-report.yml b/.github/workflows/test-report.yml index eb27dbf..e3f9555 100644 --- a/.github/workflows/test-report.yml +++ b/.github/workflows/test-report.yml @@ -6,16 +6,12 @@ on: types: - completed -permissions: - contents: read - actions: read - jobs: report: name: Workflow test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 - uses: ./ with: artifact: test-results diff --git a/.markdownlint.json b/.markdownlint.json deleted file mode 100644 index 3f71d87..0000000 --- a/.markdownlint.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "blanks-around-headings": false, - "blanks-around-lists": false, - "blanks-around-tables": false, - "blanks-around-fences": false, - "no-bare-urls": false, - "line-length": false, - "ul-style": false, - "no-inline-html": false, - "no-multiple-blanks": { - "maximum": 3 - } -} diff --git a/.nvmrc b/.nvmrc index 54c6511..9a2a0e2 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24 +v20 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7835fed..d47e76e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,56 +1,5 @@ # Changelog -## 3.1.0 -* Feature: Add `list-files` input to control test report file listing https://github.com/dorny/test-reporter/pull/773 -* Feature: Add `summary_file` output with the path to the generated summary in Markdown format https://github.com/dorny/test-reporter/pull/772 - -## 3.0.0 -* Feature: Use NodeJS 24 LTS as default runtime https://github.com/dorny/test-reporter/pull/738 - -## 2.7.0 -* Feature: Add `slug-prefix` output for link anchors https://github.com/dorny/test-reporter/pull/731 -* Feature: Report `jest-junit` testsuite errors as failures https://github.com/dorny/test-reporter/pull/155 -* Security: Update dependencies to fix reported security vulnerabilities - -## 2.6.0 -* Fix: For `workflow_run` events, resolve the commit of the check run from related pull request head commits first (matching `workflow_run.head_branch`, then first PR), and fall back to `workflow_run.head_sha` for non-PR runs https://github.com/dorny/test-reporter/pull/673 -* Change: The `test-reporter` action will listed all artifacts associated with the build run https://github.com/dorny/test-reporter/pull/693 -* Maintenance: Upgrade to ESLint v9 https://github.com/dorny/test-reporter/pull/629 - -## 2.5.0 -* Feature: Add Nette Tester support with `tester-junit` reporter https://github.com/dorny/test-reporter/pull/707 -* Maintenance: Bump actions/upload-artifact from 5 to 6 https://github.com/dorny/test-reporter/pull/695 - -## 2.4.0 -* Feature: Add PHPUnit support with JUnit XML dialect parser https://github.com/dorny/test-reporter/pull/422 -* Feature: Add JUnit XML sample files and tests for validation https://github.com/dorny/test-reporter/pull/701 -* Fix: Refactor deprecated `String.substr()` function to use `String.substring()` https://github.com/dorny/test-reporter/pull/704 - -## 2.3.0 -* Feature: Add Python support with `python-xunit` reporter (pytest) https://github.com/dorny/test-reporter/pull/643 -* Feature: Add pytest traceback parsing and `directory-mapping` option https://github.com/dorny/test-reporter/pull/238 -* Performance: Update sax.js to fix large XML file parsing https://github.com/dorny/test-reporter/pull/681 -* Documentation: Complete documentation for all supported reporters https://github.com/dorny/test-reporter/pull/691 -* Security: Bump js-yaml and mocha in /reports/mocha (fixes prototype pollution) https://github.com/dorny/test-reporter/pull/682 - -## 2.2.0 -* Feature: Add collapsed option to control report summary visibility https://github.com/dorny/test-reporter/pull/664 -* Fix badge encoding for values including underscore and hyphens https://github.com/dorny/test-reporter/pull/672 -* Fix missing `report-title` attribute in action definition https://github.com/dorny/test-reporter/pull/637 -* Refactor variable names to fix shadowing issues https://github.com/dorny/test-reporter/pull/630 - -## 2.1.1 -* Fix error when a TestMethod element does not have a className attribute in a trx file https://github.com/dorny/test-reporter/pull/623 -* Add stack trace from trx to summary https://github.com/dorny/test-reporter/pull/615 -* List only failed tests https://github.com/dorny/test-reporter/pull/606 -* Add type definitions to `github-utils.ts` https://github.com/dorny/test-reporter/pull/604 -* Avoid split on undefined https://github.com/dorny/test-reporter/pull/258 -* Return links to summary report https://github.com/dorny/test-reporter/pull/588 -* Add step summary short summary https://github.com/dorny/test-reporter/pull/589 -* Fix for empty TRX TestDefinitions https://github.com/dorny/test-reporter/pull/582 -* Increase step summary limit to 1MiB https://github.com/dorny/test-reporter/pull/581 -* Fix input description for list options https://github.com/dorny/test-reporter/pull/572 - ## 2.1.0 * Feature: Add summary title https://github.com/dorny/test-reporter/pull/568 * Feature: Add Golang test parser https://github.com/dorny/test-reporter/pull/571 diff --git a/README.md b/README.md index f6624d8..ff030f2 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ This [Github Action](https://github.com/features/actions) displays test results ✔️ Provides final `conclusion` and counts of `passed`, `failed` and `skipped` tests as output parameters **How it looks:** -|![Summary showing test run with all tests passed, including details such as test file names, number of passed, failed, and skipped tests, and execution times. The interface is dark-themed and displays a green badge indicating 3527 passed and 4 skipped tests.](assets/fluent-validation-report.png)|![Summary showing test run with a failed unit test. The summary uses a dark background and highlights errors in red for quick identification.](assets/provider-error-summary.png)|![GitHub Actions annotation showing details of a failed unit test with a detailed error message, stack trace, and code annotation.](assets/provider-error-details.png)|![Test cases written in Mocha framework with a list of expectations for each test case. The table format and color-coded badges help users quickly assess test suite health.](assets/mocha-groups.png)| +|![](assets/fluent-validation-report.png)|![](assets/provider-error-summary.png)|![](assets/provider-error-details.png)|![](assets/mocha-groups.png)| |:--:|:--:|:--:|:--:| **Supported languages / frameworks:** @@ -19,9 +19,6 @@ This [Github Action](https://github.com/features/actions) displays test results - Go / [go test](https://pkg.go.dev/testing) - Java / [JUnit](https://junit.org/) - JavaScript / [JEST](https://jestjs.io/) / [Mocha](https://mochajs.org/) -- Python / [pytest](https://docs.pytest.org/en/stable/) / [unittest](https://docs.python.org/3/library/unittest.html) -- PHP / [PHPUnit](https://phpunit.de/) / [Nette Tester](https://tester.nette.org/) -- Ruby / [RSpec](https://rspec.info/) - Swift / xUnit For more information see [Supported formats](#supported-formats) section. @@ -47,12 +44,12 @@ jobs: name: Build & Test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 # checkout the repo + - uses: actions/checkout@v4 # checkout the repo - run: npm ci # install packages - run: npm test # run tests (configured to use jest-junit reporter) - name: Test Report - uses: dorny/test-reporter@v3 + uses: dorny/test-reporter@v2 if: ${{ !cancelled() }} # run this step even if previous step failed with: name: JEST Tests # Name of the check run which will be created @@ -78,10 +75,10 @@ jobs: build-test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 # checkout the repo + - uses: actions/checkout@v4 # checkout the repo - run: npm ci # install packages - run: npm test # run tests (configured to use jest-junit reporter) - - uses: actions/upload-artifact@v7 # upload test results + - uses: actions/upload-artifact@v4 # upload test results if: ${{ !cancelled() }} # run this step even if previous step failed with: name: test-results @@ -103,7 +100,7 @@ jobs: report: runs-on: ubuntu-latest steps: - - uses: dorny/test-reporter@v3 + - uses: dorny/test-reporter@v2 with: artifact: test-results # artifact name name: JEST Tests # Name of the check run which will be created @@ -114,7 +111,7 @@ jobs: ## Usage ```yaml -- uses: dorny/test-reporter@v3 +- uses: dorny/test-reporter@v2 with: # Name or regex of artifact containing test results @@ -148,10 +145,7 @@ jobs: # java-junit # jest-junit # mocha-json - # phpunit-junit - # python-xunit # rspec-json - # swift-xunit reporter: '' # Allows you to generate only the summary. @@ -184,12 +178,6 @@ jobs: # none list-tests: 'all' - # Limits which test result files are listed: - # all - # failed - # none - list-files: 'all' - # Limits number of created annotations with error message and stack trace captured during test execution. # Must be less or equal to 50. max-annotations: '10' @@ -200,13 +188,6 @@ jobs: # Set this action as failed if no test results were found fail-on-empty: 'true' - # Controls whether test report details are collapsed or expanded. - # Supported options: - # auto: Collapse only if all tests pass (default behavior) - # always: Always collapse the report details - # never: Always expand the report details - collapsed: 'auto' - # Relative path under $GITHUB_WORKSPACE where the repository was checked out. working-directory: '' @@ -225,8 +206,6 @@ jobs: | time | Test execution time [ms] | | url | Check run URL | | url_html | Check run URL HTML | -| summary_file | Path to a file containing the generated test report summary in Markdown format | -| slug_prefix| Random anchor links slug prefix generated for the summary headers | ## Supported formats @@ -274,20 +253,6 @@ Supported testing frameworks: For more information see [dotnet test](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test#examples) -
- dotnet-nunit - -Test execution must be configured to generate [NUnit3](https://docs.nunit.org/articles/nunit/technical-notes/usage/Test-Result-XML-Format.html) XML test results. -Install the [NUnit3TestAdapter](https://www.nuget.org/packages/NUnit3TestAdapter) package (required; it registers the `nunit` logger for `dotnet test`), then run tests with: - -`dotnet test --logger "nunit;LogFileName=test-results.xml"` - -Supported testing frameworks: -- [NUnit](https://nunit.org/) - -For more information see [dotnet test](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test#examples) -
-
flutter-json @@ -331,27 +296,6 @@ This is due to the fact Java stack traces don't contain a full path to the sourc Some heuristic was necessary to figure out the mapping between the line in the stack trace and an actual source file.
-
- phpunit-junit - -[PHPUnit](https://phpunit.de/) can generate JUnit XML via CLI: -`phpunit --log-junit reports/phpunit-junit.xml` - -
- -
- tester-junit - -[Nette Tester](https://tester.nette.org/) can generate JUnit XML via CLI: - -```bash -tester -s -o junit tests/ > reports/tester-junit.xml -``` - -**Note:** Nette Tester's JUnit output doesn't include test suite names. The parser will use the report file name as the suite name and automatically group tests by directory structure. - -
-
jest-junit @@ -405,41 +349,6 @@ Before version [v9.1.0](https://github.com/mochajs/mocha/releases/tag/v9.1.0), M Please update Mocha to version [v9.1.0](https://github.com/mochajs/mocha/releases/tag/v9.1.0) or above if you encounter this issue.
-
- python-xunit (Experimental) - -Support for Python test results in xUnit format is experimental - should work but it was not extensively tested. - -For **pytest** support, configure [JUnit XML output](https://docs.pytest.org/en/stable/how-to/output.html#creating-junitxml-format-files) and run with the `--junit-xml` option, which also lets you specify the output path for test results. - -```shell -pytest --junit-xml=test-report.xml -``` - -For **unittest** support, use a test runner that outputs the JUnit report format, such as [unittest-xml-reporting](https://pypi.org/project/unittest-xml-reporting/). -
- -
- rspec-json - -[RSpec](https://rspec.info/) testing framework support requires the usage of JSON formatter. -You can configure RSpec to output JSON format by using the `--format json` option and redirecting to a file: - -```shell -rspec --format json --out rspec-results.json -``` - -Or configure it in `.rspec` file: -``` ---format json ---out rspec-results.json -``` - -For more information see: -- [RSpec documentation](https://rspec.info/) -- [RSpec Formatters](https://relishapp.com/rspec/rspec-core/docs/formatters) -
-
swift-xunit (Experimental) diff --git a/__tests__/__outputs__/dotnet-trx-only-failed.md b/__tests__/__outputs__/dotnet-trx-only-failed.md deleted file mode 100644 index 5eeaec5..0000000 --- a/__tests__/__outputs__/dotnet-trx-only-failed.md +++ /dev/null @@ -1,34 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-5%20passed%2C%205%20failed%2C%201%20skipped-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/dotnet-trx.trx](#user-content-r0)|5 ✅|5 ❌|1 ⚪|1s| -## ❌ fixtures/dotnet-trx.trx -**11** tests were completed in **1s** with **5** passed, **5** failed and **1** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[DotnetTests.XUnitTests.CalculatorTests](#user-content-r0s0)|5 ✅|5 ❌|1 ⚪|118ms| -### ❌ DotnetTests.XUnitTests.CalculatorTests -``` -❌ Exception_In_TargetTest - System.DivideByZeroException : Attempted to divide by zero. - at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.Unit\Calculator.cs:line 9 - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 33 -❌ Exception_In_Test - System.Exception : Test - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 39 -❌ Failing_Test - Assert.Equal() Failure - Expected: 3 - Actual: 2 - at DotnetTests.XUnitTests.CalculatorTests.Failing_Test() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 27 -❌ Is_Even_Number(i: 3) - Assert.True() Failure - Expected: True - Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Is_Even_Number(Int32 i) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 59 -❌ Should be even number(i: 3) - Assert.True() Failure - Expected: True - Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Theory_With_Custom_Name(Int32 i) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 67 -``` \ No newline at end of file diff --git a/__tests__/__outputs__/dotnet-trx.md b/__tests__/__outputs__/dotnet-trx.md index 40bcaf2..92f12c0 100644 --- a/__tests__/__outputs__/dotnet-trx.md +++ b/__tests__/__outputs__/dotnet-trx.md @@ -12,29 +12,23 @@ ✅ Custom Name ❌ Exception_In_TargetTest System.DivideByZeroException : Attempted to divide by zero. - at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.Unit\Calculator.cs:line 9 - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 33 ❌ Exception_In_Test System.Exception : Test - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 39 ❌ Failing_Test Assert.Equal() Failure Expected: 3 Actual: 2 - at DotnetTests.XUnitTests.CalculatorTests.Failing_Test() in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 27 ✅ Is_Even_Number(i: 2) ❌ Is_Even_Number(i: 3) Assert.True() Failure Expected: True Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Is_Even_Number(Int32 i) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 59 ✅ Passing_Test ✅ Should be even number(i: 2) ❌ Should be even number(i: 3) Assert.True() Failure Expected: True Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Theory_With_Custom_Name(Int32 i) in C:\Users\Michal\Workspace\dorny\test-reporter\reports\dotnet\DotnetTests.XUnitTests\CalculatorTests.cs:line 67 ⚪ Skipped_Test ✅ Timeout_Test ``` \ No newline at end of file diff --git a/__tests__/__outputs__/dotnet-xunitv3.md b/__tests__/__outputs__/dotnet-xunitv3.md deleted file mode 100644 index f27f9e2..0000000 --- a/__tests__/__outputs__/dotnet-xunitv3.md +++ /dev/null @@ -1,26 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-1%20passed%2C%203%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/dotnet-xunitv3.trx](#user-content-r0)|1 ✅|3 ❌||267ms| -## ❌ fixtures/dotnet-xunitv3.trx -**4** tests were completed in **267ms** with **1** passed, **3** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[DotnetTests.XUnitV3Tests.FixtureTests](#user-content-r0s0)|1 ✅|1 ❌||18ms| -|[Unclassified](#user-content-r0s1)||2 ❌||0ms| -### ❌ DotnetTests.XUnitV3Tests.FixtureTests -``` -❌ Failing_Test - Assert.Null() Failure: Value is not null - Expected: null - Actual: Fixture { } - at DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test() in /_/reports/dotnet/DotnetTests.XUnitV3Tests/FixtureTests.cs:line 25 - at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) - at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr) -✅ Passing_Test -``` -### ❌ Unclassified -``` -❌ [Test Class Cleanup Failure (DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test)] -❌ [Test Class Cleanup Failure (DotnetTests.XUnitV3Tests.FixtureTests.Passing_Test)] -``` \ No newline at end of file diff --git a/__tests__/__outputs__/jest-test-errors-results.md b/__tests__/__outputs__/jest-test-errors-results.md deleted file mode 100644 index e7b98ff..0000000 --- a/__tests__/__outputs__/jest-test-errors-results.md +++ /dev/null @@ -1,22 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-2%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/test-errors/jest/jest-test-results.xml](#user-content-r0)||2 ❌||646ms| -## ❌ fixtures/test-errors/jest/jest-test-results.xml -**2** tests were completed in **646ms** with **0** passed, **2** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[libs/bar.spec.ts](#user-content-r0s0)||1 ❌||0ms| -|[libs/foo.spec.ts](#user-content-r0s1)||1 ❌||0ms| -### ❌ libs/bar.spec.ts -``` -Test suite failed to run - ❌ libs/bar.spec.ts - ● Test suite failed to run -``` -### ❌ libs/foo.spec.ts -``` -Test suite failed to run - ❌ libs/foo.spec.ts - ● Test suite failed to run -``` \ No newline at end of file diff --git a/__tests__/__outputs__/junit-basic.md b/__tests__/__outputs__/junit-basic.md deleted file mode 100644 index 642aaf4..0000000 --- a/__tests__/__outputs__/junit-basic.md +++ /dev/null @@ -1,23 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-5%20passed%2C%201%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/external/java/junit4-basic.xml](#user-content-r0)|5 ✅|1 ❌||16s| -## ❌ fixtures/external/java/junit4-basic.xml -**6** tests were completed in **16s** with **5** passed, **1** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[Tests.Authentication](#user-content-r0s0)|2 ✅|1 ❌||9s| -|[Tests.Registration](#user-content-r0s1)|3 ✅|||7s| -### ❌ Tests.Authentication -``` -✅ testCase7 -✅ testCase8 -❌ testCase9 - AssertionError: Assertion error message -``` -### ✅ Tests.Registration -``` -✅ testCase1 -✅ testCase2 -✅ testCase3 -``` \ No newline at end of file diff --git a/__tests__/__outputs__/junit-complete.md b/__tests__/__outputs__/junit-complete.md deleted file mode 100644 index 8dbbb7c..0000000 --- a/__tests__/__outputs__/junit-complete.md +++ /dev/null @@ -1,22 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-5%20passed%2C%202%20failed%2C%201%20skipped-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/external/java/junit4-complete.xml](#user-content-r0)|5 ✅|2 ❌|1 ⚪|16s| -## ❌ fixtures/external/java/junit4-complete.xml -**8** tests were completed in **16s** with **5** passed, **2** failed and **1** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[Tests.Registration](#user-content-r0s0)|5 ✅|2 ❌|1 ⚪|16s| -### ❌ Tests.Registration -``` -✅ testCase1 -✅ testCase2 -✅ testCase3 -⚪ testCase4 -❌ testCase5 - AssertionError: Expected value did not match. -❌ testCase6 - ArithmeticError: Division by zero. -✅ testCase7 -✅ testCase8 -``` \ No newline at end of file diff --git a/__tests__/__outputs__/phpunit-junit-basic-results.md b/__tests__/__outputs__/phpunit-junit-basic-results.md deleted file mode 100644 index 641b9dd..0000000 --- a/__tests__/__outputs__/phpunit-junit-basic-results.md +++ /dev/null @@ -1,30 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-8%20passed%2C%201%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/external/phpunit/junit-basic.xml](#user-content-r0)|8 ✅|1 ❌||16s| -## ❌ fixtures/external/phpunit/junit-basic.xml -**9** tests were completed in **16s** with **8** passed, **1** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[Tests.Authentication](#user-content-r0s0)|2 ✅|1 ❌||9s| -|[Tests.Authentication.Login](#user-content-r0s1)|3 ✅|||4s| -|[Tests.Registration](#user-content-r0s2)|3 ✅|||7s| -### ❌ Tests.Authentication -``` -✅ testCase7 -✅ testCase8 -❌ testCase9 - AssertionError: Assertion error message -``` -### ✅ Tests.Authentication.Login -``` -✅ testCase4 -✅ testCase5 -✅ testCase6 -``` -### ✅ Tests.Registration -``` -✅ testCase1 -✅ testCase2 -✅ testCase3 -``` \ No newline at end of file diff --git a/__tests__/__outputs__/phpunit-phpcheckstyle-results.md b/__tests__/__outputs__/phpunit-phpcheckstyle-results.md deleted file mode 100644 index 6966c55..0000000 --- a/__tests__/__outputs__/phpunit-phpcheckstyle-results.md +++ /dev/null @@ -1,88 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-28%20passed%2C%202%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/external/phpunit/phpcheckstyle-phpunit.xml](#user-content-r0)|28 ✅|2 ❌||41ms| -## ❌ fixtures/external/phpunit/phpcheckstyle-phpunit.xml -**30** tests were completed in **41ms** with **28** passed, **2** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[CommentsTest](#user-content-r0s0)|3 ✅|||7ms| -|[DeprecationTest](#user-content-r0s1)|1 ✅|||1ms| -|[GoodTest](#user-content-r0s2)|4 ✅|||5ms| -|[IndentationTest](#user-content-r0s3)|8 ✅|||8ms| -|[MetricsTest](#user-content-r0s4)|1 ✅|||4ms| -|[NamingTest](#user-content-r0s5)|2 ✅|||3ms| -|[OptimizationTest](#user-content-r0s6)|1 ✅|||1ms| -|[OtherTest](#user-content-r0s7)|2 ✅|2 ❌||7ms| -|[PHPTagsTest](#user-content-r0s8)|2 ✅|||1ms| -|[ProhibitedTest](#user-content-r0s9)|1 ✅|||1ms| -|[StrictCompareTest](#user-content-r0s10)|1 ✅|||2ms| -|[UnusedTest](#user-content-r0s11)|2 ✅|||2ms| -### ✅ CommentsTest -``` -✅ testGoodDoc -✅ testComments -✅ testTODOs -``` -### ✅ DeprecationTest -``` -✅ testDeprecations -``` -### ✅ GoodTest -``` -✅ testGood -✅ testDoWhile -✅ testAnonymousFunction -✅ testException -``` -### ✅ IndentationTest -``` -✅ testTabIndentation -✅ testSpaceIndentation -✅ testSpaceIndentationArray -✅ testGoodSpaceIndentationArray -✅ testGoodIndentationNewLine -✅ testGoodIndentationSpaces -✅ testBadSpaces -✅ testBadSpaceAfterControl -``` -### ✅ MetricsTest -``` -✅ testMetrics -``` -### ✅ NamingTest -``` -✅ testNaming -✅ testFunctionNaming -``` -### ✅ OptimizationTest -``` -✅ testTextAfterClosingTag -``` -### ❌ OtherTest -``` -❌ testOther - PHPUnit\Framework\ExpectationFailedException -❌ testException - PHPUnit\Framework\ExpectationFailedException -✅ testEmpty -✅ testSwitchCaseNeedBreak -``` -### ✅ PHPTagsTest -``` -✅ testTextAfterClosingTag -✅ testClosingTagNotNeeded -``` -### ✅ ProhibitedTest -``` -✅ testProhibited -``` -### ✅ StrictCompareTest -``` -✅ testStrictCompare -``` -### ✅ UnusedTest -``` -✅ testGoodUnused -✅ testBadUnused -``` \ No newline at end of file diff --git a/__tests__/__outputs__/phpunit-test-results.md b/__tests__/__outputs__/phpunit-test-results.md deleted file mode 100644 index 67f8258..0000000 --- a/__tests__/__outputs__/phpunit-test-results.md +++ /dev/null @@ -1,41 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-10%20passed%2C%202%20failed-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/phpunit/phpunit.xml](#user-content-r0)|10 ✅|2 ❌||148ms| -## ❌ fixtures/phpunit/phpunit.xml -**12** tests were completed in **148ms** with **10** passed, **2** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[CLI Arguments](#user-content-r0s0)||2 ❌||140ms| -|[PHPUnit\Event\CollectingDispatcherTest](#user-content-r0s1)|2 ✅|||4ms| -|[PHPUnit\Event\DeferringDispatcherTest](#user-content-r0s2)|4 ✅|||3ms| -|[PHPUnit\Event\DirectDispatcherTest](#user-content-r0s3)|4 ✅|||1ms| -### ❌ CLI Arguments -``` -❌ targeting-traits-with-coversclass-attribute-is-deprecated.phpt - PHPUnit\Framework\PhptAssertionFailedError -❌ targeting-traits-with-usesclass-attribute-is-deprecated.phpt - PHPUnit\Framework\PhptAssertionFailedError -``` -### ✅ PHPUnit\Event\CollectingDispatcherTest -``` -PHPUnit.Event.CollectingDispatcherTest - ✅ testHasNoCollectedEventsWhenFlushedImmediatelyAfterCreation - ✅ testCollectsDispatchedEventsUntilFlushed -``` -### ✅ PHPUnit\Event\DeferringDispatcherTest -``` -PHPUnit.Event.DeferringDispatcherTest - ✅ testCollectsEventsUntilFlush - ✅ testFlushesCollectedEvents - ✅ testSubscriberCanBeRegistered - ✅ testTracerCanBeRegistered -``` -### ✅ PHPUnit\Event\DirectDispatcherTest -``` -PHPUnit.Event.DirectDispatcherTest - ✅ testDispatchesEventToKnownSubscribers - ✅ testDispatchesEventToTracers - ✅ testRegisterRejectsUnknownSubscriber - ✅ testDispatchRejectsUnknownEventType -``` \ No newline at end of file diff --git a/__tests__/__outputs__/python-xunit-pytest.md b/__tests__/__outputs__/python-xunit-pytest.md deleted file mode 100644 index 7b13e28..0000000 --- a/__tests__/__outputs__/python-xunit-pytest.md +++ /dev/null @@ -1,26 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-6%20passed%2C%202%20failed%2C%202%20skipped-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/python-xunit-pytest.xml](#user-content-r0)|6 ✅|2 ❌|2 ⚪|19ms| -## ❌ fixtures/python-xunit-pytest.xml -**10** tests were completed in **19ms** with **6** passed, **2** failed and **2** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[pytest](#user-content-r0s0)|6 ✅|2 ❌|2 ⚪|19ms| -### ❌ pytest -``` -tests.test_lib - ✅ test_always_pass - ✅ test_with_subtests - ✅ test_parameterized[param1] - ✅ test_parameterized[param2] - ⚪ test_always_skip - ❌ test_always_fail - assert False - ⚪ test_expected_failure - ❌ test_error - Exception: error - ✅ test_with_record_property -custom_classname - ✅ test_with_record_xml_attribute -``` \ No newline at end of file diff --git a/__tests__/__outputs__/python-xunit-unittest.md b/__tests__/__outputs__/python-xunit-unittest.md deleted file mode 100644 index 230d186..0000000 --- a/__tests__/__outputs__/python-xunit-unittest.md +++ /dev/null @@ -1,23 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-4%20passed%2C%202%20failed%2C%202%20skipped-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/python-xunit-unittest.xml](#user-content-r0)|4 ✅|2 ❌|2 ⚪|1ms| -## ❌ fixtures/python-xunit-unittest.xml -**8** tests were completed in **1ms** with **4** passed, **2** failed and **2** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[TestAcme-20251114214921](#user-content-r0s0)|4 ✅|2 ❌|2 ⚪|1ms| -### ❌ TestAcme-20251114214921 -``` -TestAcme - ✅ test_always_pass - ✅ test_parameterized_0_param1 - ✅ test_parameterized_1_param2 - ✅ test_with_subtests - ❌ test_always_fail - AssertionError: failed - ❌ test_error - Exception: error - ⚪ test_always_skip - ⚪ test_expected_failure -``` \ No newline at end of file diff --git a/__tests__/__outputs__/tester-bootstrap-test-results.md b/__tests__/__outputs__/tester-bootstrap-test-results.md deleted file mode 100644 index 93359ab..0000000 --- a/__tests__/__outputs__/tester-bootstrap-test-results.md +++ /dev/null @@ -1,20 +0,0 @@ -![Tests passed successfully](https://img.shields.io/badge/tests-4%20passed-success) -
Expand for details - -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/nette-tester/BootstrapFormRenderer-report.xml](#user-content-r0)|4 ✅|||300ms| -## ✅ fixtures/nette-tester/BootstrapFormRenderer-report.xml -**4** tests were completed in **300ms** with **4** passed, **0** failed and **0** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[BootstrapFormRenderer-report.xml](#user-content-r0s0)|4 ✅|||300ms| -### ✅ BootstrapFormRenderer-report.xml -``` -KdybyTests/BootstrapFormRenderer - ✅ BootstrapRendererTest.phpt::testRenderingBasics - ✅ BootstrapRendererTest.phpt::testRenderingIndividual - ✅ BootstrapRendererTest.phpt::testRenderingComponents - ✅ BootstrapRendererTest.phpt::testMultipleFormsInTemplate -``` -
\ No newline at end of file diff --git a/__tests__/__outputs__/tester-v1.7-test-results.md b/__tests__/__outputs__/tester-v1.7-test-results.md deleted file mode 100644 index 253837f..0000000 --- a/__tests__/__outputs__/tester-v1.7-test-results.md +++ /dev/null @@ -1,87 +0,0 @@ -![Tests failed](https://img.shields.io/badge/tests-61%20passed%2C%201%20failed%2C%203%20skipped-critical) -|Report|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[fixtures/nette-tester/tester-v1.7-report.xml](#user-content-r0)|61 ✅|1 ❌|3 ⚪|2s| -## ❌ fixtures/nette-tester/tester-v1.7-report.xml -**65** tests were completed in **2s** with **61** passed, **1** failed and **3** skipped. -|Test suite|Passed|Failed|Skipped|Time| -|:---|---:|---:|---:|---:| -|[tester-v1.7-report.xml](#user-content-r0s0)|61 ✅|1 ❌|3 ⚪|2s| -### ❌ tester-v1.7-report.xml -``` -tests/Framework - ⚪ Dumper.toPhp.php7.phpt - ✅ Assert.contains.phpt - ✅ Assert.count.phpt - ✅ Assert.equal.phpt - ✅ Assert.equal.recursive.phpt::testSimple - ✅ Assert.equal.recursive.phpt::testMultiple - ✅ Assert.equal.recursive.phpt::testDeep - ✅ Assert.equal.recursive.phpt::testCross - ✅ Assert.equal.recursive.phpt::testThirdParty - ✅ Assert.error.phpt - ✅ Assert.exception.phpt - ✅ Assert.false.phpt - ✅ Assert.match.phpt - ✅ Assert.match.regexp.phpt - ✅ Assert.nan.phpt - ✅ Assert.noError.phpt - ✅ Assert.same.phpt - ✅ Assert.null.phpt - ✅ Assert.true.phpt - ✅ Assert.truthy.phpt - ✅ DataProvider.load.phpt - ✅ Assert.type.phpt - ✅ DataProvider.parseAnnotation.phpt - ✅ DataProvider.testQuery.phpt - ✅ DomQuery.css2Xpath.phpt - ✅ DomQuery.fromHtml.phpt - ✅ DomQuery.fromXml.phpt - ✅ Dumper.dumpException.phpt - ✅ Dumper.color.phpt - ✅ Dumper.toLine.phpt - ✅ Dumper.toPhp.recursion.phpt - ✅ Dumper.toPhp.phpt - ✅ FileMock.phpt - ✅ Helpers.escapeArg.phpt - ✅ Helpers.parseDocComment.phpt - ✅ TestCase.annotationThrows.phpt - ✅ TestCase.annotationThrows.setUp.tearDown.phpt - ✅ TestCase.annotationThrows.syntax.phpt - ✅ TestCase.basic.phpt - ✅ TestCase.dataProvider.generator.phpt - ✅ TestCase.dataProvider.phpt - ✅ TestCase.invalidMethods.phpt - ✅ TestCase.invalidProvider.phpt - ✅ TestCase.order.error.phpt - ✅ TestCase.order.errorMuted.phpt - ✅ TestCase.order.phpt - ✅ Prevent loop in error handling. The #268 regression. (TestCase.ownErrorHandler.phpt) -tests/CodeCoverage - ⚪ Collector.start.phpt - ✅ PhpParser.parse.lines.phpt - ✅ PhpParser.parse.methods.phpt - ✅ CloverXMLGenerator.phpt - ✅ PhpParser.parse.edge.phpt - ✅ PhpParser.parse.lines-of-code.phpt - ✅ PhpParser.parse.namespaces.phpt -tests/Runner - ✅ CommandLine.phpt - ⚪ HhvmPhpInterpreter.phpt - ✅ Runner.find-tests.phpt - ✅ Job.phpt - ✅ ZendPhpExecutable.phpt - ✅ Runner.multiple.phpt - ✅ Runner.edge.phpt - ✅ Runner.stop-on-fail.phpt - ❌ Runner.multiple-fails.phpt - Failed: '... in /Users/izso/Developer/nette/tester/tests/Runner/multiple-fails/...' should match - ... '..., unexpected end of file in %a%testcase-syntax-error.phptx on line ...' - - diff '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.expected' '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.actual' - - in tests/Runner/Runner.multiple-fails.phpt(78) Tester\Assert::match() - ✅ Runner.annotations.phpt -tests/RunnerOutput - ✅ JUnitPrinter.phpt -``` \ No newline at end of file diff --git a/__tests__/__snapshots__/dart-json.test.ts.snap b/__tests__/__snapshots__/dart-json.test.ts.snap index 88a7349..a499822 100644 --- a/__tests__/__snapshots__/dart-json.test.ts.snap +++ b/__tests__/__snapshots__/dart-json.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`dart-json tests matches report snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/dotnet-nunit.test.ts.snap b/__tests__/__snapshots__/dotnet-nunit.test.ts.snap index 529f702..60d55f2 100644 --- a/__tests__/__snapshots__/dotnet-nunit.test.ts.snap +++ b/__tests__/__snapshots__/dotnet-nunit.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`dotnet-nunit tests report from ./reports/dotnet test results matches snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/dotnet-trx.test.ts.snap b/__tests__/__snapshots__/dotnet-trx.test.ts.snap index b9d272d..1ca07eb 100644 --- a/__tests__/__snapshots__/dotnet-trx.test.ts.snap +++ b/__tests__/__snapshots__/dotnet-trx.test.ts.snap @@ -1,6 +1,6 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`dotnet-trx tests matches dotnet-trx report snapshot 1`] = ` +exports[`dotnet-trx tests matches report snapshot 1`] = ` TestRunResult { "path": "fixtures/dotnet-trx.trx", "suites": [ @@ -21,9 +21,7 @@ TestRunResult { at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.Unit\\Calculator.cs:line 9 at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 33", "line": 9, - "message": "System.DivideByZeroException : Attempted to divide by zero. - at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.Unit\\Calculator.cs:line 9 - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 33", + "message": "System.DivideByZeroException : Attempted to divide by zero.", "path": "DotnetTests.Unit/Calculator.cs", }, "name": "Exception_In_TargetTest", @@ -35,8 +33,7 @@ TestRunResult { "details": "System.Exception : Test at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 39", "line": 39, - "message": "System.Exception : Test - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 39", + "message": "System.Exception : Test", "path": "DotnetTests.XUnitTests/CalculatorTests.cs", }, "name": "Exception_In_Test", @@ -52,8 +49,7 @@ Actual: 2 "line": 27, "message": "Assert.Equal() Failure Expected: 3 -Actual: 2 - at DotnetTests.XUnitTests.CalculatorTests.Failing_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 27", +Actual: 2", "path": "DotnetTests.XUnitTests/CalculatorTests.cs", }, "name": "Failing_Test", @@ -75,8 +71,7 @@ Actual: False "line": 59, "message": "Assert.True() Failure Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Is_Even_Number(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 59", +Actual: False", "path": "DotnetTests.XUnitTests/CalculatorTests.cs", }, "name": "Is_Even_Number(i: 3)", @@ -104,213 +99,7 @@ Actual: False "line": 67, "message": "Assert.True() Failure Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Theory_With_Custom_Name(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 67", - "path": "DotnetTests.XUnitTests/CalculatorTests.cs", - }, - "name": "Should be even number(i: 3)", - "result": "failed", - "time": 0.6537000000000001, - }, - TestCaseResult { - "error": undefined, - "name": "Skipped_Test", - "result": "skipped", - "time": 1, - }, - TestCaseResult { - "error": undefined, - "name": "Timeout_Test", - "result": "success", - "time": 108.42580000000001, - }, - ], - }, - ], - "name": "DotnetTests.XUnitTests.CalculatorTests", - "totalTime": undefined, - }, - ], - "totalTime": 1116, -} -`; - -exports[`dotnet-trx tests matches dotnet-xunitv3 report snapshot 1`] = ` -TestRunResult { - "path": "fixtures/dotnet-xunitv3.trx", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": null, - "tests": [ - TestCaseResult { - "error": { - "details": "Assert.Null() Failure: Value is not null -Expected: null -Actual: Fixture { } - at DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test() in /_/reports/dotnet/DotnetTests.XUnitV3Tests/FixtureTests.cs:line 25 - at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) - at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)", - "line": 25, - "message": "Assert.Null() Failure: Value is not null -Expected: null -Actual: Fixture { } - at DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test() in /_/reports/dotnet/DotnetTests.XUnitV3Tests/FixtureTests.cs:line 25 - at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) - at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)", - "path": "DotnetTests.XUnitV3Tests/FixtureTests.cs", - }, - "name": "Failing_Test", - "result": "failed", - "time": 17.0545, - }, - TestCaseResult { - "error": undefined, - "name": "Passing_Test", - "result": "success", - "time": 0.8786, - }, - ], - }, - ], - "name": "DotnetTests.XUnitV3Tests.FixtureTests", - "totalTime": undefined, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": null, - "tests": [ - TestCaseResult { - "error": undefined, - "name": "[Test Class Cleanup Failure (DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test)]", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "[Test Class Cleanup Failure (DotnetTests.XUnitV3Tests.FixtureTests.Passing_Test)]", - "result": "failed", - "time": 0, - }, - ], - }, - ], - "name": "Unclassified", - "totalTime": undefined, - }, - ], - "totalTime": 267, -} -`; - -exports[`dotnet-trx tests matches report snapshot (only failed tests) 1`] = ` -TestRunResult { - "path": "fixtures/dotnet-trx.trx", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": null, - "tests": [ - TestCaseResult { - "error": undefined, - "name": "Custom Name", - "result": "success", - "time": 0.1371, - }, - TestCaseResult { - "error": { - "details": "System.DivideByZeroException : Attempted to divide by zero. - at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.Unit\\Calculator.cs:line 9 - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 33", - "line": 9, - "message": "System.DivideByZeroException : Attempted to divide by zero. - at DotnetTests.Unit.Calculator.Div(Int32 a, Int32 b) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.Unit\\Calculator.cs:line 9 - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_TargetTest() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 33", - "path": "DotnetTests.Unit/Calculator.cs", - }, - "name": "Exception_In_TargetTest", - "result": "failed", - "time": 0.8377, - }, - TestCaseResult { - "error": { - "details": "System.Exception : Test - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 39", - "line": 39, - "message": "System.Exception : Test - at DotnetTests.XUnitTests.CalculatorTests.Exception_In_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 39", - "path": "DotnetTests.XUnitTests/CalculatorTests.cs", - }, - "name": "Exception_In_Test", - "result": "failed", - "time": 2.5175, - }, - TestCaseResult { - "error": { - "details": "Assert.Equal() Failure -Expected: 3 -Actual: 2 - at DotnetTests.XUnitTests.CalculatorTests.Failing_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 27", - "line": 27, - "message": "Assert.Equal() Failure -Expected: 3 -Actual: 2 - at DotnetTests.XUnitTests.CalculatorTests.Failing_Test() in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 27", - "path": "DotnetTests.XUnitTests/CalculatorTests.cs", - }, - "name": "Failing_Test", - "result": "failed", - "time": 3.8697, - }, - TestCaseResult { - "error": undefined, - "name": "Is_Even_Number(i: 2)", - "result": "success", - "time": 0.0078, - }, - TestCaseResult { - "error": { - "details": "Assert.True() Failure -Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Is_Even_Number(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 59", - "line": 59, - "message": "Assert.True() Failure -Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Is_Even_Number(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 59", - "path": "DotnetTests.XUnitTests/CalculatorTests.cs", - }, - "name": "Is_Even_Number(i: 3)", - "result": "failed", - "time": 0.41409999999999997, - }, - TestCaseResult { - "error": undefined, - "name": "Passing_Test", - "result": "success", - "time": 0.1365, - }, - TestCaseResult { - "error": undefined, - "name": "Should be even number(i: 2)", - "result": "success", - "time": 0.0097, - }, - TestCaseResult { - "error": { - "details": "Assert.True() Failure -Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Theory_With_Custom_Name(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 67", - "line": 67, - "message": "Assert.True() Failure -Expected: True -Actual: False - at DotnetTests.XUnitTests.CalculatorTests.Theory_With_Custom_Name(Int32 i) in C:\\Users\\Michal\\Workspace\\dorny\\test-reporter\\reports\\dotnet\\DotnetTests.XUnitTests\\CalculatorTests.cs:line 67", +Actual: False", "path": "DotnetTests.XUnitTests/CalculatorTests.cs", }, "name": "Should be even number(i: 3)", diff --git a/__tests__/__snapshots__/golang-json.test.ts.snap b/__tests__/__snapshots__/golang-json.test.ts.snap index bd28d4a..75c6de1 100644 --- a/__tests__/__snapshots__/golang-json.test.ts.snap +++ b/__tests__/__snapshots__/golang-json.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`golang-json tests report from ./reports/dotnet test results matches snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/java-junit.test.ts.snap b/__tests__/__snapshots__/java-junit.test.ts.snap index ce56a55..341b092 100644 --- a/__tests__/__snapshots__/java-junit.test.ts.snap +++ b/__tests__/__snapshots__/java-junit.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`java-junit tests report from apache/pulsar single suite test results matches snapshot 1`] = ` TestRunResult { @@ -6878,153 +6878,3 @@ at java.lang.Thread.run(Thread.java:748) "totalTime": 2126531.0000000005, } `; - -exports[`java-junit tests report from testmo/junitxml basic example matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/external/java/junit4-basic.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase1", - "result": "success", - "time": 2113.871, - }, - TestCaseResult { - "error": undefined, - "name": "testCase2", - "result": "success", - "time": 1051, - }, - TestCaseResult { - "error": undefined, - "name": "testCase3", - "result": "success", - "time": 3441, - }, - ], - }, - ], - "name": "Tests.Registration", - "totalTime": 6605.870999999999, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase7", - "result": "success", - "time": 2508, - }, - TestCaseResult { - "error": undefined, - "name": "testCase8", - "result": "success", - "time": 1230.8159999999998, - }, - TestCaseResult { - "error": { - "details": undefined, - "line": undefined, - "message": "AssertionError: Assertion error message", - "path": undefined, - }, - "name": "testCase9", - "result": "failed", - "time": 982, - }, - ], - }, - ], - "name": "Tests.Authentication", - "totalTime": 9076.816, - }, - ], - "totalTime": 15682.687, -} -`; - -exports[`java-junit tests report from testmo/junitxml complete example matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/external/java/junit4-complete.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase1", - "result": "success", - "time": 2436, - }, - TestCaseResult { - "error": undefined, - "name": "testCase2", - "result": "success", - "time": 1534, - }, - TestCaseResult { - "error": undefined, - "name": "testCase3", - "result": "success", - "time": 822, - }, - TestCaseResult { - "error": undefined, - "name": "testCase4", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": { - "details": undefined, - "line": undefined, - "message": "AssertionError: Expected value did not match.", - "path": undefined, - }, - "name": "testCase5", - "result": "failed", - "time": 2902.412, - }, - TestCaseResult { - "error": { - "details": undefined, - "line": undefined, - "message": "ArithmeticError: Division by zero.", - "path": undefined, - }, - "name": "testCase6", - "result": "failed", - "time": 3819, - }, - TestCaseResult { - "error": undefined, - "name": "testCase7", - "result": "success", - "time": 2944, - }, - TestCaseResult { - "error": undefined, - "name": "testCase8", - "result": "success", - "time": 1625.275, - }, - ], - }, - ], - "name": "Tests.Registration", - "totalTime": 16082.687, - }, - ], - "totalTime": 16082.687, -} -`; diff --git a/__tests__/__snapshots__/jest-junit.test.ts.snap b/__tests__/__snapshots__/jest-junit.test.ts.snap index dc71713..eb20dfe 100644 --- a/__tests__/__snapshots__/jest-junit.test.ts.snap +++ b/__tests__/__snapshots__/jest-junit.test.ts.snap @@ -1,67 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing - -exports[`jest-junit tests jest testsuite errors example test results matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/test-errors/jest/jest-test-results.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "Test suite failed to run", - "tests": [ - TestCaseResult { - "error": { - "details": " ● Test suite failed to run - - tsconfig.json:13:3 - error TS6258: 'typeRoots' should be set inside the 'compilerOptions' object of the config json file - - 13 "typeRoots": ["./src/lib/types", "./node_modules/@types"], - ~~~~~~~~~~~ -", - "line": undefined, - "path": undefined, - }, - "name": "libs/foo.spec.ts", - "result": "failed", - "time": 0, - }, - ], - }, - ], - "name": "libs/foo.spec.ts", - "totalTime": 0, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "Test suite failed to run", - "tests": [ - TestCaseResult { - "error": { - "details": " ● Test suite failed to run - - tsconfig.json:13:3 - error TS6258: 'typeRoots' should be set inside the 'compilerOptions' object of the config json file - - 13 "typeRoots": ["./src/lib/types", "./node_modules/@types"], - ~~~~~~~~~~~ -", - "line": undefined, - "path": undefined, - }, - "name": "libs/bar.spec.ts", - "result": "failed", - "time": 0, - }, - ], - }, - ], - "name": "libs/bar.spec.ts", - "totalTime": 0, - }, - ], - "totalTime": 646, -} -`; +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`jest-junit tests parsing ESLint report without timing information works - PR #134 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/mocha-json.test.ts.snap b/__tests__/__snapshots__/mocha-json.test.ts.snap index 4a1448c..7038239 100644 --- a/__tests__/__snapshots__/mocha-json.test.ts.snap +++ b/__tests__/__snapshots__/mocha-json.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`mocha-json tests report from ./reports/mocha-json test results matches snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/phpunit-junit.test.ts.snap b/__tests__/__snapshots__/phpunit-junit.test.ts.snap deleted file mode 100644 index d48d941..0000000 --- a/__tests__/__snapshots__/phpunit-junit.test.ts.snap +++ /dev/null @@ -1,628 +0,0 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing - -exports[`phpunit-junit tests report from junit-basic.xml matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/external/phpunit/junit-basic.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase1", - "result": "success", - "time": 2113.871, - }, - TestCaseResult { - "error": undefined, - "name": "testCase2", - "result": "success", - "time": 1051, - }, - TestCaseResult { - "error": undefined, - "name": "testCase3", - "result": "success", - "time": 3441, - }, - ], - }, - ], - "name": "Tests.Registration", - "totalTime": 6605.870999999999, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase4", - "result": "success", - "time": 2244, - }, - TestCaseResult { - "error": undefined, - "name": "testCase5", - "result": "success", - "time": 781, - }, - TestCaseResult { - "error": undefined, - "name": "testCase6", - "result": "success", - "time": 1331, - }, - ], - }, - ], - "name": "Tests.Authentication.Login", - "totalTime": 4356, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCase7", - "result": "success", - "time": 2508, - }, - TestCaseResult { - "error": undefined, - "name": "testCase8", - "result": "success", - "time": 1230.8159999999998, - }, - TestCaseResult { - "error": { - "details": "", - "line": undefined, - "message": "AssertionError: Assertion error message", - "path": undefined, - }, - "name": "testCase9", - "result": "failed", - "time": 982, - }, - ], - }, - ], - "name": "Tests.Authentication", - "totalTime": 9076.816, - }, - ], - "totalTime": 15682.687, -} -`; - -exports[`phpunit-junit tests report from phpcheckstyle-phpunit.xml matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/external/phpunit/phpcheckstyle-phpunit.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testGoodDoc", - "result": "success", - "time": 5.093, - }, - TestCaseResult { - "error": undefined, - "name": "testComments", - "result": "success", - "time": 0.921, - }, - TestCaseResult { - "error": undefined, - "name": "testTODOs", - "result": "success", - "time": 0.6880000000000001, - }, - ], - }, - ], - "name": "CommentsTest", - "totalTime": 6.702, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testDeprecations", - "result": "success", - "time": 0.9740000000000001, - }, - ], - }, - ], - "name": "DeprecationTest", - "totalTime": 0.9740000000000001, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testGood", - "result": "success", - "time": 2.6470000000000002, - }, - TestCaseResult { - "error": undefined, - "name": "testDoWhile", - "result": "success", - "time": 1.0219999999999998, - }, - TestCaseResult { - "error": undefined, - "name": "testAnonymousFunction", - "result": "success", - "time": 0.8, - }, - TestCaseResult { - "error": undefined, - "name": "testException", - "result": "success", - "time": 0.888, - }, - ], - }, - ], - "name": "GoodTest", - "totalTime": 5.357, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testTabIndentation", - "result": "success", - "time": 0.857, - }, - TestCaseResult { - "error": undefined, - "name": "testSpaceIndentation", - "result": "success", - "time": 0.929, - }, - TestCaseResult { - "error": undefined, - "name": "testSpaceIndentationArray", - "result": "success", - "time": 0.975, - }, - TestCaseResult { - "error": undefined, - "name": "testGoodSpaceIndentationArray", - "result": "success", - "time": 1.212, - }, - TestCaseResult { - "error": undefined, - "name": "testGoodIndentationNewLine", - "result": "success", - "time": 0.859, - }, - TestCaseResult { - "error": undefined, - "name": "testGoodIndentationSpaces", - "result": "success", - "time": 0.78, - }, - TestCaseResult { - "error": undefined, - "name": "testBadSpaces", - "result": "success", - "time": 1.1199999999999999, - }, - TestCaseResult { - "error": undefined, - "name": "testBadSpaceAfterControl", - "result": "success", - "time": 0.9219999999999999, - }, - ], - }, - ], - "name": "IndentationTest", - "totalTime": 7.654, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testMetrics", - "result": "success", - "time": 4.146999999999999, - }, - ], - }, - ], - "name": "MetricsTest", - "totalTime": 4.146999999999999, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testNaming", - "result": "success", - "time": 1.426, - }, - TestCaseResult { - "error": undefined, - "name": "testFunctionNaming", - "result": "success", - "time": 1.271, - }, - ], - }, - ], - "name": "NamingTest", - "totalTime": 2.697, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testTextAfterClosingTag", - "result": "success", - "time": 0.9940000000000001, - }, - ], - }, - ], - "name": "OptimizationTest", - "totalTime": 0.9940000000000001, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": { - "details": "OtherTest::testOther -We expect 20 warnings -Failed asserting that 19 matches expected 20. - -/workspace/phpcheckstyle/test/OtherTest.php:24", - "line": 12, - "message": "PHPUnit\\Framework\\ExpectationFailedException", - "path": undefined, - }, - "name": "testOther", - "result": "failed", - "time": 5.2509999999999994, - }, - TestCaseResult { - "error": { - "details": "OtherTest::testException -We expect 1 error -Failed asserting that 0 matches expected 1. - -/workspace/phpcheckstyle/test/OtherTest.php:40", - "line": 31, - "message": "PHPUnit\\Framework\\ExpectationFailedException", - "path": undefined, - }, - "name": "testException", - "result": "failed", - "time": 0.751, - }, - TestCaseResult { - "error": undefined, - "name": "testEmpty", - "result": "success", - "time": 0.42700000000000005, - }, - TestCaseResult { - "error": undefined, - "name": "testSwitchCaseNeedBreak", - "result": "success", - "time": 0.901, - }, - ], - }, - ], - "name": "OtherTest", - "totalTime": 7.329, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testTextAfterClosingTag", - "result": "success", - "time": 0.641, - }, - TestCaseResult { - "error": undefined, - "name": "testClosingTagNotNeeded", - "result": "success", - "time": 0.631, - }, - ], - }, - ], - "name": "PHPTagsTest", - "totalTime": 1.272, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testProhibited", - "result": "success", - "time": 0.9380000000000001, - }, - ], - }, - ], - "name": "ProhibitedTest", - "totalTime": 0.9380000000000001, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testStrictCompare", - "result": "success", - "time": 1.578, - }, - ], - }, - ], - "name": "StrictCompareTest", - "totalTime": 1.578, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testGoodUnused", - "result": "success", - "time": 0.94, - }, - TestCaseResult { - "error": undefined, - "name": "testBadUnused", - "result": "success", - "time": 0.895, - }, - ], - }, - ], - "name": "UnusedTest", - "totalTime": 1.835, - }, - ], - "totalTime": undefined, -} -`; - -exports[`phpunit-junit tests report from phpunit test results matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/phpunit/phpunit.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "PHPUnit.Event.CollectingDispatcherTest", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testHasNoCollectedEventsWhenFlushedImmediatelyAfterCreation", - "result": "success", - "time": 1.441, - }, - TestCaseResult { - "error": undefined, - "name": "testCollectsDispatchedEventsUntilFlushed", - "result": "success", - "time": 2.815, - }, - ], - }, - ], - "name": "PHPUnit\\Event\\CollectingDispatcherTest", - "totalTime": 4.256, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "PHPUnit.Event.DeferringDispatcherTest", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testCollectsEventsUntilFlush", - "result": "success", - "time": 1.6720000000000002, - }, - TestCaseResult { - "error": undefined, - "name": "testFlushesCollectedEvents", - "result": "success", - "time": 0.661, - }, - TestCaseResult { - "error": undefined, - "name": "testSubscriberCanBeRegistered", - "result": "success", - "time": 0.33399999999999996, - }, - TestCaseResult { - "error": undefined, - "name": "testTracerCanBeRegistered", - "result": "success", - "time": 0.262, - }, - ], - }, - ], - "name": "PHPUnit\\Event\\DeferringDispatcherTest", - "totalTime": 2.928, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "PHPUnit.Event.DirectDispatcherTest", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "testDispatchesEventToKnownSubscribers", - "result": "success", - "time": 0.17, - }, - TestCaseResult { - "error": undefined, - "name": "testDispatchesEventToTracers", - "result": "success", - "time": 0.248, - }, - TestCaseResult { - "error": undefined, - "name": "testRegisterRejectsUnknownSubscriber", - "result": "success", - "time": 0.257, - }, - TestCaseResult { - "error": undefined, - "name": "testDispatchRejectsUnknownEventType", - "result": "success", - "time": 0.11900000000000001, - }, - ], - }, - ], - "name": "PHPUnit\\Event\\DirectDispatcherTest", - "totalTime": 0.794, - }, - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "", - "tests": [ - TestCaseResult { - "error": { - "details": "targeting-traits-with-coversclass-attribute-is-deprecated.phptFailed asserting that string matches format description. ---- Expected -+++ Actual -@@ @@ - PHPUnit Started (PHPUnit 11.2-g0c2333363 using PHP 8.2.17 (cli) on Linux) - Test Runner Configured - Test Suite Loaded (1 test) -+Test Runner Triggered Warning (No code coverage driver available) - Event Facade Sealed - Test Runner Started - Test Suite Sorted -@@ @@ - Test Preparation Started (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithCoversClassTest::testSomething) - Test Prepared (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithCoversClassTest::testSomething) - Test Passed (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithCoversClassTest::testSomething) --Test Runner Triggered Deprecation (Targeting a trait such as PHPUnit\\TestFixture\\CoveredTrait with #[CoversClass] is deprecated, please refactor your test to use #[CoversTrait] instead.) - Test Finished (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithCoversClassTest::testSomething) - Test Suite Finished (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithCoversClassTest, 1 test) - Test Runner Execution Finished - Test Runner Finished --PHPUnit Finished (Shell Exit Code: 0) -+PHPUnit Finished (Shell Exit Code: 1) - -/home/matteo/OSS/phpunit/tests/end-to-end/metadata/targeting-traits-with-coversclass-attribute-is-deprecated.phpt:28 -/home/matteo/OSS/phpunit/src/Framework/TestSuite.php:369 -/home/matteo/OSS/phpunit/src/TextUI/TestRunner.php:62 -/home/matteo/OSS/phpunit/src/TextUI/Application.php:200", - "line": undefined, - "message": "PHPUnit\\Framework\\PhptAssertionFailedError", - "path": undefined, - }, - "name": "targeting-traits-with-coversclass-attribute-is-deprecated.phpt", - "result": "failed", - "time": 68.151, - }, - TestCaseResult { - "error": { - "details": "targeting-traits-with-usesclass-attribute-is-deprecated.phptFailed asserting that string matches format description. ---- Expected -+++ Actual -@@ @@ - PHPUnit Started (PHPUnit 11.2-g0c2333363 using PHP 8.2.17 (cli) on Linux) - Test Runner Configured - Test Suite Loaded (1 test) -+Test Runner Triggered Warning (No code coverage driver available) - Event Facade Sealed - Test Runner Started - Test Suite Sorted -@@ @@ - Test Preparation Started (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithUsesClassTest::testSomething) - Test Prepared (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithUsesClassTest::testSomething) - Test Passed (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithUsesClassTest::testSomething) --Test Runner Triggered Deprecation (Targeting a trait such as PHPUnit\\TestFixture\\CoveredTrait with #[UsesClass] is deprecated, please refactor your test to use #[UsesTrait] instead.) - Test Finished (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithUsesClassTest::testSomething) - Test Suite Finished (PHPUnit\\DeprecatedAnnotationsTestFixture\\TraitTargetedWithUsesClassTest, 1 test) - Test Runner Execution Finished - Test Runner Finished --PHPUnit Finished (Shell Exit Code: 0) -+PHPUnit Finished (Shell Exit Code: 1) - -/home/matteo/OSS/phpunit/tests/end-to-end/metadata/targeting-traits-with-usesclass-attribute-is-deprecated.phpt:28 -/home/matteo/OSS/phpunit/src/Framework/TestSuite.php:369 -/home/matteo/OSS/phpunit/src/TextUI/TestRunner.php:62 -/home/matteo/OSS/phpunit/src/TextUI/Application.php:200", - "line": undefined, - "message": "PHPUnit\\Framework\\PhptAssertionFailedError", - "path": undefined, - }, - "name": "targeting-traits-with-usesclass-attribute-is-deprecated.phpt", - "result": "failed", - "time": 64.268, - }, - ], - }, - ], - "name": "CLI Arguments", - "totalTime": 140.397, - }, - ], - "totalTime": undefined, -} -`; diff --git a/__tests__/__snapshots__/python-xunit.test.ts.snap b/__tests__/__snapshots__/python-xunit.test.ts.snap deleted file mode 100644 index f325c84..0000000 --- a/__tests__/__snapshots__/python-xunit.test.ts.snap +++ /dev/null @@ -1,192 +0,0 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing - -exports[`python-xunit pytest report report from python test results matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/python-xunit-pytest.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "tests.test_lib", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "test_always_pass", - "result": "success", - "time": 2, - }, - TestCaseResult { - "error": undefined, - "name": "test_with_subtests", - "result": "success", - "time": 5, - }, - TestCaseResult { - "error": undefined, - "name": "test_parameterized[param1]", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_parameterized[param2]", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_always_skip", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": { - "details": "def test_always_fail(): - > assert False - E assert False - - tests/test_lib.py:25: AssertionError - ", - "line": undefined, - "message": "assert False", - "path": undefined, - }, - "name": "test_always_fail", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_expected_failure", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": { - "details": "def test_error(): - > raise Exception("error") - E Exception: error - - tests/test_lib.py:32: Exception - ", - "line": undefined, - "message": "Exception: error", - "path": undefined, - }, - "name": "test_error", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_with_record_property", - "result": "success", - "time": 0, - }, - ], - }, - TestGroupResult { - "name": "custom_classname", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "test_with_record_xml_attribute", - "result": "success", - "time": 0, - }, - ], - }, - ], - "name": "pytest", - "totalTime": 19, - }, - ], - "totalTime": undefined, -} -`; - -exports[`python-xunit unittest report report from python test results matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/python-xunit-unittest.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "TestAcme", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "test_always_pass", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_parameterized_0_param1", - "result": "success", - "time": 1, - }, - TestCaseResult { - "error": undefined, - "name": "test_parameterized_1_param2", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_with_subtests", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": { - "details": "Traceback (most recent call last): - File "/Users/foo/Projects/python-test/tests/test_lib.py", line 24, in test_always_fail - self.fail("failed") -AssertionError: failed -", - "line": undefined, - "message": "AssertionError: failed", - "path": undefined, - }, - "name": "test_always_fail", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": { - "details": "Traceback (most recent call last): - File "/Users/foo/Projects/python-test/tests/test_lib.py", line 31, in test_error - raise Exception("error") -Exception: error -", - "line": undefined, - "message": "Exception: error", - "path": undefined, - }, - "name": "test_error", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_always_skip", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "test_expected_failure", - "result": "skipped", - "time": 0, - }, - ], - }, - ], - "name": "TestAcme-20251114214921", - "totalTime": 1, - }, - ], - "totalTime": 1, -} -`; diff --git a/__tests__/__snapshots__/rspec-json.test.ts.snap b/__tests__/__snapshots__/rspec-json.test.ts.snap index 51c1943..cc14bfb 100644 --- a/__tests__/__snapshots__/rspec-json.test.ts.snap +++ b/__tests__/__snapshots__/rspec-json.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`rspec-json tests report from ./reports/rspec-json test results matches snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/swift-xunit.test.ts.snap b/__tests__/__snapshots__/swift-xunit.test.ts.snap index bddc6ea..ae34deb 100644 --- a/__tests__/__snapshots__/swift-xunit.test.ts.snap +++ b/__tests__/__snapshots__/swift-xunit.test.ts.snap @@ -1,4 +1,4 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`swift-xunit tests report from swift test results matches snapshot 1`] = ` TestRunResult { diff --git a/__tests__/__snapshots__/tester-junit.test.ts.snap b/__tests__/__snapshots__/tester-junit.test.ts.snap deleted file mode 100644 index 9bf445a..0000000 --- a/__tests__/__snapshots__/tester-junit.test.ts.snap +++ /dev/null @@ -1,485 +0,0 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing - -exports[`tester-junit tests parses complex test names from BootstrapFormRenderer-report.xml 1`] = ` -TestRunResult { - "path": "fixtures/nette-tester/BootstrapFormRenderer-report.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "KdybyTests/BootstrapFormRenderer", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "BootstrapRendererTest.phpt::testRenderingBasics", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "BootstrapRendererTest.phpt::testRenderingIndividual", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "BootstrapRendererTest.phpt::testRenderingComponents", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "BootstrapRendererTest.phpt::testMultipleFormsInTemplate", - "result": "success", - "time": 0, - }, - ], - }, - ], - "name": "BootstrapFormRenderer-report.xml", - "totalTime": 300, - }, - ], - "totalTime": undefined, -} -`; - -exports[`tester-junit tests report from tester-v1.7-report.xml matches snapshot 1`] = ` -TestRunResult { - "path": "fixtures/nette-tester/tester-v1.7-report.xml", - "suites": [ - TestSuiteResult { - "groups": [ - TestGroupResult { - "name": "tests/Framework", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "Dumper.toPhp.php7.phpt", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.contains.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.count.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.recursive.phpt::testSimple", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.recursive.phpt::testMultiple", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.recursive.phpt::testDeep", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.recursive.phpt::testCross", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.equal.recursive.phpt::testThirdParty", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.error.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.exception.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.false.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.match.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.match.regexp.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.nan.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.noError.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.same.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.null.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.true.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.truthy.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DataProvider.load.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Assert.type.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DataProvider.parseAnnotation.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DataProvider.testQuery.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DomQuery.css2Xpath.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DomQuery.fromHtml.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "DomQuery.fromXml.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Dumper.dumpException.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Dumper.color.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Dumper.toLine.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Dumper.toPhp.recursion.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Dumper.toPhp.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "FileMock.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Helpers.escapeArg.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Helpers.parseDocComment.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.annotationThrows.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.annotationThrows.setUp.tearDown.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.annotationThrows.syntax.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.basic.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.dataProvider.generator.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.dataProvider.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.invalidMethods.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.invalidProvider.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.order.error.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.order.errorMuted.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "TestCase.order.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Prevent loop in error handling. The #268 regression. (TestCase.ownErrorHandler.phpt)", - "result": "success", - "time": 0, - }, - ], - }, - TestGroupResult { - "name": "tests/CodeCoverage", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "Collector.start.phpt", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "PhpParser.parse.lines.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "PhpParser.parse.methods.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "CloverXMLGenerator.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "PhpParser.parse.edge.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "PhpParser.parse.lines-of-code.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "PhpParser.parse.namespaces.phpt", - "result": "success", - "time": 0, - }, - ], - }, - TestGroupResult { - "name": "tests/Runner", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "CommandLine.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "HhvmPhpInterpreter.phpt", - "result": "skipped", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Runner.find-tests.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Job.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "ZendPhpExecutable.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Runner.multiple.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Runner.edge.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Runner.stop-on-fail.phpt", - "result": "success", - "time": 0, - }, - TestCaseResult { - "error": { - "details": "Failed: '... in /Users/izso/Developer/nette/tester/tests/Runner/multiple-fails/...' should match - ... '..., unexpected end of file in %a%testcase-syntax-error.phptx on line ...' - -diff '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.expected' '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.actual' - -in tests/Runner/Runner.multiple-fails.phpt(78) Tester\\Assert::match()", - "line": undefined, - "message": "Failed: '... in /Users/izso/Developer/nette/tester/tests/Runner/multiple-fails/...' should match - ... '..., unexpected end of file in %a%testcase-syntax-error.phptx on line ...' - -diff '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.expected' '/Users/izso/Developer/nette/tester/tests/Runner/output/Runner.multiple-fails.actual' - -in tests/Runner/Runner.multiple-fails.phpt(78) Tester\\Assert::match()", - "path": undefined, - }, - "name": "Runner.multiple-fails.phpt", - "result": "failed", - "time": 0, - }, - TestCaseResult { - "error": undefined, - "name": "Runner.annotations.phpt", - "result": "success", - "time": 0, - }, - ], - }, - TestGroupResult { - "name": "tests/RunnerOutput", - "tests": [ - TestCaseResult { - "error": undefined, - "name": "JUnitPrinter.phpt", - "result": "success", - "time": 0, - }, - ], - }, - ], - "name": "tester-v1.7-report.xml", - "totalTime": 2100, - }, - ], - "totalTime": undefined, -} -`; diff --git a/__tests__/dart-json.test.ts b/__tests__/dart-json.test.ts index c272cf4..12b664b 100644 --- a/__tests__/dart-json.test.ts +++ b/__tests__/dart-json.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {DartJsonParser} from '../src/parsers/dart-json/dart-json-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {DartJsonParser} from '../src/parsers/dart-json/dart-json-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('dart-json tests', () => { it('produces empty test run result when there are no test cases', async () => { diff --git a/__tests__/dotnet-nunit.test.ts b/__tests__/dotnet-nunit.test.ts index ea170b5..6903c5a 100644 --- a/__tests__/dotnet-nunit.test.ts +++ b/__tests__/dotnet-nunit.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {DotnetNunitParser} from '../src/parsers/dotnet-nunit/dotnet-nunit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {DotnetNunitParser} from '../src/parsers/dotnet-nunit/dotnet-nunit-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('dotnet-nunit tests', () => { it('report from ./reports/dotnet test results matches snapshot', async () => { diff --git a/__tests__/dotnet-trx.test.ts b/__tests__/dotnet-trx.test.ts index 08c5bfa..e7f83ee 100644 --- a/__tests__/dotnet-trx.test.ts +++ b/__tests__/dotnet-trx.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {DotnetTrxParser} from '../src/parsers/dotnet-trx/dotnet-trx-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport, ReportOptions} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {DotnetTrxParser} from '../src/parsers/dotnet-trx/dotnet-trx-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('dotnet-trx tests', () => { it('produces empty test run result when there are no test cases', async () => { @@ -44,34 +39,9 @@ describe('dotnet-trx tests', () => { expect(result.result).toBe('success') }) - it.each([['dotnet-trx'], ['dotnet-xunitv3']])('matches %s report snapshot', async reportName => { - const fixturePath = path.join(__dirname, 'fixtures', `${reportName}.trx`) - const outputPath = path.join(__dirname, '__outputs__', `${reportName}.md`) - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [ - 'DotnetTests.Unit/Calculator.cs', - 'DotnetTests.XUnitTests/CalculatorTests.cs', - 'DotnetTests.XUnitV3Tests/FixtureTests.cs' - ] - //workDir: 'C:/Users/Michal/Workspace/dorny/test-check/reports/dotnet/' - } - - const parser = new DotnetTrxParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('matches report snapshot (only failed tests)', async () => { + it('matches report snapshot', async () => { const fixturePath = path.join(__dirname, 'fixtures', 'dotnet-trx.trx') - const outputPath = path.join(__dirname, '__outputs__', 'dotnet-trx-only-failed.md') + const outputPath = path.join(__dirname, '__outputs__', 'dotnet-trx.md') const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) @@ -85,12 +55,7 @@ describe('dotnet-trx tests', () => { const result = await parser.parse(filePath, fileContent) expect(result).toMatchSnapshot() - const reportOptions: ReportOptions = { - ...DEFAULT_OPTIONS, - listSuites: 'all', - listTests: 'failed' - } - const report = getReport([result], reportOptions) + const report = getReport([result]) fs.mkdirSync(path.dirname(outputPath), {recursive: true}) fs.writeFileSync(outputPath, report) }) diff --git a/__tests__/fixtures/dotnet-xunitv3.trx b/__tests__/fixtures/dotnet-xunitv3.trx deleted file mode 100644 index 6bd9c25..0000000 --- a/__tests__/fixtures/dotnet-xunitv3.trx +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - Assert.Null() Failure: Value is not null -Expected: null -Actual: Fixture { } - at DotnetTests.XUnitV3Tests.FixtureTests.Failing_Test() in /_/reports/dotnet/DotnetTests.XUnitV3Tests/FixtureTests.cs:line 25 - at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) - at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Exit code indicates failure: '2'. Please refer to https://aka.ms/testingplatform/exitcodes for more information. - - - - \ No newline at end of file diff --git a/__tests__/fixtures/empty/phpunit-empty.xml b/__tests__/fixtures/empty/phpunit-empty.xml deleted file mode 100644 index 0d3d2e2..0000000 --- a/__tests__/fixtures/empty/phpunit-empty.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/__tests__/fixtures/external/java/junit4-basic.xml b/__tests__/fixtures/external/java/junit4-basic.xml deleted file mode 100644 index cece7ae..0000000 --- a/__tests__/fixtures/external/java/junit4-basic.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/__tests__/fixtures/external/java/junit4-complete.xml b/__tests__/fixtures/external/java/junit4-complete.xml deleted file mode 100644 index 14f131b..0000000 --- a/__tests__/fixtures/external/java/junit4-complete.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - Config line #1 - Config line #2 - Config line #3 - - - - - Data written to standard out. - - - Data written to standard error. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Data written to standard out. - - - Data written to standard error. - - - - - - - - - - - - - This text describes the purpose of this test case and provides - an overview of what the test does and how it works. - - - - - diff --git a/__tests__/fixtures/external/phpunit/junit-basic.xml b/__tests__/fixtures/external/phpunit/junit-basic.xml deleted file mode 100644 index 27f5771..0000000 --- a/__tests__/fixtures/external/phpunit/junit-basic.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/__tests__/fixtures/external/phpunit/phpcheckstyle-phpunit.xml b/__tests__/fixtures/external/phpunit/phpcheckstyle-phpunit.xml deleted file mode 100644 index 629fe81..0000000 --- a/__tests__/fixtures/external/phpunit/phpcheckstyle-phpunit.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - File "./test/sample/bad_comments.php" warning, line 4 - Avoid Shell/Perl like comments. -File "./test/sample/bad_comments.php" warning, line 6 - The class Comments must have a docblock comment. -File "./test/sample/bad_comments.php" warning, line 10 - The function testComment must have a docblock comment. -File "./test/sample/bad_comments.php" warning, line 18 - The function testComment returns a value and must include @returns in its docblock. -File "./test/sample/bad_comments.php" warning, line 18 - The function testComment parameters must match those in its docblock @param. -File "./test/sample/bad_comments.php" warning, line 18 - The function testComment throws an exception and must include @throws in its docblock. - - - - File "./test/sample/todo.php" warning, line 3 - TODO: The todo message. - - - - - - File "./test/sample/bad_deprecation.php" warning, line 17 - split is deprecated since PHP 5.3. explode($pattern, $string) or preg_split('@'.$pattern.'@', $string) must be used instead. -File "./test/sample/bad_deprecation.php" warning, line 19 - ereg is deprecated since PHP 5.3. preg_match('@'.$pattern.'@', $string) must be used instead. -File "./test/sample/bad_deprecation.php" warning, line 21 - session_register is deprecated since PHP 5.3. $_SESSION must be used instead. -File "./test/sample/bad_deprecation.php" warning, line 23 - mysql_db_query is deprecated since PHP 5.3. mysql_select_db and mysql_query must be used instead. -File "./test/sample/bad_deprecation.php" warning, line 25 - $HTTP_GET_VARS is deprecated since PHP 5.3. $_GET must be used instead. - - - - - - - - - - - - File "./test/sample/bad_indentation.php" warning, line 8 - Whitespace indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 15 - Whitespace indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 17 - Whitespace indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 18 - Whitespace indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 19 - Whitespace indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 20 - Whitespace indentation must not be used. - - - - File "./test/sample/bad_indentation.php" warning, line 10 - Tab indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 10 - The indentation level must be 4 but was 1. -File "./test/sample/bad_indentation.php" warning, line 13 - Tab indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 13 - The indentation level must be 4 but was 1. -File "./test/sample/bad_indentation.php" warning, line 15 - The indentation level must be 8 but was 4. -File "./test/sample/bad_indentation.php" warning, line 16 - Tab indentation must not be used. -File "./test/sample/bad_indentation.php" warning, line 16 - The indentation level must be 8 but was 1. -File "./test/sample/bad_indentation.php" warning, line 17 - The indentation level must be 8 but was 3. -File "./test/sample/bad_indentation.php" warning, line 18 - The indentation level must be 8 but was 5. -File "./test/sample/bad_indentation.php" warning, line 19 - The indentation level must be 8 but was 6. -File "./test/sample/bad_indentation.php" warning, line 20 - The indentation level must be 4 but was 1. - - - - File "./test/sample/bad_indentation_array.php" warning, line 10 - Tab indentation must not be used. -File "./test/sample/bad_indentation_array.php" warning, line 10 - The indentation level must be 4 but was 1. -File "./test/sample/bad_indentation_array.php" warning, line 13 - Tab indentation must not be used. -File "./test/sample/bad_indentation_array.php" warning, line 13 - The indentation level must be 4 but was 1. -File "./test/sample/bad_indentation_array.php" warning, line 16 - The indentation level must be 12 but was 8. -File "./test/sample/bad_indentation_array.php" warning, line 24 - The indentation level must be 12 but was 8. -File "./test/sample/bad_indentation_array.php" warning, line 29 - The indentation level must be 8 but was 12. -File "./test/sample/bad_indentation_array.php" warning, line 15 - Undeclared or unused variable: $aVar. -File "./test/sample/bad_indentation_array.php" warning, line 19 - Undeclared or unused variable: $bVar. -File "./test/sample/bad_indentation_array.php" warning, line 23 - Undeclared or unused variable: $cVar. -File "./test/sample/bad_indentation_array.php" warning, line 27 - Undeclared or unused variable: $dVar. - - - - - - - File "./test/sample/bad_spaces.php" warning, line 17 - Whitespace must follow ,. -File "./test/sample/bad_spaces.php" warning, line 17 - Whitespace must precede {. -File "./test/sample/bad_spaces.php" warning, line 19 - Whitespace must follow if. -File "./test/sample/bad_spaces.php" warning, line 23 - Whitespace must precede =. -File "./test/sample/bad_spaces.php" warning, line 23 - Whitespace must follow =. -File "./test/sample/bad_spaces.php" warning, line 23 - Whitespace must precede +. -File "./test/sample/bad_spaces.php" warning, line 23 - Whitespace must follow +. -File "./test/sample/bad_spaces.php" info, line 25 - Whitespace must not precede ,. -File "./test/sample/bad_spaces.php" info, line 26 - Whitespace must not follow !. - - - - File "./test/sample/bad_space_after_control.php" warning, line 19 - Whitespace must not follow if. - - - - - - File "./test/sample/bad_metrics.php" warning, line 21 - The function testMetrics's number of parameters (6) must not exceed 4. -File "./test/sample/bad_metrics.php" info, line 55 - Line is too long. [233/160] -File "./test/sample/bad_metrics.php" warning, line 21 - The Cyclomatic Complexity of function testMetrics is too high. [15/10] -File "./test/sample/bad_metrics.php" warning, line 244 - The testMetrics function body length is too long. [223/200] - - - - - - File "./test/sample/_bad_naming.php" error, line 11 - Constant _badly_named_constant name should follow the pattern /^[A-Z][A-Z0-9_]*$/. -File "./test/sample/_bad_naming.php" error, line 13 - Constant bad_CONST name should follow the pattern /^[A-Z][A-Z0-9_]*$/. -File "./test/sample/_bad_naming.php" warning, line 17 - Top level variable $XXX name should follow the pattern /^[a-z_][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" warning, line 20 - Variable x name length is too short. -File "./test/sample/_bad_naming.php" error, line 28 - Class badlynamedclass name should follow the pattern /^[A-Z][a-zA-Z0-9_]*$/. -File "./test/sample/_bad_naming.php" warning, line 32 - Member variable $YYY name should follow the pattern /^[a-z_][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" warning, line 37 - The constructor name must be __construct(). -File "./test/sample/_bad_naming.php" error, line 44 - Function Badlynamedfunction name should follow the pattern /^[a-z][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" warning, line 47 - Local variable $ZZZ name should follow the pattern /^[a-z_][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" error, line 54 - Protected function Badlynamedfunction2 name should follow the pattern /^[a-z][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" error, line 61 - Private function badlynamedfunction3 name should follow the pattern /^_[a-z][a-zA-Z0-9]*$/. -File "./test/sample/_bad_naming.php" error, line 70 - Interface _badlynamedinterface name should follow the pattern /^[A-Z][a-zA-Z0-9_]*$/. -File "./test/sample/_bad_naming.php" error, line 75 - File _bad_naming.php name should follow the pattern /^[a-zA-Z][a-zA-Z0-9._]*$/. - - - - - - - File "./test/sample/bad_optimisation.php" warning, line 18 - count function must not be used inside a loop. -File "./test/sample/bad_optimisation.php" warning, line 23 - count function must not be used inside a loop. - - - - - - OtherTest::testOther -We expect 20 warnings -Failed asserting that 19 matches expected 20. - -/workspace/phpcheckstyle/test/OtherTest.php:24 - File "./test/sample/bad_other.php" warning, line 17 - All arguments with default values must be at the end of the block or statement. -File "./test/sample/bad_other.php" warning, line 21 - Errors must not be silenced when calling a function. -File "./test/sample/bad_other.php" warning, line 23 - Prefer single-quoted strings when you don't need string interpolation. -File "./test/sample/bad_other.php" warning, line 23 - Encapsed variables must not be used inside a string. -File "./test/sample/bad_other.php" warning, line 23 - Encapsed variables must not be used inside a string. -File "./test/sample/bad_other.php" warning, line 23 - Prefer single-quoted strings when you don't need string interpolation. -File "./test/sample/bad_other.php" warning, line 37 - TODO: Show todos -File "./test/sample/bad_other.php" warning, line 40 - Avoid empty statements (;;). -File "./test/sample/bad_other.php" warning, line 42 - Boolean operators (&&) must be used instead of logical operators (AND). -File "./test/sample/bad_other.php" warning, line 42 - Empty if block. -File "./test/sample/bad_other.php" warning, line 48 - Heredoc syntax must not be used. -File "./test/sample/bad_other.php" warning, line 52 - The statement if must contain its code within a {} block. -File "./test/sample/bad_other.php" warning, line 54 - Consider using a strict comparison operator instead of ==. -File "./test/sample/bad_other.php" warning, line 54 - The statement while must contain its code within a {} block. -File "./test/sample/bad_other.php" warning, line 66 - The switch statement must have a default case. -File "./test/sample/bad_other.php" warning, line 79 - The default case of a switch statement must be located after all other cases. -File "./test/sample/bad_other.php" warning, line 93 - Unary operators (++ or --) must not be used inside a control statement -File "./test/sample/bad_other.php" warning, line 95 - Assigments (=) must not be used inside a control statement. -File "./test/sample/bad_other.php" warning, line 106 - File ./test/sample/bad_other.php must not have multiple class declarations. - - - - OtherTest::testException -We expect 1 error -Failed asserting that 0 matches expected 1. - -/workspace/phpcheckstyle/test/OtherTest.php:40 - - - File "./test/sample/empty.php" warning, line 1 - The file ./test/sample/empty.php is empty. - - - - File "./test/sample/switch_multi_case.php" warning, line 10 - The case statement must contain a break. - - - - - - File "./test/sample/bad_php_tags_text_after_end.php" warning, line 9 - A PHP close tag must not be included at the end of the file. - - - - File "./test/sample/bad_php_tags_end_not_needed.php" warning, line 1 - PHP tag should be at the beginning of the line. - - - - - - File "./test/sample/bad_prohibited.php" warning, line 18 - The function exec must not be called. -File "./test/sample/bad_prohibited.php" warning, line 20 - Token T_PRINT must not be used. - - - - - - File "./test/sample/bad_strictcompare.php" warning, line 14 - Consider using a strict comparison operator instead of ==. -File "./test/sample/bad_strictcompare.php" warning, line 19 - Consider using a strict comparison operator instead of !=. -File "./test/sample/bad_strictcompare.php" warning, line 24 - Consider using a strict comparison operator instead of ==. -File "./test/sample/bad_strictcompare.php" warning, line 29 - Consider using a strict comparison operator instead of ==. - - - - - - - File "./test/sample/bad_unused.php" warning, line 23 - Function _testUnused has unused code after RETURN. -File "./test/sample/bad_unused.php" warning, line 27 - The function _testUnused parameter $b is not used. -File "./test/sample/bad_unused.php" warning, line 18 - Unused private function: _testUnused. -File "./test/sample/bad_unused.php" warning, line 20 - Undeclared or unused variable: $c. - - - - - - diff --git a/__tests__/fixtures/nette-tester/BootstrapFormRenderer-report.xml b/__tests__/fixtures/nette-tester/BootstrapFormRenderer-report.xml deleted file mode 100644 index cde3cd5..0000000 --- a/__tests__/fixtures/nette-tester/BootstrapFormRenderer-report.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/__tests__/fixtures/nette-tester/tester-v1.7-report.xml b/__tests__/fixtures/nette-tester/tester-v1.7-report.xml deleted file mode 100644 index 7de1127..0000000 --- a/__tests__/fixtures/nette-tester/tester-v1.7-report.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/__tests__/fixtures/phpunit/phpunit-paths.xml b/__tests__/fixtures/phpunit/phpunit-paths.xml deleted file mode 100644 index 46b0a16..0000000 --- a/__tests__/fixtures/phpunit/phpunit-paths.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - /home/runner/work/repo/src/Fake.php:42 - - - /home/runner/work/repo/src/Other.php:10 - - - at /home/runner/work/repo/src/Paren.php(123) - - - C:\repo\src\Win.php:77 - - - at C:\repo\src\WinParen.php(88) - - - /home/runner/work/repo/tests/Sample.phpt:12 - - - diff --git a/__tests__/fixtures/phpunit/phpunit.xml b/__tests__/fixtures/phpunit/phpunit.xml deleted file mode 100644 index b0e0cc0..0000000 --- a/__tests__/fixtures/phpunit/phpunit.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - targeting-traits-with-coversclass-attribute-is-deprecated.phptFailed asserting that string matches format description. ---- Expected -+++ Actual -@@ @@ - PHPUnit Started (PHPUnit 11.2-g0c2333363 using PHP 8.2.17 (cli) on Linux) - Test Runner Configured - Test Suite Loaded (1 test) -+Test Runner Triggered Warning (No code coverage driver available) - Event Facade Sealed - Test Runner Started - Test Suite Sorted -@@ @@ - Test Preparation Started (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithCoversClassTest::testSomething) - Test Prepared (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithCoversClassTest::testSomething) - Test Passed (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithCoversClassTest::testSomething) --Test Runner Triggered Deprecation (Targeting a trait such as PHPUnit\TestFixture\CoveredTrait with #[CoversClass] is deprecated, please refactor your test to use #[CoversTrait] instead.) - Test Finished (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithCoversClassTest::testSomething) - Test Suite Finished (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithCoversClassTest, 1 test) - Test Runner Execution Finished - Test Runner Finished --PHPUnit Finished (Shell Exit Code: 0) -+PHPUnit Finished (Shell Exit Code: 1) - -/home/matteo/OSS/phpunit/tests/end-to-end/metadata/targeting-traits-with-coversclass-attribute-is-deprecated.phpt:28 -/home/matteo/OSS/phpunit/src/Framework/TestSuite.php:369 -/home/matteo/OSS/phpunit/src/TextUI/TestRunner.php:62 -/home/matteo/OSS/phpunit/src/TextUI/Application.php:200 - - - targeting-traits-with-usesclass-attribute-is-deprecated.phptFailed asserting that string matches format description. ---- Expected -+++ Actual -@@ @@ - PHPUnit Started (PHPUnit 11.2-g0c2333363 using PHP 8.2.17 (cli) on Linux) - Test Runner Configured - Test Suite Loaded (1 test) -+Test Runner Triggered Warning (No code coverage driver available) - Event Facade Sealed - Test Runner Started - Test Suite Sorted -@@ @@ - Test Preparation Started (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithUsesClassTest::testSomething) - Test Prepared (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithUsesClassTest::testSomething) - Test Passed (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithUsesClassTest::testSomething) --Test Runner Triggered Deprecation (Targeting a trait such as PHPUnit\TestFixture\CoveredTrait with #[UsesClass] is deprecated, please refactor your test to use #[UsesTrait] instead.) - Test Finished (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithUsesClassTest::testSomething) - Test Suite Finished (PHPUnit\DeprecatedAnnotationsTestFixture\TraitTargetedWithUsesClassTest, 1 test) - Test Runner Execution Finished - Test Runner Finished --PHPUnit Finished (Shell Exit Code: 0) -+PHPUnit Finished (Shell Exit Code: 1) - -/home/matteo/OSS/phpunit/tests/end-to-end/metadata/targeting-traits-with-usesclass-attribute-is-deprecated.phpt:28 -/home/matteo/OSS/phpunit/src/Framework/TestSuite.php:369 -/home/matteo/OSS/phpunit/src/TextUI/TestRunner.php:62 -/home/matteo/OSS/phpunit/src/TextUI/Application.php:200 - - - - - - - - - - - - - - - - - - - diff --git a/__tests__/fixtures/python-xunit-pytest.xml b/__tests__/fixtures/python-xunit-pytest.xml deleted file mode 100644 index fcb044a..0000000 --- a/__tests__/fixtures/python-xunit-pytest.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - /Users/mike/Projects/python-test/tests/test_lib.py:20: skipped - - - - def test_always_fail(): - > assert False - E assert False - - tests/test_lib.py:25: AssertionError - - - - - - - def test_error(): - > raise Exception("error") - E Exception: error - - tests/test_lib.py:32: Exception - - - - - - - - - - diff --git a/__tests__/fixtures/python-xunit-unittest.xml b/__tests__/fixtures/python-xunit-unittest.xml deleted file mode 100644 index ecc67d4..0000000 --- a/__tests__/fixtures/python-xunit-unittest.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/__tests__/fixtures/test-errors/jest/files.txt b/__tests__/fixtures/test-errors/jest/files.txt deleted file mode 100644 index 486856e..0000000 --- a/__tests__/fixtures/test-errors/jest/files.txt +++ /dev/null @@ -1,3 +0,0 @@ -libs/bar.spec.ts -libs/foo.spec.ts -tsconfig.json diff --git a/__tests__/fixtures/test-errors/jest/jest-test-results.xml b/__tests__/fixtures/test-errors/jest/jest-test-results.xml deleted file mode 100644 index bc65075..0000000 --- a/__tests__/fixtures/test-errors/jest/jest-test-results.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - ● Test suite failed to run - - tsconfig.json:13:3 - error TS6258: 'typeRoots' should be set inside the 'compilerOptions' object of the config json file - - 13 "typeRoots": ["./src/lib/types", "./node_modules/@types"], - ~~~~~~~~~~~ - - - - - - ● Test suite failed to run - - tsconfig.json:13:3 - error TS6258: 'typeRoots' should be set inside the 'compilerOptions' object of the config json file - - 13 "typeRoots": ["./src/lib/types", "./node_modules/@types"], - ~~~~~~~~~~~ - - - - diff --git a/__tests__/github-workflow-run-context.test.ts b/__tests__/github-workflow-run-context.test.ts deleted file mode 100644 index 7c2ead6..0000000 --- a/__tests__/github-workflow-run-context.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import * as github from '@actions/github' -import {getCheckRunContext} from '../src/utils/github-utils' - -describe('GitHub workflow_run context resolution', () => { - const originalContext = { - eventName: github.context.eventName, - payload: github.context.payload, - runId: github.context.runId, - sha: github.context.sha - } - - afterEach(() => { - github.context.eventName = originalContext.eventName - github.context.payload = originalContext.payload - github.context.runId = originalContext.runId - github.context.sha = originalContext.sha - }) - - it('uses the head SHA from the PR matching workflow_run.head_branch when CI is triggered by a PR update', () => { - github.context.eventName = 'workflow_run' - github.context.payload = { - workflow_run: { - id: 9001, - head_branch: 'feature/refactor-reporter', - head_sha: 'merge-commit-sha-should-not-win', - pull_requests: [ - {head: {ref: 'main', sha: 'sha-from-main-pr'}}, - {head: {ref: 'feature/refactor-reporter', sha: 'sha-from-updated-pr-head'}} - ] - } - } as typeof github.context.payload - - expect(getCheckRunContext()).toEqual({ - sha: 'sha-from-updated-pr-head', - runId: 9001 - }) - }) - - it('falls back to the first associated PR head SHA when no PR branch matches (common with merge queue / detached branches)', () => { - github.context.eventName = 'workflow_run' - github.context.payload = { - workflow_run: { - id: 9002, - head_branch: 'gh-readonly-queue/main/pr-742-123456', - head_sha: 'merge-queue-commit-sha', - pull_requests: [ - {head: {ref: 'feature/billing-fix', sha: 'sha-from-first-associated-pr'}}, - {head: {ref: 'feature/other-pr', sha: 'sha-from-second-associated-pr'}} - ] - } - } as typeof github.context.payload - - expect(getCheckRunContext()).toEqual({ - sha: 'sha-from-first-associated-pr', - runId: 9002 - }) - }) - - it('uses workflow_run.head_sha when the run comes from a branch push with no related pull request', () => { - github.context.eventName = 'workflow_run' - github.context.payload = { - workflow_run: { - id: 9003, - head_branch: 'main', - head_sha: 'sha-from-push-on-main', - pull_requests: [] - } - } as typeof github.context.payload - - expect(getCheckRunContext()).toEqual({ - sha: 'sha-from-push-on-main', - runId: 9003 - }) - }) - - it('throws a clear error when webhook payload has neither PR head SHA nor workflow_run.head_sha', () => { - github.context.eventName = 'workflow_run' - github.context.payload = { - workflow_run: { - id: 9004, - head_branch: 'feature/missing-sha', - pull_requests: [{head: {ref: 'feature/missing-sha'}}] - } - } as typeof github.context.payload - - expect(() => getCheckRunContext()).toThrow('Unable to resolve SHA from workflow_run (no PR head.sha or head_sha)') - }) -}) diff --git a/__tests__/golang-json.test.ts b/__tests__/golang-json.test.ts index 0672d03..0bfdd86 100644 --- a/__tests__/golang-json.test.ts +++ b/__tests__/golang-json.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {GolangJsonParser} from '../src/parsers/golang-json/golang-json-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {GolangJsonParser} from '../src/parsers/golang-json/golang-json-parser' +import {ParseOptions} from '../src/test-parser' +import {getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('golang-json tests', () => { it('report from ./reports/dotnet test results matches snapshot', async () => { diff --git a/__tests__/java-junit.test.ts b/__tests__/java-junit.test.ts index 540e2b2..83a7dec 100644 --- a/__tests__/java-junit.test.ts +++ b/__tests__/java-junit.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {JavaJunitParser} from '../src/parsers/java-junit/java-junit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {JavaJunitParser} from '../src/parsers/java-junit/java-junit-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('java-junit tests', () => { it('produces empty test run result when there are no test cases', async () => { @@ -78,46 +73,6 @@ describe('java-junit tests', () => { fs.writeFileSync(outputPath, report) }) - it('report from testmo/junitxml basic example matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'java', 'junit4-basic.xml') - const outputPath = path.join(__dirname, '__outputs__', 'junit-basic.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JavaJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('report from testmo/junitxml complete example matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'java', 'junit4-complete.xml') - const outputPath = path.join(__dirname, '__outputs__', 'junit-complete.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JavaJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - it('parses empty failures in test results', async () => { const fixturePath = path.join(__dirname, 'fixtures', 'external', 'java', 'empty_failures.xml') const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) diff --git a/__tests__/java-stack-trace-element-parser.test.ts b/__tests__/java-stack-trace-element-parser.test.ts index ff98a03..6fe1ac2 100644 --- a/__tests__/java-stack-trace-element-parser.test.ts +++ b/__tests__/java-stack-trace-element-parser.test.ts @@ -1,4 +1,4 @@ -import {parseStackTraceElement} from '../src/parsers/java-junit/java-stack-trace-element-parser.js' +import {parseStackTraceElement} from '../src/parsers/java-junit/java-stack-trace-element-parser' describe('parseStackTraceLine tests', () => { it('empty line is not parsed', async () => { diff --git a/__tests__/jest-junit.test.ts b/__tests__/jest-junit.test.ts index 86fd8a8..f4b8335 100644 --- a/__tests__/jest-junit.test.ts +++ b/__tests__/jest-junit.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {JestJunitParser} from '../src/parsers/jest-junit/jest-junit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {JestJunitParser} from '../src/parsers/jest-junit/jest-junit-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('jest-junit tests', () => { it('produces empty test run result when there are no test cases in the testsuites element', async () => { @@ -212,166 +207,4 @@ describe('jest-junit tests', () => { // Report should have the title as the first line expect(report).toMatch(/^# My Custom Title\n/) }) - - it('report can be collapsed when configured', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - const report = getReport([result], { - ...DEFAULT_OPTIONS, - collapsed: 'always' - }) - // Report should include collapsible details - expect(report).toContain('
Expand for details') - expect(report).toContain('
') - }) - - it('report is not collapsed when configured to never', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - const report = getReport([result], { - ...DEFAULT_OPTIONS, - collapsed: 'never' - }) - // Report should not include collapsible details - expect(report).not.toContain('
Expand for details') - expect(report).not.toContain('
') - }) - - it('report auto-collapses when all tests pass', async () => { - // Test with a fixture that has all passing tests (no failures) - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit-eslint.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify this fixture has no failures - expect(result.failed).toBe(0) - - const report = getReport([result], { - ...DEFAULT_OPTIONS, - collapsed: 'auto' - }) - - // Should collapse when all tests pass - expect(report).toContain('
Expand for details') - expect(report).toContain('
') - }) - - it('report does not auto-collapse when tests fail', async () => { - // Test with a fixture that has failing tests - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify this fixture has failures - expect(result.failed).toBeGreaterThan(0) - - const report = getReport([result], { - ...DEFAULT_OPTIONS, - collapsed: 'auto' - }) - - // Should not collapse when there are failures - expect(report).not.toContain('
Expand for details') - expect(report).not.toContain('
') - }) - - it('report includes the short summary', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - const shortSummary = '1 passed, 4 failed and 1 skipped' - const report = getReport([result], DEFAULT_OPTIONS, shortSummary) - // Report should have the title as the first line - expect(report).toMatch(/^## 1 passed, 4 failed and 1 skipped\n/) - }) - - it('report includes a custom report title and short summary', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'jest-junit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - const shortSummary = '1 passed, 4 failed and 1 skipped' - const report = getReport( - [result], - { - ...DEFAULT_OPTIONS, - reportTitle: 'My Custom Title' - }, - shortSummary - ) - // Report should have the title as the first line - expect(report).toMatch(/^# My Custom Title\n## 1 passed, 4 failed and 1 skipped\n/) - }) - - it('jest testsuite errors example test results matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'test-errors', 'jest', 'jest-test-results.xml') - const trackedFilesPath = path.join(__dirname, 'fixtures', 'test-errors', 'jest', 'files.txt') - const outputPath = path.join(__dirname, '__outputs__', 'jest-test-errors-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const trackedFiles = fs.readFileSync(trackedFilesPath, {encoding: 'utf8'}).split(/\n\r?/g) - const opts: ParseOptions = { - parseErrors: true, - trackedFiles - //workDir: '/home/dorny/dorny/jest/' - } - - const parser = new JestJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) }) diff --git a/__tests__/mocha-json.test.ts b/__tests__/mocha-json.test.ts index b2379cb..1272962 100644 --- a/__tests__/mocha-json.test.ts +++ b/__tests__/mocha-json.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {MochaJsonParser} from '../src/parsers/mocha-json/mocha-json-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {MochaJsonParser} from '../src/parsers/mocha-json/mocha-json-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('mocha-json tests', () => { it('produces empty test run result when there are no test cases', async () => { diff --git a/__tests__/phpunit-junit.test.ts b/__tests__/phpunit-junit.test.ts deleted file mode 100644 index 20986d6..0000000 --- a/__tests__/phpunit-junit.test.ts +++ /dev/null @@ -1,352 +0,0 @@ -import * as fs from 'fs' -import * as path from 'path' - -import {PhpunitJunitParser} from '../src/parsers/phpunit-junit/phpunit-junit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) - -describe('phpunit-junit tests', () => { - it('produces empty test run result when there are no test cases', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'empty', 'phpunit-empty.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result.tests).toBe(0) - expect(result.result).toBe('success') - }) - - it('report from phpunit test results matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'phpunit', 'phpunit.xml') - const outputPath = path.join(__dirname, '__outputs__', 'phpunit-test-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('parses nested test suites correctly', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'phpunit', 'phpunit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Should have 4 test suites (3 nested ones plus the parent with direct testcases) - expect(result.suites.length).toBe(4) - - // Verify suite names - const suiteNames = result.suites.map(s => s.name) - expect(suiteNames).toContain('PHPUnit\\Event\\CollectingDispatcherTest') - expect(suiteNames).toContain('PHPUnit\\Event\\DeferringDispatcherTest') - expect(suiteNames).toContain('PHPUnit\\Event\\DirectDispatcherTest') - expect(suiteNames).toContain('CLI Arguments') - - // Verify total test count - expect(result.tests).toBe(12) - expect(result.passed).toBe(10) - expect(result.failed).toBe(2) - }) - - it('extracts error details from failures', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'phpunit', 'phpunit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find the CLI Arguments suite which has failures - const cliSuite = result.suites.find(s => s.name === 'CLI Arguments') - expect(cliSuite).toBeDefined() - - // Get the failed tests - const failedTests = cliSuite!.groups.flatMap(g => g.tests).filter(t => t.result === 'failed') - expect(failedTests.length).toBe(2) - - // Verify error details are captured - for (const test of failedTests) { - expect(test.error).toBeDefined() - expect(test.error!.details).toContain('Failed asserting that string matches format description') - } - }) - - it('maps absolute paths to tracked files for annotations', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'phpunit', 'phpunit-paths.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [ - 'src/Fake.php', - 'src/Other.php', - 'src/Paren.php', - 'src/Win.php', - 'src/WinParen.php', - 'tests/Sample.phpt' - ] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - const suite = result.suites.find(s => s.name === 'SampleSuite') - expect(suite).toBeDefined() - - const tests = suite!.groups.flatMap(g => g.tests) - const fileFailure = tests.find(t => t.name === 'testFailure') - expect(fileFailure).toBeDefined() - expect(fileFailure!.error).toBeDefined() - expect(fileFailure!.error!.path).toBe('src/Fake.php') - expect(fileFailure!.error!.line).toBe(42) - - const stringFailure = tests.find(t => t.name === 'testStringFailure') - expect(stringFailure).toBeDefined() - expect(stringFailure!.error).toBeDefined() - expect(stringFailure!.error!.path).toBe('src/Other.php') - expect(stringFailure!.error!.line).toBe(10) - - const parenFailure = tests.find(t => t.name === 'testParenFailure') - expect(parenFailure).toBeDefined() - expect(parenFailure!.error).toBeDefined() - expect(parenFailure!.error!.path).toBe('src/Paren.php') - expect(parenFailure!.error!.line).toBe(123) - - const windowsFailure = tests.find(t => t.name === 'testWindowsFailure') - expect(windowsFailure).toBeDefined() - expect(windowsFailure!.error).toBeDefined() - expect(windowsFailure!.error!.path).toBe('src/Win.php') - expect(windowsFailure!.error!.line).toBe(77) - - const windowsParenFailure = tests.find(t => t.name === 'testWindowsParenFailure') - expect(windowsParenFailure).toBeDefined() - expect(windowsParenFailure!.error).toBeDefined() - expect(windowsParenFailure!.error!.path).toBe('src/WinParen.php') - expect(windowsParenFailure!.error!.line).toBe(88) - - const phptFailure = tests.find(t => t.name === 'testPhptFailure') - expect(phptFailure).toBeDefined() - expect(phptFailure!.error).toBeDefined() - expect(phptFailure!.error!.path).toBe('tests/Sample.phpt') - expect(phptFailure!.error!.line).toBe(12) - }) - - it('parses junit-basic.xml with nested suites and failure', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'junit-basic.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify test counts - expect(result.tests).toBe(9) - expect(result.passed).toBe(8) - expect(result.failed).toBe(1) - expect(result.result).toBe('failed') - - // Verify suites - should have Tests.Registration, Tests.Authentication.Login, and Tests.Authentication - expect(result.suites.length).toBe(3) - - const suiteNames = result.suites.map(s => s.name) - expect(suiteNames).toContain('Tests.Registration') - expect(suiteNames).toContain('Tests.Authentication.Login') - expect(suiteNames).toContain('Tests.Authentication') - - // Verify the Registration suite has 3 tests - const registrationSuite = result.suites.find(s => s.name === 'Tests.Registration') - expect(registrationSuite).toBeDefined() - const registrationTests = registrationSuite!.groups.flatMap(g => g.tests) - expect(registrationTests.length).toBe(3) - - // Verify the Authentication suite has 3 direct tests (not counting nested suite) - const authSuite = result.suites.find(s => s.name === 'Tests.Authentication') - expect(authSuite).toBeDefined() - const authTests = authSuite!.groups.flatMap(g => g.tests) - expect(authTests.length).toBe(3) - - // Verify the Login nested suite has 3 tests - const loginSuite = result.suites.find(s => s.name === 'Tests.Authentication.Login') - expect(loginSuite).toBeDefined() - const loginTests = loginSuite!.groups.flatMap(g => g.tests) - expect(loginTests.length).toBe(3) - - // Verify failure is captured - const failedTest = authTests.find(t => t.name === 'testCase9') - expect(failedTest).toBeDefined() - expect(failedTest!.result).toBe('failed') - expect(failedTest!.error).toBeDefined() - expect(failedTest!.error!.message).toBe('AssertionError: Assertion error message') - }) - - it('parses phpcheckstyle-phpunit.xml with deeply nested suites', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'phpcheckstyle-phpunit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify test counts from the XML: tests="30", failures="2" - expect(result.tests).toBe(30) - expect(result.passed).toBe(28) - expect(result.failed).toBe(2) - expect(result.result).toBe('failed') - - // Verify the number of test suites extracted (leaf suites with testcases) - // CommentsTest, DeprecationTest, GoodTest, IndentationTest, MetricsTest, - // NamingTest, OptimizationTest, OtherTest, PHPTagsTest, ProhibitedTest, - // StrictCompareTest, UnusedTest = 12 suites - expect(result.suites.length).toBe(12) - - const suiteNames = result.suites.map(s => s.name) - expect(suiteNames).toContain('CommentsTest') - expect(suiteNames).toContain('GoodTest') - expect(suiteNames).toContain('IndentationTest') - expect(suiteNames).toContain('OtherTest') - }) - - it('extracts test data from phpcheckstyle-phpunit.xml', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'phpcheckstyle-phpunit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find the CommentsTest suite - const commentsSuite = result.suites.find(s => s.name === 'CommentsTest') - expect(commentsSuite).toBeDefined() - - // Verify tests are extracted correctly - const tests = commentsSuite!.groups.flatMap(g => g.tests) - expect(tests.length).toBe(3) - - const testGoodDoc = tests.find(t => t.name === 'testGoodDoc') - expect(testGoodDoc).toBeDefined() - expect(testGoodDoc!.result).toBe('success') - }) - - it('captures failure details from phpcheckstyle-phpunit.xml', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'phpcheckstyle-phpunit.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find the OtherTest suite which has failures - const otherSuite = result.suites.find(s => s.name === 'OtherTest') - expect(otherSuite).toBeDefined() - - const failedTests = otherSuite!.groups.flatMap(g => g.tests).filter(t => t.result === 'failed') - expect(failedTests.length).toBe(2) - - // Verify failure details - const testOther = failedTests.find(t => t.name === 'testOther') - expect(testOther).toBeDefined() - expect(testOther!.error).toBeDefined() - expect(testOther!.error!.details).toContain('We expect 20 warnings') - expect(testOther!.error!.details).toContain('Failed asserting that 19 matches expected 20') - - const testException = failedTests.find(t => t.name === 'testException') - expect(testException).toBeDefined() - expect(testException!.error).toBeDefined() - expect(testException!.error!.details).toContain('We expect 1 error') - }) - - it('report from junit-basic.xml matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'junit-basic.xml') - const outputPath = path.join(__dirname, '__outputs__', 'phpunit-junit-basic-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('report from phpcheckstyle-phpunit.xml matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'external', 'phpunit', 'phpcheckstyle-phpunit.xml') - const outputPath = path.join(__dirname, '__outputs__', 'phpunit-phpcheckstyle-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new PhpunitJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) -}) diff --git a/__tests__/python-xunit.test.ts b/__tests__/python-xunit.test.ts deleted file mode 100644 index 4e8cef3..0000000 --- a/__tests__/python-xunit.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import * as fs from 'fs' -import * as path from 'path' - -import {PythonXunitParser} from '../src/parsers/python-xunit/python-xunit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) - -const defaultOpts: ParseOptions = { - parseErrors: true, - trackedFiles: [] -} - -describe('python-xunit unittest report', () => { - const fixturePath = path.join(__dirname, 'fixtures', 'python-xunit-unittest.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - const outputPath = path.join(__dirname, '__outputs__', 'python-xunit-unittest.md') - - it('report from python test results matches snapshot', async () => { - const trackedFiles = ['tests/test_lib.py'] - const opts: ParseOptions = { - ...defaultOpts, - trackedFiles - } - - const parser = new PythonXunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('report does not include a title by default', async () => { - const parser = new PythonXunitParser(defaultOpts) - const result = await parser.parse(filePath, fileContent) - const report = getReport([result]) - // Report should have the badge as the first line - expect(report).toMatch(/^!\[Tests failed]/) - }) - - it.each([ - ['empty string', ''], - ['space', ' '], - ['tab', '\t'], - ['newline', '\n'] - ])('report does not include a title when configured value is %s', async (_, reportTitle) => { - const parser = new PythonXunitParser(defaultOpts) - const result = await parser.parse(filePath, fileContent) - const report = getReport([result], { - ...DEFAULT_OPTIONS, - reportTitle - }) - // Report should have the badge as the first line - expect(report).toMatch(/^!\[Tests failed]/) - }) - - it('report includes a custom report title', async () => { - const parser = new PythonXunitParser(defaultOpts) - const result = await parser.parse(filePath, fileContent) - const report = getReport([result], { - ...DEFAULT_OPTIONS, - reportTitle: 'My Custom Title' - }) - // Report should have the title as the first line - expect(report).toMatch(/^# My Custom Title\n/) - }) -}) - -describe('python-xunit pytest report', () => { - const fixturePath = path.join(__dirname, 'fixtures', 'python-xunit-pytest.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - const outputPath = path.join(__dirname, '__outputs__', 'python-xunit-pytest.md') - - it('report from python test results matches snapshot', async () => { - const trackedFiles = ['tests/test_lib.py'] - const opts: ParseOptions = { - ...defaultOpts, - trackedFiles - } - - const parser = new PythonXunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) -}) diff --git a/__tests__/report/get-report.test.ts b/__tests__/report/get-report.test.ts deleted file mode 100644 index 560f849..0000000 --- a/__tests__/report/get-report.test.ts +++ /dev/null @@ -1,278 +0,0 @@ -import {DEFAULT_OPTIONS, getBadge, getReport, ReportOptions} from '../../src/report/get-report.js' -import {TestCaseResult, TestGroupResult, TestRunResult, TestSuiteResult} from '../../src/test-results.js' - -describe('getBadge', () => { - describe('URI encoding with special characters', () => { - it('generates correct URI with simple badge title', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'tests' - } - const badge = getBadge(5, 0, 1, options) - expect(badge).toBe( - '![Tests passed successfully](https://img.shields.io/badge/tests-5%20passed%2C%201%20skipped-success)' - ) - }) - - it('handles badge title with single hyphen', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'unit-tests' - } - const badge = getBadge(3, 0, 0, options) - // The hyphen in the badge title should be encoded as -- - expect(badge).toBe('![Tests passed successfully](https://img.shields.io/badge/unit--tests-3%20passed-success)') - }) - - it('handles badge title with multiple hyphens', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'integration-api-tests' - } - const badge = getBadge(10, 0, 0, options) - // All hyphens in the title should be encoded as -- - expect(badge).toBe( - '![Tests passed successfully](https://img.shields.io/badge/integration--api--tests-10%20passed-success)' - ) - }) - - it('handles badge title with multiple underscores', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'my_integration_test' - } - const badge = getBadge(10, 0, 0, options) - // All underscores in the title should be encoded as __ - expect(badge).toBe( - '![Tests passed successfully](https://img.shields.io/badge/my__integration__test-10%20passed-success)' - ) - }) - - it('handles badge title with version format containing hyphen', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'MariaDb 12.0-ubi database tests' - } - const badge = getBadge(1, 0, 0, options) - // The hyphen in "12.0-ubi" should be encoded as -- - expect(badge).toBe( - '![Tests passed successfully](https://img.shields.io/badge/MariaDb%2012.0--ubi%20database%20tests-1%20passed-success)' - ) - }) - - it('handles badge title with dots and hyphens', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'v1.2.3-beta-test' - } - const badge = getBadge(4, 1, 0, options) - expect(badge).toBe( - '![Tests failed](https://img.shields.io/badge/v1.2.3--beta--test-4%20passed%2C%201%20failed-critical)' - ) - }) - - it('preserves structural hyphens between label and message', () => { - const options: ReportOptions = { - ...DEFAULT_OPTIONS, - badgeTitle: 'test-suite' - } - const badge = getBadge(2, 3, 1, options) - // The URI should have literal hyphens separating title-message-color - expect(badge).toBe( - '![Tests failed](https://img.shields.io/badge/test--suite-2%20passed%2C%203%20failed%2C%201%20skipped-critical)' - ) - }) - }) - - describe('generates test outcome as color name for imgshields', () => { - it('uses success color when all tests pass', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(5, 0, 0, options) - expect(badge).toContain('-success)') - }) - - it('uses critical color when tests fail', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(5, 2, 0, options) - expect(badge).toContain('-critical)') - }) - - it('uses yellow color when no tests found', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(0, 0, 0, options) - expect(badge).toContain('-yellow)') - }) - }) - - describe('badge message composition', () => { - it('includes only passed count when no failures or skips', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(5, 0, 0, options) - expect(badge).toBe('![Tests passed successfully](https://img.shields.io/badge/tests-5%20passed-success)') - }) - - it('includes passed and failed counts', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(5, 2, 0, options) - expect(badge).toBe('![Tests failed](https://img.shields.io/badge/tests-5%20passed%2C%202%20failed-critical)') - }) - - it('includes passed, failed and skipped counts', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(5, 2, 1, options) - expect(badge).toBe( - '![Tests failed](https://img.shields.io/badge/tests-5%20passed%2C%202%20failed%2C%201%20skipped-critical)' - ) - }) - - it('uses "none" message when no tests', () => { - const options: ReportOptions = {...DEFAULT_OPTIONS} - const badge = getBadge(0, 0, 0, options) - expect(badge).toBe('![Tests passed successfully](https://img.shields.io/badge/tests-none-yellow)') - }) - }) -}) - -describe('getReport', () => { - // Helper function to create test results - function createTestResult(path: string, passed: number, failed: number, skipped: number): TestRunResult { - const tests: TestCaseResult[] = [] - for (let i = 0; i < passed; i++) { - tests.push(new TestCaseResult(`passed-test-${i}`, 'success', 100)) - } - for (let i = 0; i < failed; i++) { - tests.push( - new TestCaseResult(`failed-test-${i}`, 'failed', 100, { - details: 'Test failed', - message: 'Assertion error' - }) - ) - } - for (let i = 0; i < skipped; i++) { - tests.push(new TestCaseResult(`skipped-test-${i}`, 'skipped', 0)) - } - - const group = new TestGroupResult('test-group', tests) - const suite = new TestSuiteResult('test-suite', [group]) - return new TestRunResult(path, [suite]) - } - - describe('list-files parameter', () => { - const results = [ - createTestResult('passing-file.spec.ts', 5, 0, 0), - createTestResult('failing-file.spec.ts', 3, 2, 1), - createTestResult('passing-with-skipped-file.spec.ts', 8, 0, 2) - ] - - it('shows all files when list-files is "all"', () => { - const report = getReport(results, { - ...DEFAULT_OPTIONS, - listFiles: 'all', - listSuites: 'none', - listTests: 'none' - }) - - expect(report).toContain('|Report|Passed|Failed|Skipped|Time|') - expect(report).toContain('passing-file.spec.ts') - expect(report).toContain('failing-file.spec.ts') - expect(report).toContain('passing-with-skipped-file.spec.ts') - }) - - it('shows only failed files when list-files is "failed"', () => { - const report = getReport(results, { - ...DEFAULT_OPTIONS, - listFiles: 'failed', - listSuites: 'none', - listTests: 'none' - }) - - expect(report).toContain('|Report|Passed|Failed|Skipped|Time|') - expect(report).not.toContain('passing-file.spec.ts') - expect(report).toContain('failing-file.spec.ts') - expect(report).not.toContain('passing-with-skipped-file.spec.ts') - }) - - it('shows no file details when list-files is "none"', () => { - const report = getReport(results, { - ...DEFAULT_OPTIONS, - listFiles: 'none', - listSuites: 'none', - listTests: 'none' - }) - - expect(report).toContain('![') - expect(report).not.toContain('|Report|Passed|Failed|Skipped|Time|') - expect(report).not.toContain('passing-file.spec.ts') - expect(report).not.toContain('failing-file.spec.ts') - expect(report).not.toContain('passing-with-skipped-file.spec.ts') - }) - - it('does not show an empty summary table when list-files is "none" and only-summary is enabled', () => { - const report = getReport(results, { - ...DEFAULT_OPTIONS, - listFiles: 'none', - listSuites: 'all', - onlySummary: true, - listTests: 'none' - }) - - expect(report).toContain('![') - expect(report).not.toContain('|Report|Passed|Failed|Skipped|Time|') - expect(report).not.toContain('passing-file.spec.ts') - expect(report).not.toContain('failing-file.spec.ts') - expect(report).not.toContain('passing-with-skipped-file.spec.ts') - }) - - it('works correctly with list-suites and list-tests when list-files is "failed"', () => { - const report = getReport(results, { - ...DEFAULT_OPTIONS, - listFiles: 'failed', - listSuites: 'all', - listTests: 'all' - }) - - expect(report).toContain('|Report|Passed|Failed|Skipped|Time|') - expect(report).not.toContain('passing-file.spec.ts') - expect(report).toContain('failing-file.spec.ts') - expect(report).not.toContain('passing-with-skipped-file.spec.ts') - // Should show suite details for the failed file - expect(report).toContain('test-suite') - }) - - it('filters correctly when all files pass and list-files is "failed"', () => { - const allPassingResults = [ - createTestResult('passing-file-1.spec.ts', 5, 0, 0), - createTestResult('passing-file-2.spec.ts', 8, 0, 2) - ] - - const report = getReport(allPassingResults, { - ...DEFAULT_OPTIONS, - listFiles: 'failed', - listSuites: 'all', - listTests: 'none' - }) - - expect(report).not.toContain('passing-file-1.spec.ts') - expect(report).not.toContain('passing-file-2.spec.ts') - expect(report).toContain('![') - expect(report).not.toContain('|Report|Passed|Failed|Skipped|Time|') - }) - - it('filters correctly when all files fail and list-files is "failed"', () => { - const allFailingResults = [ - createTestResult('failing-file-1.spec.ts', 0, 5, 0), - createTestResult('failing-file-2.spec.ts', 1, 2, 1) - ] - - const report = getReport(allFailingResults, { - ...DEFAULT_OPTIONS, - listFiles: 'failed', - listSuites: 'all', - listTests: 'none' - }) - - expect(report).toContain('failing-file-1.spec.ts') - expect(report).toContain('failing-file-2.spec.ts') - }) - }) -}) diff --git a/__tests__/rspec-json.test.ts b/__tests__/rspec-json.test.ts index e37ef09..787420b 100644 --- a/__tests__/rspec-json.test.ts +++ b/__tests__/rspec-json.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {RspecJsonParser} from '../src/parsers/rspec-json/rspec-json-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {RspecJsonParser} from '../src/parsers/rspec-json/rspec-json-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('rspec-json tests', () => { it('produces empty test run result when there are no test cases', async () => { diff --git a/__tests__/swift-xunit.test.ts b/__tests__/swift-xunit.test.ts index c46b695..9f063ee 100644 --- a/__tests__/swift-xunit.test.ts +++ b/__tests__/swift-xunit.test.ts @@ -1,15 +1,10 @@ import * as fs from 'fs' import * as path from 'path' -import {SwiftXunitParser} from '../src/parsers/swift-xunit/swift-xunit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) +import {SwiftXunitParser} from '../src/parsers/swift-xunit/swift-xunit-parser' +import {ParseOptions} from '../src/test-parser' +import {DEFAULT_OPTIONS, getReport} from '../src/report/get-report' +import {normalizeFilePath} from '../src/utils/path-utils' describe('swift-xunit tests', () => { it('report from swift test results matches snapshot', async () => { diff --git a/__tests__/tester-junit.test.ts b/__tests__/tester-junit.test.ts deleted file mode 100644 index 2743365..0000000 --- a/__tests__/tester-junit.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -import * as fs from 'fs' -import * as path from 'path' - -import {NetteTesterJunitParser} from '../src/parsers/tester-junit/tester-junit-parser.js' -import {ParseOptions} from '../src/test-parser.js' -import {getReport} from '../src/report/get-report.js' -import {normalizeFilePath} from '../src/utils/path-utils.js' - -import {fileURLToPath} from 'url' -import {dirname} from 'path' -const __filename = fileURLToPath(import.meta.url) -const __dirname = dirname(__filename) - -describe('tester-junit tests', () => { - it('produces empty test run result when there are no test cases', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'empty', 'phpunit-empty.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result.tests).toBe(0) - expect(result.result).toBe('success') - }) - - it('report from tester-v1.7-report.xml matches snapshot', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const outputPath = path.join(__dirname, '__outputs__', 'tester-v1.7-test-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('parses tester-v1.7-report.xml correctly', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify test counts from XML: tests="65" errors="1" skipped="3" - expect(result.tests).toBe(65) - expect(result.failed).toBe(1) - expect(result.skipped).toBe(3) - expect(result.passed).toBe(61) - - // Verify suite name uses file name - expect(result.suites.length).toBe(1) - expect(result.suites[0].name).toBe('tester-v1.7-report.xml') - }) - - it('groups tests by directory structure', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Get all group names - const groupNames = result.suites[0].groups.map(g => g.name) - - // Verify expected directory groups exist - expect(groupNames).toContain('tests/Framework') - expect(groupNames).toContain('tests/CodeCoverage') - expect(groupNames).toContain('tests/Runner') - expect(groupNames).toContain('tests/RunnerOutput') - }) - - it('parses test names with method suffixes correctly', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find the Framework group which has tests with method suffixes - const frameworkGroup = result.suites[0].groups.find(g => g.name === 'tests/Framework') - expect(frameworkGroup).toBeDefined() - - // Find tests with method suffixes - const testWithMethod = frameworkGroup!.tests.find(t => t.name.includes('::testSimple')) - expect(testWithMethod).toBeDefined() - expect(testWithMethod!.name).toBe('Assert.equal.recursive.phpt::testSimple') - }) - - it('parses complex test names from BootstrapFormRenderer-report.xml', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'BootstrapFormRenderer-report.xml') - const outputPath = path.join(__dirname, '__outputs__', 'tester-bootstrap-test-results.md') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Verify test counts: 4 tests, all passed - expect(result.tests).toBe(4) - expect(result.passed).toBe(4) - expect(result.failed).toBe(0) - expect(result.skipped).toBe(0) - - // Verify suite name - expect(result.suites[0].name).toBe('BootstrapFormRenderer-report.xml') - - // All tests should have method names - const allTests = result.suites[0].groups.flatMap(g => g.tests) - expect(allTests.every(t => t.name.includes('::'))).toBe(true) - expect(allTests.some(t => t.name.includes('::testRenderingBasics'))).toBe(true) - expect(allTests.some(t => t.name.includes('::testRenderingIndividual'))).toBe(true) - - expect(result).toMatchSnapshot() - - const report = getReport([result]) - fs.mkdirSync(path.dirname(outputPath), {recursive: true}) - fs.writeFileSync(outputPath, report) - }) - - it('extracts error details from failures', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find the failed test - const allTests = result.suites[0].groups.flatMap(g => g.tests) - const failedTests = allTests.filter(t => t.result === 'failed') - - expect(failedTests.length).toBe(1) - - // Verify error details are captured - const failedTest = failedTests[0] - expect(failedTest.error).toBeDefined() - expect(failedTest.error!.details).toContain('Failed:') - expect(failedTest.error!.details).toContain('multiple-fails') - }) - - it('correctly identifies skipped tests', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find skipped tests - const allTests = result.suites[0].groups.flatMap(g => g.tests) - const skippedTests = allTests.filter(t => t.result === 'skipped') - - expect(skippedTests.length).toBe(3) - - // Verify some known skipped tests - expect(skippedTests.some(t => t.name.includes('Dumper.toPhp.php7.phpt'))).toBe(true) - expect(skippedTests.some(t => t.name.includes('Collector.start.phpt'))).toBe(true) - }) - - it('parses test with description prefix correctly', async () => { - const fixturePath = path.join(__dirname, 'fixtures', 'nette-tester', 'tester-v1.7-report.xml') - const filePath = normalizeFilePath(path.relative(__dirname, fixturePath)) - const fileContent = fs.readFileSync(fixturePath, {encoding: 'utf8'}) - - const opts: ParseOptions = { - parseErrors: true, - trackedFiles: [] - } - - const parser = new NetteTesterJunitParser(opts) - const result = await parser.parse(filePath, fileContent) - - // Find test with description prefix - const allTests = result.suites[0].groups.flatMap(g => g.tests) - // The test name is generated from the basename, and the description is shown in parentheses - const testWithDescription = allTests.find(t => t.name.includes('Prevent loop')) - - expect(testWithDescription).toBeDefined() - expect(testWithDescription!.name).toContain('Prevent loop') - expect(testWithDescription!.name).toContain('TestCase.ownErrorHandler.phpt') - }) -}) diff --git a/__tests__/utils/parse-utils.test.ts b/__tests__/utils/parse-utils.test.ts index dd21ee5..83689ef 100644 --- a/__tests__/utils/parse-utils.test.ts +++ b/__tests__/utils/parse-utils.test.ts @@ -1,4 +1,4 @@ -import {parseNetDuration} from '../../src/utils/parse-utils.js' +import {parseNetDuration} from '../../src/utils/parse-utils' describe('parseNetDuration', () => { it('returns 0 for 00:00:00', () => { @@ -32,6 +32,6 @@ describe('parseNetDuration', () => { }) it('throws when string has invalid format', () => { - expect(() => parseNetDuration('12:34:56 not a duration')).toThrow(/^Invalid format/) + expect(() => parseNetDuration('12:34:56 not a duration')).toThrowError(/^Invalid format/) }) }) diff --git a/__tests__/utils/slugger.test.ts b/__tests__/utils/slugger.test.ts deleted file mode 100644 index e2ad534..0000000 --- a/__tests__/utils/slugger.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import {DEFAULT_OPTIONS} from '../../src/report/get-report.js' -import {slug} from '../../src/utils/slugger.js' - -describe('slugger', () => { - it('adds prefix from report options to generated slug', () => { - const result = slug('r0s1', { - ...DEFAULT_OPTIONS, - slugPrefix: 'prefix-' - }) - - expect(result).toEqual({ - id: 'user-content-prefix-r0s1', - link: '#user-content-prefix-r0s1' - }) - }) - - it('sanitizes custom prefix using existing slug normalization', () => { - const result = slug('r0', { - ...DEFAULT_OPTIONS, - slugPrefix: ' my /custom_prefix?.' - }) - - expect(result).toEqual({ - id: 'user-content-my-customprefix-r0', - link: '#user-content-my-customprefix-r0' - }) - }) -}) diff --git a/action.yml b/action.yml index fb11227..ec4772f 100644 --- a/action.yml +++ b/action.yml @@ -1,5 +1,6 @@ name: Test Reporter -description: Displays test results from popular testing frameworks directly in GitHub +description: | + Shows test results in GitHub UI: .NET (xUnit, NUnit, MSTest), Dart, Flutter, Java (JUnit), JavaScript (JEST, Mocha) author: Michal Dorner inputs: artifact: @@ -28,13 +29,9 @@ inputs: - dotnet-nunit - dotnet-trx - flutter-json - - golang-json - java-junit - jest-junit - mocha-json - - tester-junit - - phpunit-junit - - python-xunit - rspec-json - swift-xunit required: true @@ -54,14 +51,6 @@ inputs: - none required: false default: 'all' - list-files: - description: | - Limits which test result files are listed. Supported options: - - all - - failed - - none - required: false - default: 'all' max-annotations: description: | Limits number of created annotations with error message and stack trace captured during test execution. @@ -79,10 +68,6 @@ inputs: working-directory: description: Relative path under $GITHUB_WORKSPACE where the repository was checked out required: false - report-title: - description: Title for the test report summary - required: false - default: '' only-summary: description: | Allows you to generate only the summary. @@ -100,14 +85,6 @@ inputs: description: Customize badge title required: false default: 'tests' - collapsed: - description: | - Controls whether test report details are collapsed or expanded. Supported options: - - auto: Collapse only if all tests pass (default behavior) - - always: Always collapse the report details - - never: Always expand the report details - required: false - default: 'auto' token: description: GitHub Access Token required: false @@ -130,12 +107,8 @@ outputs: description: Check run URL url_html: description: Check run URL HTML - summary_file: - description: Path to a file containing the generated test report summary in Markdown format - slug_prefix: - description: Random prefix added to generated report anchor slugs for this action run runs: - using: 'node24' + using: 'node20' main: 'dist/index.js' branding: color: blue diff --git a/dist/index.js b/dist/index.js index 8f0b42f..6596a6f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,11 +1,11 @@ -import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; -/******/ var __webpack_modules__ = ({ +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ -/***/ 9659: +/***/ 4548: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); @@ -39,6 +39,2788 @@ var __importStar = (this && this.__importStar) || (function () { return result; }; })(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ArtifactProvider = void 0; +const core = __importStar(__nccwpck_require__(7484)); +const github = __importStar(__nccwpck_require__(3228)); +const adm_zip_1 = __importDefault(__nccwpck_require__(1316)); +const picomatch_1 = __importDefault(__nccwpck_require__(4006)); +const github_utils_1 = __nccwpck_require__(6667); +class ArtifactProvider { + octokit; + artifact; + name; + pattern; + sha; + runId; + token; + artifactNameMatch; + fileNameMatch; + getReportName; + constructor(octokit, artifact, name, pattern, sha, runId, token) { + this.octokit = octokit; + this.artifact = artifact; + this.name = name; + this.pattern = pattern; + this.sha = sha; + this.runId = runId; + this.token = token; + if (this.artifact.startsWith('/')) { + const endIndex = this.artifact.lastIndexOf('/'); + const rePattern = this.artifact.substring(1, endIndex); + const reOpts = this.artifact.substring(endIndex + 1); + const re = new RegExp(rePattern, reOpts); + this.artifactNameMatch = (str) => re.test(str); + this.getReportName = (str) => { + const match = str.match(re); + if (match === null) { + throw new Error(`Artifact name '${str}' does not match regex ${this.artifact}`); + } + let reportName = this.name; + for (let i = 1; i < match.length; i++) { + reportName = reportName.replace(new RegExp(`\\$${i}`, 'g'), match[i]); + } + return reportName; + }; + } + else { + this.artifactNameMatch = (str) => str === this.artifact; + this.getReportName = () => this.name; + } + this.fileNameMatch = (0, picomatch_1.default)(pattern); + } + async load() { + const result = {}; + const resp = await this.octokit.rest.actions.listWorkflowRunArtifacts({ + ...github.context.repo, + run_id: this.runId + }); + if (resp.data.artifacts.length === 0) { + core.warning(`No artifacts found in run ${this.runId}`); + return {}; + } + const artifacts = resp.data.artifacts.filter(a => this.artifactNameMatch(a.name)); + if (artifacts.length === 0) { + core.warning(`No artifact matches ${this.artifact}`); + return {}; + } + for (const art of artifacts) { + const fileName = `${art.name}.zip`; + await (0, github_utils_1.downloadArtifact)(this.octokit, art.id, fileName, this.token); + core.startGroup(`Reading archive ${fileName}`); + try { + const reportName = this.getReportName(art.name); + core.info(`Report name: ${reportName}`); + const files = []; + const zip = new adm_zip_1.default(fileName); + for (const entry of zip.getEntries()) { + const file = entry.entryName; + if (entry.isDirectory) { + core.info(`Skipping ${file}: entry is a directory`); + continue; + } + if (!this.fileNameMatch(file)) { + core.info(`Skipping ${file}: filename does not match pattern`); + continue; + } + const content = zip.readAsText(entry); + files.push({ file, content }); + core.info(`Read ${file}: ${content.length} chars`); + } + if (result[reportName]) { + result[reportName].push(...files); + } + else { + result[reportName] = files; + } + } + finally { + core.endGroup(); + } + } + return result; + } + async listTrackedFiles() { + return (0, github_utils_1.listFiles)(this.octokit, this.sha); + } +} +exports.ArtifactProvider = ArtifactProvider; + + +/***/ }), + +/***/ 922: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LocalFileProvider = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const fast_glob_1 = __importDefault(__nccwpck_require__(5648)); +const git_1 = __nccwpck_require__(5454); +class LocalFileProvider { + name; + pattern; + constructor(name, pattern) { + this.name = name; + this.pattern = pattern; + } + async load() { + const result = []; + for (const pat of this.pattern) { + const paths = await (0, fast_glob_1.default)(pat, { dot: true }); + for (const file of paths) { + const content = await fs.promises.readFile(file, { encoding: 'utf8' }); + result.push({ file, content }); + } + } + return { [this.name]: result }; + } + async listTrackedFiles() { + return (0, git_1.listFiles)(); + } +} +exports.LocalFileProvider = LocalFileProvider; + + +/***/ }), + +/***/ 5915: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(7484)); +const github = __importStar(__nccwpck_require__(3228)); +const artifact_provider_1 = __nccwpck_require__(4548); +const local_file_provider_1 = __nccwpck_require__(922); +const get_annotations_1 = __nccwpck_require__(4400); +const get_report_1 = __nccwpck_require__(7070); +const dart_json_parser_1 = __nccwpck_require__(1254); +const dotnet_nunit_parser_1 = __nccwpck_require__(6394); +const dotnet_trx_parser_1 = __nccwpck_require__(1658); +const golang_json_parser_1 = __nccwpck_require__(5162); +const java_junit_parser_1 = __nccwpck_require__(8342); +const jest_junit_parser_1 = __nccwpck_require__(1042); +const mocha_json_parser_1 = __nccwpck_require__(5402); +const rspec_json_parser_1 = __nccwpck_require__(9768); +const swift_xunit_parser_1 = __nccwpck_require__(7330); +const path_utils_1 = __nccwpck_require__(9132); +const github_utils_1 = __nccwpck_require__(6667); +async function main() { + try { + const testReporter = new TestReporter(); + await testReporter.run(); + } + catch (error) { + if (error instanceof Error) + core.setFailed(error); + else + core.setFailed(JSON.stringify(error)); + } +} +class TestReporter { + artifact = core.getInput('artifact', { required: false }); + name = core.getInput('name', { required: true }); + path = core.getInput('path', { required: true }); + pathReplaceBackslashes = core.getInput('path-replace-backslashes', { required: false }) === 'true'; + reporter = core.getInput('reporter', { required: true }); + listSuites = core.getInput('list-suites', { required: true }); + listTests = core.getInput('list-tests', { required: true }); + maxAnnotations = parseInt(core.getInput('max-annotations', { required: true })); + failOnError = core.getInput('fail-on-error', { required: true }) === 'true'; + failOnEmpty = core.getInput('fail-on-empty', { required: true }) === 'true'; + workDirInput = core.getInput('working-directory', { required: false }); + onlySummary = core.getInput('only-summary', { required: false }) === 'true'; + useActionsSummary = core.getInput('use-actions-summary', { required: false }) === 'true'; + badgeTitle = core.getInput('badge-title', { required: false }); + reportTitle = core.getInput('report-title', { required: false }); + token = core.getInput('token', { required: true }); + octokit; + context = (0, github_utils_1.getCheckRunContext)(); + constructor() { + this.octokit = github.getOctokit(this.token); + if (this.listSuites !== 'all' && this.listSuites !== 'failed' && this.listSuites !== 'none') { + core.setFailed(`Input parameter 'list-suites' has invalid value`); + return; + } + if (this.listTests !== 'all' && this.listTests !== 'failed' && this.listTests !== 'none') { + core.setFailed(`Input parameter 'list-tests' has invalid value`); + return; + } + if (isNaN(this.maxAnnotations) || this.maxAnnotations < 0 || this.maxAnnotations > 50) { + core.setFailed(`Input parameter 'max-annotations' has invalid value`); + return; + } + } + async run() { + if (this.workDirInput) { + core.info(`Changing directory to '${this.workDirInput}'`); + process.chdir(this.workDirInput); + } + core.info(`Check runs will be created with SHA=${this.context.sha}`); + // Split path pattern by ',' and optionally convert all backslashes to forward slashes + // fast-glob (micromatch) always interprets backslashes as escape characters instead of directory separators + const pathsList = this.path.split(','); + const pattern = this.pathReplaceBackslashes ? pathsList.map(path_utils_1.normalizeFilePath) : pathsList; + const inputProvider = this.artifact + ? new artifact_provider_1.ArtifactProvider(this.octokit, this.artifact, this.name, pattern, this.context.sha, this.context.runId, this.token) + : new local_file_provider_1.LocalFileProvider(this.name, pattern); + const parseErrors = this.maxAnnotations > 0; + const trackedFiles = parseErrors ? await inputProvider.listTrackedFiles() : []; + const workDir = this.artifact ? undefined : (0, path_utils_1.normalizeDirPath)(process.cwd(), true); + if (parseErrors) + core.info(`Found ${trackedFiles.length} files tracked by GitHub`); + const options = { + workDir, + trackedFiles, + parseErrors + }; + core.info(`Using test report parser '${this.reporter}'`); + const parser = this.getParser(this.reporter, options); + const results = []; + const input = await inputProvider.load(); + for (const [reportName, files] of Object.entries(input)) { + try { + core.startGroup(`Creating test report ${reportName}`); + const tr = await this.createReport(parser, reportName, files); + results.push(...tr); + } + finally { + core.endGroup(); + } + } + const isFailed = results.some(tr => tr.result === 'failed'); + const conclusion = isFailed ? 'failure' : 'success'; + const passed = results.reduce((sum, tr) => sum + tr.passed, 0); + const failed = results.reduce((sum, tr) => sum + tr.failed, 0); + const skipped = results.reduce((sum, tr) => sum + tr.skipped, 0); + const time = results.reduce((sum, tr) => sum + tr.time, 0); + core.setOutput('conclusion', conclusion); + core.setOutput('passed', passed); + core.setOutput('failed', failed); + core.setOutput('skipped', skipped); + core.setOutput('time', time); + if (this.failOnError && isFailed) { + core.setFailed(`Failed test were found and 'fail-on-error' option is set to ${this.failOnError}`); + return; + } + if (results.length === 0 && this.failOnEmpty) { + core.setFailed(`No test report files were found`); + return; + } + } + async createReport(parser, name, files) { + if (files.length === 0) { + core.warning(`No file matches path ${this.path}`); + return []; + } + core.info(`Processing test results for check run ${name}`); + const results = []; + for (const { file, content } of files) { + try { + const tr = await parser.parse(file, content); + results.push(tr); + } + catch (error) { + core.error(`Processing test results from ${file} failed`); + throw error; + } + } + const { listSuites, listTests, onlySummary, useActionsSummary, badgeTitle, reportTitle } = this; + const passed = results.reduce((sum, tr) => sum + tr.passed, 0); + const failed = results.reduce((sum, tr) => sum + tr.failed, 0); + const skipped = results.reduce((sum, tr) => sum + tr.skipped, 0); + const shortSummary = `${passed} passed, ${failed} failed and ${skipped} skipped `; + let baseUrl = ''; + if (this.useActionsSummary) { + const summary = (0, get_report_1.getReport)(results, { + listSuites, + listTests, + baseUrl, + onlySummary, + useActionsSummary, + badgeTitle, + reportTitle + }); + core.info('Summary content:'); + core.info(summary); + core.summary.addRaw(`# ${shortSummary}`); + await core.summary.addRaw(summary).write(); + } + else { + core.info(`Creating check run ${name}`); + const createResp = await this.octokit.rest.checks.create({ + head_sha: this.context.sha, + name, + status: 'in_progress', + output: { + title: name, + summary: '' + }, + ...github.context.repo + }); + core.info('Creating report summary'); + baseUrl = createResp.data.html_url; + const summary = (0, get_report_1.getReport)(results, { + listSuites, + listTests, + baseUrl, + onlySummary, + useActionsSummary, + badgeTitle, + reportTitle + }); + core.info('Creating annotations'); + const annotations = (0, get_annotations_1.getAnnotations)(results, this.maxAnnotations); + const isFailed = this.failOnError && results.some(tr => tr.result === 'failed'); + const conclusion = isFailed ? 'failure' : 'success'; + core.info(`Updating check run conclusion (${conclusion}) and output`); + const resp = await this.octokit.rest.checks.update({ + check_run_id: createResp.data.id, + conclusion, + status: 'completed', + output: { + title: shortSummary, + summary, + annotations + }, + ...github.context.repo + }); + core.info(`Check run create response: ${resp.status}`); + core.info(`Check run URL: ${resp.data.url}`); + core.info(`Check run HTML: ${resp.data.html_url}`); + core.setOutput('url', resp.data.url); + core.setOutput('url_html', resp.data.html_url); + } + return results; + } + getParser(reporter, options) { + switch (reporter) { + case 'dart-json': + return new dart_json_parser_1.DartJsonParser(options, 'dart'); + case 'dotnet-nunit': + return new dotnet_nunit_parser_1.DotnetNunitParser(options); + case 'dotnet-trx': + return new dotnet_trx_parser_1.DotnetTrxParser(options); + case 'golang-json': + return new golang_json_parser_1.GolangJsonParser(options); + case 'flutter-json': + return new dart_json_parser_1.DartJsonParser(options, 'flutter'); + case 'java-junit': + return new java_junit_parser_1.JavaJunitParser(options); + case 'jest-junit': + return new jest_junit_parser_1.JestJunitParser(options); + case 'mocha-json': + return new mocha_json_parser_1.MochaJsonParser(options); + case 'rspec-json': + return new rspec_json_parser_1.RspecJsonParser(options); + case 'swift-xunit': + return new swift_xunit_parser_1.SwiftXunitParser(options); + default: + throw new Error(`Input variable 'reporter' is set to invalid value '${reporter}'`); + } + } +} +main(); + + +/***/ }), + +/***/ 1254: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DartJsonParser = void 0; +const path_utils_1 = __nccwpck_require__(9132); +const dart_json_types_1 = __nccwpck_require__(7064); +const test_results_1 = __nccwpck_require__(613); +class TestRun { + path; + suites; + success; + time; + constructor(path, suites, success, time) { + this.path = path; + this.suites = suites; + this.success = success; + this.time = time; + } +} +class TestSuite { + suite; + constructor(suite) { + this.suite = suite; + } + groups = {}; +} +class TestGroup { + group; + constructor(group) { + this.group = group; + } + tests = []; +} +class TestCase { + testStart; + constructor(testStart) { + this.testStart = testStart; + this.groupId = testStart.test.groupIDs[testStart.test.groupIDs.length - 1]; + } + groupId; + print = []; + testDone; + error; + get result() { + if (this.testDone?.skipped) { + return 'skipped'; + } + if (this.testDone?.result === 'success') { + return 'success'; + } + if (this.testDone?.result === 'error' || this.testDone?.result === 'failure') { + return 'failed'; + } + return undefined; + } + get time() { + return this.testDone !== undefined ? this.testDone.time - this.testStart.time : 0; + } +} +class DartJsonParser { + options; + sdk; + assumedWorkDir; + constructor(options, sdk) { + this.options = options; + this.sdk = sdk; + } + async parse(path, content) { + const tr = this.getTestRun(path, content); + const result = this.getTestRunResult(tr); + return Promise.resolve(result); + } + getTestRun(path, content) { + const lines = content.split(/\n\r?/g); + const events = lines + .map((str, i) => { + if (str.trim() === '') { + return null; + } + try { + return JSON.parse(str); + } + catch (e) { + const errWithCol = e; + const col = errWithCol.columnNumber !== undefined ? `:${errWithCol.columnNumber}` : ''; + throw new Error(`Invalid JSON at ${path}:${i + 1}${col}\n\n${e}`); + } + }) + .filter(evt => evt != null); + let success = false; + let totalTime = 0; + const suites = {}; + const tests = {}; + for (const evt of events) { + if ((0, dart_json_types_1.isSuiteEvent)(evt)) { + suites[evt.suite.id] = new TestSuite(evt.suite); + } + else if ((0, dart_json_types_1.isGroupEvent)(evt)) { + suites[evt.group.suiteID].groups[evt.group.id] = new TestGroup(evt.group); + } + else if ((0, dart_json_types_1.isTestStartEvent)(evt) && evt.test.url !== null) { + const test = new TestCase(evt); + const suite = suites[evt.test.suiteID]; + const group = suite.groups[evt.test.groupIDs[evt.test.groupIDs.length - 1]]; + group.tests.push(test); + tests[evt.test.id] = test; + } + else if ((0, dart_json_types_1.isTestDoneEvent)(evt) && tests[evt.testID]) { + tests[evt.testID].testDone = evt; + } + else if ((0, dart_json_types_1.isErrorEvent)(evt) && tests[evt.testID]) { + tests[evt.testID].error = evt; + } + else if ((0, dart_json_types_1.isMessageEvent)(evt) && tests[evt.testID]) { + tests[evt.testID].print.push(evt); + } + else if ((0, dart_json_types_1.isDoneEvent)(evt)) { + success = evt.success; + totalTime = evt.time; + } + } + return new TestRun(path, Object.values(suites), success, totalTime); + } + getTestRunResult(tr) { + const suites = tr.suites.map(s => { + return new test_results_1.TestSuiteResult(this.getRelativePath(s.suite.path), this.getGroups(s)); + }); + return new test_results_1.TestRunResult(tr.path, suites, tr.time); + } + getGroups(suite) { + const groups = Object.values(suite.groups).filter(grp => grp.tests.length > 0); + groups.sort((a, b) => (a.group.line ?? 0) - (b.group.line ?? 0)); + return groups.map(group => { + group.tests.sort((a, b) => (a.testStart.test.line ?? 0) - (b.testStart.test.line ?? 0)); + const tests = group.tests + .filter(tc => !tc.testDone?.hidden) + .map(tc => { + const error = this.getError(suite, tc); + const testName = group.group.name !== undefined && tc.testStart.test.name.startsWith(group.group.name) + ? tc.testStart.test.name.slice(group.group.name.length).trim() + : tc.testStart.test.name.trim(); + return new test_results_1.TestCaseResult(testName, tc.result, tc.time, error); + }); + return new test_results_1.TestGroupResult(group.group.name, tests); + }); + } + getError(testSuite, test) { + if (!this.options.parseErrors || !test.error) { + return undefined; + } + const { trackedFiles } = this.options; + const stackTrace = test.error?.stackTrace ?? ''; + const print = test.print + .filter(p => p.messageType === 'print') + .map(p => p.message) + .join('\n'); + const details = [print, stackTrace].filter(str => str !== '').join('\n'); + const src = this.exceptionThrowSource(details, trackedFiles); + const message = this.getErrorMessage(test.error?.error ?? '', print); + let path; + let line; + if (src !== undefined) { + path = src.path; + line = src.line; + } + else { + const testStartPath = this.getRelativePath(testSuite.suite.path); + if (trackedFiles.includes(testStartPath)) { + path = testStartPath; + line = test.testStart.test.root_line ?? test.testStart.test.line ?? undefined; + } + } + return { + path, + line, + message, + details + }; + } + getErrorMessage(message, print) { + if (this.sdk === 'flutter') { + const uselessMessageRe = /^Test failed\. See exception logs above\.\nThe test description was:/m; + const flutterPrintRe = /^══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞═+\s+(.*)\s+When the exception was thrown, this was the stack:/ms; + if (uselessMessageRe.test(message)) { + const match = print.match(flutterPrintRe); + if (match !== null) { + return match[1]; + } + } + } + return message || print; + } + exceptionThrowSource(ex, trackedFiles) { + const lines = ex.split(/\r?\n/g); + // regexp to extract file path and line number from stack trace + const dartRe = /^(?!package:)(.*)\s+(\d+):\d+\s+/; + const flutterRe = /^#\d+\s+.*\((?!package:)(.*):(\d+):\d+\)$/; + const re = this.sdk === 'dart' ? dartRe : flutterRe; + for (const str of lines) { + const match = str.match(re); + if (match !== null) { + const [_, pathStr, lineStr] = match; + const path = (0, path_utils_1.normalizeFilePath)(this.getRelativePath(pathStr)); + if (trackedFiles.includes(path)) { + const line = parseInt(lineStr); + return { path, line }; + } + } + } + } + getRelativePath(path) { + const prefix = 'file://'; + if (path.startsWith(prefix)) { + path = path.substr(prefix.length); + } + path = (0, path_utils_1.normalizeFilePath)(path); + const workDir = this.getWorkDir(path); + if (workDir !== undefined && path.startsWith(workDir)) { + path = path.substr(workDir.length); + } + return path; + } + getWorkDir(path) { + return (this.options.workDir ?? + this.assumedWorkDir ?? + (this.assumedWorkDir = (0, path_utils_1.getBasePath)(path, this.options.trackedFiles))); + } +} +exports.DartJsonParser = DartJsonParser; + + +/***/ }), + +/***/ 7064: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// reflects documentation at https://github.com/dart-lang/test/blob/master/pkgs/test/doc/json_reporter.md +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isSuiteEvent = isSuiteEvent; +exports.isGroupEvent = isGroupEvent; +exports.isTestStartEvent = isTestStartEvent; +exports.isTestDoneEvent = isTestDoneEvent; +exports.isErrorEvent = isErrorEvent; +exports.isDoneEvent = isDoneEvent; +exports.isMessageEvent = isMessageEvent; +function isSuiteEvent(event) { + return event.type === 'suite'; +} +function isGroupEvent(event) { + return event.type === 'group'; +} +function isTestStartEvent(event) { + return event.type === 'testStart'; +} +function isTestDoneEvent(event) { + return event.type === 'testDone'; +} +function isErrorEvent(event) { + return event.type === 'error'; +} +function isDoneEvent(event) { + return event.type === 'done'; +} +function isMessageEvent(event) { + return event.type === 'print'; +} + + +/***/ }), + +/***/ 6394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DotnetNunitParser = void 0; +const xml2js_1 = __nccwpck_require__(758); +const node_utils_1 = __nccwpck_require__(5384); +const path_utils_1 = __nccwpck_require__(9132); +const test_results_1 = __nccwpck_require__(613); +class DotnetNunitParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const ju = await this.getNunitReport(path, content); + return this.getTestRunResult(path, ju); + } + async getNunitReport(path, content) { + try { + return (await (0, xml2js_1.parseStringPromise)(content)); + } + catch (e) { + throw new Error(`Invalid XML at ${path}\n\n${e}`); + } + } + getTestRunResult(path, nunit) { + const suites = []; + const time = parseFloat(nunit['test-run'].$.duration) * 1000; + this.populateTestCasesRecursive(suites, [], nunit['test-run']['test-suite']); + return new test_results_1.TestRunResult(path, suites, time); + } + populateTestCasesRecursive(result, suitePath, testSuites) { + if (testSuites === undefined) { + return; + } + for (const suite of testSuites) { + suitePath.push(suite); + this.populateTestCasesRecursive(result, suitePath, suite['test-suite']); + const testcases = suite['test-case']; + if (testcases !== undefined) { + for (const testcase of testcases) { + this.addTestCase(result, suitePath, testcase); + } + } + suitePath.pop(); + } + } + addTestCase(result, suitePath, testCase) { + // The last suite in the suite path is the "group". + // The rest are concatenated together to form the "suite". + // But ignore "Theory" suites. + const suitesWithoutTheories = suitePath.filter(suite => suite.$.type !== 'Theory'); + const suiteName = suitesWithoutTheories + .slice(0, suitesWithoutTheories.length - 1) + .map(suite => suite.$.name) + .join('.'); + const groupName = suitesWithoutTheories[suitesWithoutTheories.length - 1].$.name; + let existingSuite = result.find(existingSuite => existingSuite.name === suiteName); + if (existingSuite === undefined) { + existingSuite = new test_results_1.TestSuiteResult(suiteName, []); + result.push(existingSuite); + } + let existingGroup = existingSuite.groups.find(existingGroup => existingGroup.name === groupName); + if (existingGroup === undefined) { + existingGroup = new test_results_1.TestGroupResult(groupName, []); + existingSuite.groups.push(existingGroup); + } + existingGroup.tests.push(new test_results_1.TestCaseResult(testCase.$.name, this.getTestExecutionResult(testCase), parseFloat(testCase.$.duration) * 1000, this.getTestCaseError(testCase))); + } + getTestExecutionResult(test) { + if (test.$.result === 'Failed' || test.failure) + return 'failed'; + if (test.$.result === 'Skipped') + return 'skipped'; + return 'success'; + } + getTestCaseError(tc) { + if (!this.options.parseErrors || !tc.failure || tc.failure.length === 0) { + return undefined; + } + const details = tc.failure[0]; + let path; + let line; + if (details['stack-trace'] !== undefined && details['stack-trace'].length > 0) { + const src = (0, node_utils_1.getExceptionSource)(details['stack-trace'][0], this.options.trackedFiles, file => this.getRelativePath(file)); + if (src) { + path = src.path; + line = src.line; + } + } + return { + path, + line, + message: details.message && details.message.length > 0 ? details.message[0] : '', + details: details['stack-trace'] && details['stack-trace'].length > 0 ? details['stack-trace'][0] : '' + }; + } + getRelativePath(path) { + path = (0, path_utils_1.normalizeFilePath)(path); + const workDir = this.getWorkDir(path); + if (workDir !== undefined && path.startsWith(workDir)) { + path = path.substr(workDir.length); + } + return path; + } + getWorkDir(path) { + return (this.options.workDir ?? + this.assumedWorkDir ?? + (this.assumedWorkDir = (0, path_utils_1.getBasePath)(path, this.options.trackedFiles))); + } +} +exports.DotnetNunitParser = DotnetNunitParser; + + +/***/ }), + +/***/ 1658: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DotnetTrxParser = void 0; +const xml2js_1 = __nccwpck_require__(758); +const path_utils_1 = __nccwpck_require__(9132); +const parse_utils_1 = __nccwpck_require__(9633); +const test_results_1 = __nccwpck_require__(613); +class TestClass { + name; + constructor(name) { + this.name = name; + } + tests = []; +} +class Test { + name; + outcome; + duration; + error; + constructor(name, outcome, duration, error) { + this.name = name; + this.outcome = outcome; + this.duration = duration; + this.error = error; + } + get result() { + switch (this.outcome) { + case 'Passed': + return 'success'; + case 'NotExecuted': + return 'skipped'; + case 'Failed': + return 'failed'; + } + } +} +class DotnetTrxParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const trx = await this.getTrxReport(path, content); + const tc = this.getTestClasses(trx); + const tr = this.getTestRunResult(path, trx, tc); + tr.sort(true); + return tr; + } + async getTrxReport(path, content) { + try { + return (await (0, xml2js_1.parseStringPromise)(content)); + } + catch (e) { + throw new Error(`Invalid XML at ${path}\n\n${e}`); + } + } + getTestClasses(trx) { + if (trx.TestRun.TestDefinitions === undefined || trx.TestRun.Results === undefined || + !trx.TestRun.TestDefinitions.some(td => td.UnitTest && Array.isArray(td.UnitTest))) { + return []; + } + const unitTests = {}; + for (const td of trx.TestRun.TestDefinitions) { + for (const ut of td.UnitTest) { + unitTests[ut.$.id] = ut; + } + } + const unitTestsResults = trx.TestRun.Results.flatMap(r => r.UnitTestResult).flatMap(result => ({ + result, + test: unitTests[result.$.testId] + })); + const testClasses = {}; + for (const r of unitTestsResults) { + const className = r.test.TestMethod[0].$.className; + let tc = testClasses[className]; + if (tc === undefined) { + tc = new TestClass(className); + testClasses[tc.name] = tc; + } + const error = this.getErrorInfo(r.result); + const durationAttr = r.result.$.duration; + const duration = durationAttr ? (0, parse_utils_1.parseNetDuration)(durationAttr) : 0; + const resultTestName = r.result.$.testName; + const testName = resultTestName.startsWith(className) && resultTestName[className.length] === '.' + ? resultTestName.substr(className.length + 1) + : resultTestName; + const test = new Test(testName, r.result.$.outcome, duration, error); + tc.tests.push(test); + } + const result = Object.values(testClasses); + return result; + } + getTestRunResult(path, trx, testClasses) { + const times = trx.TestRun.Times[0].$; + const totalTime = (0, parse_utils_1.parseIsoDate)(times.finish).getTime() - (0, parse_utils_1.parseIsoDate)(times.start).getTime(); + const suites = testClasses.map(testClass => { + const tests = testClass.tests.map(test => { + const error = this.getError(test); + return new test_results_1.TestCaseResult(test.name, test.result, test.duration, error); + }); + const group = new test_results_1.TestGroupResult(null, tests); + return new test_results_1.TestSuiteResult(testClass.name, [group]); + }); + return new test_results_1.TestRunResult(path, suites, totalTime); + } + getErrorInfo(testResult) { + if (testResult.$.outcome !== 'Failed') { + return undefined; + } + const output = testResult.Output; + const error = output?.length > 0 && output[0].ErrorInfo?.length > 0 ? output[0].ErrorInfo[0] : undefined; + return error; + } + getError(test) { + if (!this.options.parseErrors || !test.error) { + return undefined; + } + const error = test.error; + if (!Array.isArray(error.Message) || + error.Message.length === 0 || + !Array.isArray(error.StackTrace) || + error.StackTrace.length === 0) { + return undefined; + } + const message = test.error.Message[0]; + const stackTrace = test.error.StackTrace[0]; + let path; + let line; + const src = this.exceptionThrowSource(stackTrace); + if (src) { + path = src.path; + line = src.line; + } + return { + path, + line, + message, + details: `${message}\n${stackTrace}` + }; + } + exceptionThrowSource(stackTrace) { + const lines = stackTrace.split(/\r*\n/); + const re = / in (.+):line (\d+)$/; + const { trackedFiles } = this.options; + for (const str of lines) { + const match = str.match(re); + if (match !== null) { + const [_, fileStr, lineStr] = match; + const filePath = (0, path_utils_1.normalizeFilePath)(fileStr); + const workDir = this.getWorkDir(filePath); + if (workDir) { + const file = filePath.substr(workDir.length); + if (trackedFiles.includes(file)) { + const line = parseInt(lineStr); + return { path: file, line }; + } + } + } + } + } + getWorkDir(path) { + return (this.options.workDir ?? + this.assumedWorkDir ?? + (this.assumedWorkDir = (0, path_utils_1.getBasePath)(path, this.options.trackedFiles))); + } +} +exports.DotnetTrxParser = DotnetTrxParser; + + +/***/ }), + +/***/ 5162: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GolangJsonParser = void 0; +const test_results_1 = __nccwpck_require__(613); +class GolangJsonParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const events = await this.getGolangTestEvents(path, content); + return this.getTestRunResult(path, events); + } + async getGolangTestEvents(path, content) { + return content.trim().split('\n').map((line, index) => { + try { + return JSON.parse(line); + } + catch (e) { + throw new Error(`Invalid JSON at ${path} line ${index + 1}\n\n${e}`); + } + }); + } + getTestRunResult(path, events) { + const eventGroups = new Map(); + for (const event of events) { + if (!event.Test) { + continue; + } + const k = `${event.Package}/${event.Test}`; + let g = eventGroups.get(k); + if (!g) { + g = []; + eventGroups.set(k, g); + } + g.push(event); + } + const suites = []; + for (const eventGroup of eventGroups.values()) { + const event = eventGroup[0]; + let suite = suites.find(s => s.name === event.Package); + if (!suite) { + suite = new test_results_1.TestSuiteResult(event.Package, []); + suites.push(suite); + } + if (!event.Test) { + continue; + } + let groupName; + let rest; + [groupName, ...rest] = event.Test.split('/'); + let testName = rest.join('/'); + if (!testName) { + testName = groupName; + groupName = null; + } + let group = suite.groups.find(g => g.name === groupName); + if (!group) { + group = new test_results_1.TestGroupResult(groupName, []); + suite.groups.push(group); + } + const lastEvent = eventGroup.at(-1); + const result = lastEvent.Action === 'pass' ? 'success' + : lastEvent.Action === 'skip' ? 'skipped' + : 'failed'; + if (lastEvent.Elapsed === undefined) { + throw new Error('missing elapsed on final test event'); + } + const time = lastEvent.Elapsed * 1000; + let error = undefined; + if (result !== 'success') { + const outputEvents = eventGroup + .filter(e => e.Action === 'output') + .map(e => e.Output ?? '') + // Go output prepends indentation to help group tests - remove it + .map(o => o.replace(/^ /, '')); + // First and last lines will be generic "test started" and "test finished" lines - remove them + outputEvents.splice(0, 1); + outputEvents.splice(-1, 1); + const details = outputEvents.join(''); + error = { + message: details, + details: details + }; + } + group.tests.push(new test_results_1.TestCaseResult(testName, result, time, error)); + } + return new test_results_1.TestRunResult(path, suites); + } +} +exports.GolangJsonParser = GolangJsonParser; + + +/***/ }), + +/***/ 8342: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JavaJunitParser = void 0; +const path = __importStar(__nccwpck_require__(6928)); +const xml2js_1 = __nccwpck_require__(758); +const java_stack_trace_element_parser_1 = __nccwpck_require__(8105); +const path_utils_1 = __nccwpck_require__(9132); +const test_results_1 = __nccwpck_require__(613); +class JavaJunitParser { + options; + trackedFiles; + constructor(options) { + this.options = options; + // Map to efficient lookup of all paths with given file name + this.trackedFiles = {}; + for (const filePath of options.trackedFiles) { + const fileName = path.basename(filePath); + const files = this.trackedFiles[fileName] ?? (this.trackedFiles[fileName] = []); + files.push((0, path_utils_1.normalizeFilePath)(filePath)); + } + } + async parse(filePath, content) { + const reportOrSuite = await this.getJunitReport(filePath, content); + const isReport = reportOrSuite.testsuites !== undefined; + // XML might contain: + // - multiple suites under root node + // - single as root node + let ju; + if (isReport) { + ju = reportOrSuite; + } + else { + // Make it behave the same way as if suite was inside root node + const suite = reportOrSuite.testsuite; + ju = { + testsuites: { + $: { time: suite.$.time }, + testsuite: [suite] + } + }; + } + return this.getTestRunResult(filePath, ju); + } + async getJunitReport(filePath, content) { + try { + return await (0, xml2js_1.parseStringPromise)(content); + } + catch (e) { + throw new Error(`Invalid XML at ${filePath}\n\n${e}`); + } + } + getTestRunResult(filePath, junit) { + const suites = junit.testsuites.testsuite === undefined + ? [] + : junit.testsuites.testsuite.map(ts => { + const name = ts.$.name.trim(); + const time = parseFloat(ts.$.time) * 1000; + const sr = new test_results_1.TestSuiteResult(name, this.getGroups(ts), time); + return sr; + }); + const seconds = parseFloat(junit.testsuites.$?.time); + const time = isNaN(seconds) ? undefined : seconds * 1000; + return new test_results_1.TestRunResult(filePath, suites, time); + } + getGroups(suite) { + if (suite.testcase === undefined) { + return []; + } + const groups = []; + for (const tc of suite.testcase) { + // Normally classname is same as suite name - both refer to same Java class + // Therefore it doesn't make sense to process it as a group + // and tests will be added to default group with empty name + const className = tc.$.classname === suite.$.name ? '' : tc.$.classname; + let grp = groups.find(g => g.name === className); + if (grp === undefined) { + grp = { name: className, tests: [] }; + groups.push(grp); + } + grp.tests.push(tc); + } + return groups.map(grp => { + const tests = grp.tests.map(tc => { + const name = tc.$.name.trim(); + const result = this.getTestCaseResult(tc); + const time = parseFloat(tc.$.time) * 1000; + const error = this.getTestCaseError(tc); + return new test_results_1.TestCaseResult(name, result, time, error); + }); + return new test_results_1.TestGroupResult(grp.name, tests); + }); + } + getTestCaseResult(test) { + if (test.failure || test.error) + return 'failed'; + if (test.skipped) + return 'skipped'; + return 'success'; + } + getTestCaseError(tc) { + if (!this.options.parseErrors) { + return undefined; + } + // We process and the same way + const failures = tc.failure ?? tc.error; + if (!failures) { + return undefined; + } + const failure = failures[0]; + const details = typeof failure === 'object' ? failure._ : failure; + let filePath; + let line; + if (details != null) { + const src = this.exceptionThrowSource(details); + if (src) { + filePath = src.filePath; + line = src.line; + } + } + let message; + if (typeof failure === 'object') { + message = failure.$.message; + if (failure.$?.type) { + message = failure.$.type + ': ' + message; + } + } + return { + path: filePath, + line, + details, + message + }; + } + exceptionThrowSource(stackTrace) { + const lines = stackTrace.split(/\r?\n/); + for (const str of lines) { + const stackTraceElement = (0, java_stack_trace_element_parser_1.parseStackTraceElement)(str); + if (stackTraceElement) { + const { tracePath, fileName, lineStr } = stackTraceElement; + const filePath = this.getFilePath(tracePath, fileName); + if (filePath !== undefined) { + const line = parseInt(lineStr); + return { filePath, line }; + } + } + } + } + // Stacktrace in Java doesn't contain full paths to source file. + // There are only package, file name and line. + // Assuming folder structure matches package name (as it should in Java), + // we can try to match tracked file. + getFilePath(tracePath, fileName) { + // Check if there is any tracked file with given name + const files = this.trackedFiles[fileName]; + if (files === undefined) { + return undefined; + } + // Remove class name and method name from trace. + // Take parts until first item with capital letter - package names are lowercase while class name is CamelCase. + const packageParts = tracePath.split(/\./g); + const packageIndex = packageParts.findIndex(part => part[0] <= 'Z'); + if (packageIndex !== -1) { + packageParts.splice(packageIndex, packageParts.length - packageIndex); + } + if (packageParts.length === 0) { + return undefined; + } + // Get right file + // - file name matches + // - parent folders structure must reflect the package name + for (const filePath of files) { + const dirs = path.dirname(filePath).split(/\//g); + if (packageParts.length > dirs.length) { + continue; + } + // get only N parent folders, where N = length of package name parts + if (dirs.length > packageParts.length) { + dirs.splice(0, dirs.length - packageParts.length); + } + // check if parent folder structure matches package name + const isMatch = packageParts.every((part, i) => part === dirs[i]); + if (isMatch) { + return filePath; + } + } + return undefined; + } +} +exports.JavaJunitParser = JavaJunitParser; + + +/***/ }), + +/***/ 8105: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseStackTraceElement = parseStackTraceElement; +// classloader and module name are optional: +// at //(:) +// https://github.com/eclipse-openj9/openj9/issues/11452#issuecomment-754946992 +const re = /^\s*at (\S+\/\S*\/)?(.*)\((.*):(\d+)\)$/; +function parseStackTraceElement(stackTraceLine) { + const match = stackTraceLine.match(re); + if (match !== null) { + const [_, maybeClassLoaderAndModuleNameAndVersion, tracePath, fileName, lineStr] = match; + const { classLoader, moduleNameAndVersion } = parseClassLoaderAndModule(maybeClassLoaderAndModuleNameAndVersion); + return { + classLoader, + moduleNameAndVersion, + tracePath, + fileName, + lineStr + }; + } + return undefined; +} +function parseClassLoaderAndModule(maybeClassLoaderAndModuleNameAndVersion) { + if (maybeClassLoaderAndModuleNameAndVersion) { + const res = maybeClassLoaderAndModuleNameAndVersion.split('/'); + const classLoader = res[0]; + let moduleNameAndVersion = res[1]; + if (moduleNameAndVersion === '') { + moduleNameAndVersion = undefined; + } + return { classLoader, moduleNameAndVersion }; + } + return { classLoader: undefined, moduleNameAndVersion: undefined }; +} + + +/***/ }), + +/***/ 1042: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JestJunitParser = void 0; +const xml2js_1 = __nccwpck_require__(758); +const node_utils_1 = __nccwpck_require__(5384); +const path_utils_1 = __nccwpck_require__(9132); +const test_results_1 = __nccwpck_require__(613); +class JestJunitParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const ju = await this.getJunitReport(path, content); + return this.getTestRunResult(path, ju); + } + async getJunitReport(path, content) { + try { + return (await (0, xml2js_1.parseStringPromise)(content)); + } + catch (e) { + throw new Error(`Invalid XML at ${path}\n\n${e}`); + } + } + getTestRunResult(path, junit) { + const suites = junit.testsuites.testsuite === undefined + ? [] + : junit.testsuites.testsuite.map(ts => { + const name = this.escapeCharacters(ts.$.name.trim()); + const time = parseFloat(ts.$.time) * 1000; + const sr = new test_results_1.TestSuiteResult(name, this.getGroups(ts), time); + return sr; + }); + const time = junit.testsuites.$ && parseFloat(junit.testsuites.$.time) * 1000; + return new test_results_1.TestRunResult(path, suites, time); + } + getGroups(suite) { + if (!suite.testcase) { + return []; + } + const groups = []; + for (const tc of suite.testcase) { + let grp = groups.find(g => g.describe === tc.$.classname); + if (grp === undefined) { + grp = { describe: tc.$.classname, tests: [] }; + groups.push(grp); + } + grp.tests.push(tc); + } + return groups.map(grp => { + const tests = grp.tests.map(tc => { + const name = tc.$.name.trim(); + const result = this.getTestCaseResult(tc); + const time = parseFloat(tc.$.time) * 1000; + const error = this.getTestCaseError(tc); + return new test_results_1.TestCaseResult(name, result, time, error); + }); + return new test_results_1.TestGroupResult(grp.describe, tests); + }); + } + getTestCaseResult(test) { + if (test.failure) + return 'failed'; + if (test.skipped) + return 'skipped'; + return 'success'; + } + getTestCaseError(tc) { + if (!this.options.parseErrors || !tc.failure) { + return undefined; + } + const details = typeof tc.failure[0] === 'string' ? tc.failure[0] : tc.failure[0]['_']; + let path; + let line; + const src = (0, node_utils_1.getExceptionSource)(details, this.options.trackedFiles, file => this.getRelativePath(file)); + if (src) { + path = src.path; + line = src.line; + } + return { + path, + line, + details + }; + } + getRelativePath(path) { + path = (0, path_utils_1.normalizeFilePath)(path); + const workDir = this.getWorkDir(path); + if (workDir !== undefined && path.startsWith(workDir)) { + path = path.substr(workDir.length); + } + return path; + } + getWorkDir(path) { + return (this.options.workDir ?? + this.assumedWorkDir ?? + (this.assumedWorkDir = (0, path_utils_1.getBasePath)(path, this.options.trackedFiles))); + } + escapeCharacters(s) { + return s.replace(/([<>])/g, '\\$1'); + } +} +exports.JestJunitParser = JestJunitParser; + + +/***/ }), + +/***/ 5402: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MochaJsonParser = void 0; +const test_results_1 = __nccwpck_require__(613); +const node_utils_1 = __nccwpck_require__(5384); +const path_utils_1 = __nccwpck_require__(9132); +class MochaJsonParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const mocha = this.getMochaJson(path, content); + const result = this.getTestRunResult(path, mocha); + result.sort(true); + return Promise.resolve(result); + } + getMochaJson(path, content) { + try { + return JSON.parse(content); + } + catch (e) { + throw new Error(`Invalid JSON at ${path}\n\n${e}`); + } + } + getTestRunResult(resultsPath, mocha) { + const suitesMap = {}; + const getSuite = (test) => { + const path = this.getRelativePath(test.file); + return suitesMap[path] ?? (suitesMap[path] = new test_results_1.TestSuiteResult(path, [])); + }; + for (const test of mocha.passes) { + const suite = getSuite(test); + this.processTest(suite, test, 'success'); + } + for (const test of mocha.failures) { + const suite = getSuite(test); + this.processTest(suite, test, 'failed'); + } + for (const test of mocha.pending) { + const suite = getSuite(test); + this.processTest(suite, test, 'skipped'); + } + const suites = Object.values(suitesMap); + return new test_results_1.TestRunResult(resultsPath, suites, mocha.stats.duration); + } + processTest(suite, test, result) { + const groupName = test.fullTitle !== test.title + ? test.fullTitle.substr(0, test.fullTitle.length - test.title.length).trimEnd() + : null; + let group = suite.groups.find(grp => grp.name === groupName); + if (group === undefined) { + group = new test_results_1.TestGroupResult(groupName, []); + suite.groups.push(group); + } + const error = this.getTestCaseError(test); + const testCase = new test_results_1.TestCaseResult(test.title, result, test.duration ?? 0, error); + group.tests.push(testCase); + } + getTestCaseError(test) { + const details = test.err.stack; + const message = test.err.message; + if (details === undefined) { + return undefined; + } + let path; + let line; + const src = (0, node_utils_1.getExceptionSource)(details, this.options.trackedFiles, file => this.getRelativePath(file)); + if (src) { + path = src.path; + line = src.line; + } + return { + path, + line, + message, + details + }; + } + getRelativePath(path) { + path = (0, path_utils_1.normalizeFilePath)(path); + const workDir = this.getWorkDir(path); + if (workDir !== undefined && path.startsWith(workDir)) { + path = path.substr(workDir.length); + } + return path; + } + getWorkDir(path) { + return (this.options.workDir ?? + this.assumedWorkDir ?? + (this.assumedWorkDir = (0, path_utils_1.getBasePath)(path, this.options.trackedFiles))); + } +} +exports.MochaJsonParser = MochaJsonParser; + + +/***/ }), + +/***/ 9768: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RspecJsonParser = void 0; +const test_results_1 = __nccwpck_require__(613); +class RspecJsonParser { + options; + assumedWorkDir; + constructor(options) { + this.options = options; + } + async parse(path, content) { + const mocha = this.getRspecJson(path, content); + const result = this.getTestRunResult(path, mocha); + result.sort(true); + return Promise.resolve(result); + } + getRspecJson(path, content) { + try { + return JSON.parse(content); + } + catch (e) { + throw new Error(`Invalid JSON at ${path}\n\n${e}`); + } + } + getTestRunResult(resultsPath, rspec) { + const suitesMap = {}; + const getSuite = (test) => { + const path = test.file_path; + return suitesMap[path] ?? (suitesMap[path] = new test_results_1.TestSuiteResult(path, [])); + }; + for (const test of rspec.examples) { + const suite = getSuite(test); + if (test.status === 'failed') { + this.processTest(suite, test, 'failed'); + } + else if (test.status === 'passed') { + this.processTest(suite, test, 'success'); + } + else if (test.status === 'pending') { + this.processTest(suite, test, 'skipped'); + } + } + const suites = Object.values(suitesMap); + return new test_results_1.TestRunResult(resultsPath, suites, rspec.summary.duration); + } + processTest(suite, test, result) { + const groupName = test.full_description !== test.description + ? test.full_description.substr(0, test.full_description.length - test.description.length).trimEnd() + : null; + let group = suite.groups.find(grp => grp.name === groupName); + if (group === undefined) { + group = new test_results_1.TestGroupResult(groupName, []); + suite.groups.push(group); + } + const error = this.getTestCaseError(test); + const testCase = new test_results_1.TestCaseResult(test.full_description, result, test.run_time ?? 0, error); + group.tests.push(testCase); + } + getTestCaseError(test) { + const backtrace = test.exception?.backtrace; + const message = test.exception?.message; + if (backtrace === undefined) { + return undefined; + } + let path; + let line; + const details = backtrace.join('\n'); + const src = this.getExceptionSource(backtrace); + if (src) { + path = src.path; + line = src.line; + } + return { + path, + line, + message, + details + }; + } + getExceptionSource(backtrace) { + const re = /^(.*?):(\d+):/; + for (const str of backtrace) { + const match = str.match(re); + if (match !== null) { + const [_, path, lineStr] = match; + if (path.startsWith('./')) { + const line = parseInt(lineStr); + return { path, line }; + } + } + } + return undefined; + } +} +exports.RspecJsonParser = RspecJsonParser; + + +/***/ }), + +/***/ 7330: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SwiftXunitParser = void 0; +const java_junit_parser_1 = __nccwpck_require__(8342); +class SwiftXunitParser extends java_junit_parser_1.JavaJunitParser { + options; + constructor(options) { + super(options); + this.options = options; + } +} +exports.SwiftXunitParser = SwiftXunitParser; + + +/***/ }), + +/***/ 4400: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAnnotations = getAnnotations; +const markdown_utils_1 = __nccwpck_require__(5129); +const parse_utils_1 = __nccwpck_require__(9633); +function getAnnotations(results, maxCount) { + if (maxCount === 0) { + return []; + } + // Collect errors from TestRunResults + // Merge duplicates if there are more test results files processed + const errors = []; + const mergeDup = results.length > 1; + for (const tr of results) { + for (const ts of tr.suites) { + for (const tg of ts.groups) { + for (const tc of tg.tests) { + const err = tc.error; + if (err === undefined) { + continue; + } + const path = err.path ?? tr.path; + const line = err.line ?? 0; + if (mergeDup) { + const dup = errors.find(e => path === e.path && line === e.line && err.details === e.details); + if (dup !== undefined) { + dup.testRunPaths.push(tr.path); + continue; + } + } + errors.push({ + testRunPaths: [tr.path], + suiteName: ts.name, + testName: tg.name ? `${tg.name} ► ${tc.name}` : tc.name, + details: err.details, + message: err.message ?? (0, parse_utils_1.getFirstNonEmptyLine)(err.details) ?? 'Test failed', + path, + line + }); + } + } + } + } + // Limit number of created annotations + errors.splice(maxCount + 1); + const annotations = errors.map(e => { + const message = [ + 'Failed test found in:', + e.testRunPaths.map(p => ` ${p}`).join('\n'), + 'Error:', + ident((0, markdown_utils_1.fixEol)(e.message), ' ') + ].join('\n'); + return enforceCheckRunLimits({ + path: e.path, + start_line: e.line, + end_line: e.line, + annotation_level: 'failure', + title: `${e.suiteName} ► ${e.testName}`, + raw_details: (0, markdown_utils_1.fixEol)(e.details), + message + }); + }); + return annotations; +} +function enforceCheckRunLimits(err) { + err.title = (0, markdown_utils_1.ellipsis)(err.title || '', 255); + err.message = (0, markdown_utils_1.ellipsis)(err.message, 65535); + if (err.raw_details) { + err.raw_details = (0, markdown_utils_1.ellipsis)(err.raw_details, 65535); + } + return err; +} +function ident(text, prefix) { + return text + .split(/\n/g) + .map(line => prefix + line) + .join('\n'); +} + + +/***/ }), + +/***/ 7070: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_OPTIONS = void 0; +exports.getReport = getReport; +const core = __importStar(__nccwpck_require__(7484)); +const markdown_utils_1 = __nccwpck_require__(5129); +const node_utils_1 = __nccwpck_require__(5384); +const parse_utils_1 = __nccwpck_require__(9633); +const slugger_1 = __nccwpck_require__(9537); +const MAX_REPORT_LENGTH = 65535; +const MAX_ACTIONS_SUMMARY_LENGTH = 1048576; +exports.DEFAULT_OPTIONS = { + listSuites: 'all', + listTests: 'all', + baseUrl: '', + onlySummary: false, + useActionsSummary: true, + badgeTitle: 'tests', + reportTitle: '' +}; +function getReport(results, options = exports.DEFAULT_OPTIONS) { + core.info('Generating check run summary'); + applySort(results); + const opts = { ...options }; + let lines = renderReport(results, opts); + let report = lines.join('\n'); + if (getByteLength(report) <= getMaxReportLength(options)) { + return report; + } + if (opts.listTests === 'all') { + core.info("Test report summary is too big - setting 'listTests' to 'failed'"); + opts.listTests = 'failed'; + lines = renderReport(results, opts); + report = lines.join('\n'); + if (getByteLength(report) <= getMaxReportLength(options)) { + return report; + } + } + core.warning(`Test report summary exceeded limit of ${getMaxReportLength(options)} bytes and will be trimmed`); + return trimReport(lines, options); +} +function getMaxReportLength(options = exports.DEFAULT_OPTIONS) { + return options.useActionsSummary ? MAX_ACTIONS_SUMMARY_LENGTH : MAX_REPORT_LENGTH; +} +function trimReport(lines, options) { + const closingBlock = '```'; + const errorMsg = `**Report exceeded GitHub limit of ${getMaxReportLength(options)} bytes and has been trimmed**`; + const maxErrorMsgLength = closingBlock.length + errorMsg.length + 2; + const maxReportLength = getMaxReportLength(options) - maxErrorMsgLength; + let reportLength = 0; + let codeBlock = false; + let endLineIndex = 0; + for (endLineIndex = 0; endLineIndex < lines.length; endLineIndex++) { + const line = lines[endLineIndex]; + const lineLength = getByteLength(line); + reportLength += lineLength + 1; + if (reportLength > maxReportLength) { + break; + } + if (line === '```') { + codeBlock = !codeBlock; + } + } + const reportLines = lines.slice(0, endLineIndex); + if (codeBlock) { + reportLines.push('```'); + } + reportLines.push(errorMsg); + return reportLines.join('\n'); +} +function applySort(results) { + results.sort((a, b) => a.path.localeCompare(b.path, node_utils_1.DEFAULT_LOCALE)); + for (const res of results) { + res.suites.sort((a, b) => a.name.localeCompare(b.name, node_utils_1.DEFAULT_LOCALE)); + } +} +function getByteLength(text) { + return Buffer.byteLength(text, 'utf8'); +} +function renderReport(results, options) { + const sections = []; + const reportTitle = options.reportTitle.trim(); + if (reportTitle) { + sections.push(`# ${reportTitle}`); + } + const badge = getReportBadge(results, options); + sections.push(badge); + const runs = getTestRunsReport(results, options); + sections.push(...runs); + return sections; +} +function getReportBadge(results, options) { + const passed = results.reduce((sum, tr) => sum + tr.passed, 0); + const skipped = results.reduce((sum, tr) => sum + tr.skipped, 0); + const failed = results.reduce((sum, tr) => sum + tr.failed, 0); + return getBadge(passed, failed, skipped, options); +} +function getBadge(passed, failed, skipped, options) { + const text = []; + if (passed > 0) { + text.push(`${passed} passed`); + } + if (failed > 0) { + text.push(`${failed} failed`); + } + if (skipped > 0) { + text.push(`${skipped} skipped`); + } + const message = text.length > 0 ? text.join(', ') : 'none'; + let color = 'success'; + if (failed > 0) { + color = 'critical'; + } + else if (passed === 0 && failed === 0) { + color = 'yellow'; + } + const hint = failed > 0 ? 'Tests failed' : 'Tests passed successfully'; + const uri = encodeURIComponent(`${options.badgeTitle}-${message}-${color}`); + return `![${hint}](https://img.shields.io/badge/${uri})`; +} +function getTestRunsReport(testRuns, options) { + const sections = []; + const totalFailed = testRuns.reduce((sum, tr) => sum + tr.failed, 0); + if (totalFailed === 0) { + sections.push(`
Expand for details`); + sections.push(` `); + } + if (testRuns.length > 0 || options.onlySummary) { + const tableData = testRuns + .map((tr, originalIndex) => ({ tr, originalIndex })) + .filter(({ tr }) => tr.passed > 0 || tr.failed > 0 || tr.skipped > 0) + .map(({ tr, originalIndex }) => { + const time = (0, markdown_utils_1.formatTime)(tr.time); + const name = tr.path; + const addr = options.baseUrl + makeRunSlug(originalIndex, options).link; + const nameLink = (0, markdown_utils_1.link)(name, addr); + const passed = tr.passed > 0 ? `${tr.passed} ${markdown_utils_1.Icon.success}` : ''; + const failed = tr.failed > 0 ? `${tr.failed} ${markdown_utils_1.Icon.fail}` : ''; + const skipped = tr.skipped > 0 ? `${tr.skipped} ${markdown_utils_1.Icon.skip}` : ''; + return [nameLink, passed, failed, skipped, time]; + }); + const resultsTable = (0, markdown_utils_1.table)(['Report', 'Passed', 'Failed', 'Skipped', 'Time'], [markdown_utils_1.Align.Left, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right], ...tableData); + sections.push(resultsTable); + } + if (options.onlySummary === false) { + const suitesReports = testRuns.map((tr, i) => getSuitesReport(tr, i, options)).flat(); + sections.push(...suitesReports); + } + if (totalFailed === 0) { + sections.push(`
`); + } + return sections; +} +function getSuitesReport(tr, runIndex, options) { + const sections = []; + const suites = options.listSuites === 'failed' ? tr.failedSuites : tr.suites; + if (options.listSuites !== 'none') { + const trSlug = makeRunSlug(runIndex, options); + const nameLink = `${tr.path}`; + const icon = getResultIcon(tr.result); + sections.push(`## ${icon}\xa0${nameLink}`); + const time = (0, markdown_utils_1.formatTime)(tr.time); + const headingLine2 = tr.tests > 0 + ? `**${tr.tests}** tests were completed in **${time}** with **${tr.passed}** passed, **${tr.failed}** failed and **${tr.skipped}** skipped.` + : 'No tests found'; + sections.push(headingLine2); + if (suites.length > 0) { + const suitesTable = (0, markdown_utils_1.table)(['Test suite', 'Passed', 'Failed', 'Skipped', 'Time'], [markdown_utils_1.Align.Left, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right, markdown_utils_1.Align.Right], ...suites.map((s, suiteIndex) => { + const tsTime = (0, markdown_utils_1.formatTime)(s.time); + const tsName = s.name; + const skipLink = options.listTests === 'none' || (options.listTests === 'failed' && s.result !== 'failed'); + const tsAddr = options.baseUrl + makeSuiteSlug(runIndex, suiteIndex, options).link; + const tsNameLink = skipLink ? tsName : (0, markdown_utils_1.link)(tsName, tsAddr); + const passed = s.passed > 0 ? `${s.passed} ${markdown_utils_1.Icon.success}` : ''; + const failed = s.failed > 0 ? `${s.failed} ${markdown_utils_1.Icon.fail}` : ''; + const skipped = s.skipped > 0 ? `${s.skipped} ${markdown_utils_1.Icon.skip}` : ''; + return [tsNameLink, passed, failed, skipped, tsTime]; + })); + sections.push(suitesTable); + } + } + if (options.listTests !== 'none') { + const tests = suites.map((ts, suiteIndex) => getTestsReport(ts, runIndex, suiteIndex, options)).flat(); + if (tests.length > 1) { + sections.push(...tests); + } + } + return sections; +} +function getTestsReport(ts, runIndex, suiteIndex, options) { + if (options.listTests === 'failed' && ts.result !== 'failed') { + return []; + } + const groups = ts.groups; + if (groups.length === 0) { + return []; + } + const sections = []; + const tsName = ts.name; + const tsSlug = makeSuiteSlug(runIndex, suiteIndex, options); + const tsNameLink = `${tsName}`; + const icon = getResultIcon(ts.result); + sections.push(`### ${icon}\xa0${tsNameLink}`); + sections.push('```'); + for (const grp of groups) { + if (grp.name) { + sections.push(grp.name); + } + const space = grp.name ? ' ' : ''; + for (const tc of grp.tests) { + const result = getResultIcon(tc.result); + sections.push(`${space}${result} ${tc.name}`); + if (tc.error) { + const lines = (tc.error.message ?? (0, parse_utils_1.getFirstNonEmptyLine)(tc.error.details)?.trim()) + ?.split(/\r?\n/g) + .map(l => '\t' + l); + if (lines) { + sections.push(...lines); + } + } + } + } + sections.push('```'); + return sections; +} +function makeRunSlug(runIndex, options) { + // use prefix to avoid slug conflicts after escaping the paths + return (0, slugger_1.slug)(`r${runIndex}`, options); +} +function makeSuiteSlug(runIndex, suiteIndex, options) { + // use prefix to avoid slug conflicts after escaping the paths + return (0, slugger_1.slug)(`r${runIndex}s${suiteIndex}`, options); +} +function getResultIcon(result) { + switch (result) { + case 'success': + return markdown_utils_1.Icon.success; + case 'skipped': + return markdown_utils_1.Icon.skip; + case 'failed': + return markdown_utils_1.Icon.fail; + default: + return ''; + } +} + + +/***/ }), + +/***/ 613: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TestCaseResult = exports.TestGroupResult = exports.TestSuiteResult = exports.TestRunResult = void 0; +const node_utils_1 = __nccwpck_require__(5384); +class TestRunResult { + path; + suites; + totalTime; + constructor(path, suites, totalTime) { + this.path = path; + this.suites = suites; + this.totalTime = totalTime; + } + get tests() { + return this.suites.reduce((sum, g) => sum + g.tests, 0); + } + get passed() { + return this.suites.reduce((sum, g) => sum + g.passed, 0); + } + get failed() { + return this.suites.reduce((sum, g) => sum + g.failed, 0); + } + get skipped() { + return this.suites.reduce((sum, g) => sum + g.skipped, 0); + } + get time() { + return this.totalTime ?? this.suites.reduce((sum, g) => sum + g.time, 0); + } + get result() { + return this.suites.some(t => t.result === 'failed') ? 'failed' : 'success'; + } + get failedSuites() { + return this.suites.filter(s => s.result === 'failed'); + } + sort(deep) { + this.suites.sort((a, b) => a.name.localeCompare(b.name, node_utils_1.DEFAULT_LOCALE)); + if (deep) { + for (const suite of this.suites) { + suite.sort(deep); + } + } + } +} +exports.TestRunResult = TestRunResult; +class TestSuiteResult { + name; + groups; + totalTime; + constructor(name, groups, totalTime) { + this.name = name; + this.groups = groups; + this.totalTime = totalTime; + } + get tests() { + return this.groups.reduce((sum, g) => sum + g.tests.length, 0); + } + get passed() { + return this.groups.reduce((sum, g) => sum + g.passed, 0); + } + get failed() { + return this.groups.reduce((sum, g) => sum + g.failed, 0); + } + get skipped() { + return this.groups.reduce((sum, g) => sum + g.skipped, 0); + } + get time() { + return this.totalTime ?? this.groups.reduce((sum, g) => sum + g.time, 0); + } + get result() { + return this.groups.some(t => t.result === 'failed') ? 'failed' : 'success'; + } + get failedGroups() { + return this.groups.filter(grp => grp.result === 'failed'); + } + sort(deep) { + this.groups.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? '', node_utils_1.DEFAULT_LOCALE)); + if (deep) { + for (const grp of this.groups) { + grp.sort(); + } + } + } +} +exports.TestSuiteResult = TestSuiteResult; +class TestGroupResult { + name; + tests; + constructor(name, tests) { + this.name = name; + this.tests = tests; + } + get passed() { + return this.tests.reduce((sum, t) => (t.result === 'success' ? sum + 1 : sum), 0); + } + get failed() { + return this.tests.reduce((sum, t) => (t.result === 'failed' ? sum + 1 : sum), 0); + } + get skipped() { + return this.tests.reduce((sum, t) => (t.result === 'skipped' ? sum + 1 : sum), 0); + } + get time() { + return this.tests.reduce((sum, t) => sum + t.time, 0); + } + get result() { + return this.tests.some(t => t.result === 'failed') ? 'failed' : 'success'; + } + get failedTests() { + return this.tests.filter(tc => tc.result === 'failed'); + } + sort() { + this.tests.sort((a, b) => a.name.localeCompare(b.name, node_utils_1.DEFAULT_LOCALE)); + } +} +exports.TestGroupResult = TestGroupResult; +class TestCaseResult { + name; + result; + time; + error; + constructor(name, result, time, error) { + this.name = name; + this.result = result; + this.time = time; + this.error = error; + } +} +exports.TestCaseResult = TestCaseResult; + + +/***/ }), + +/***/ 5454: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listFiles = listFiles; +const core = __importStar(__nccwpck_require__(7484)); +const exec_1 = __nccwpck_require__(5236); +async function listFiles() { + core.startGroup('Listing all files tracked by git'); + let output = ''; + try { + output = (await (0, exec_1.getExecOutput)('git', ['ls-files', '-z'])).stdout; + } + finally { + fixStdOutNullTermination(); + core.endGroup(); + } + return output.split('\u0000').filter(s => s.length > 0); +} +function fixStdOutNullTermination() { + // Previous command uses NULL as delimiters and output is printed to stdout. + // We have to make sure next thing written to stdout will start on new line. + // Otherwise things like ::set-output wouldn't work. + core.info(''); +} + + +/***/ }), + +/***/ 6667: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCheckRunContext = getCheckRunContext; +exports.downloadArtifact = downloadArtifact; +exports.listFiles = listFiles; +const fs_1 = __nccwpck_require__(9896); +const core = __importStar(__nccwpck_require__(7484)); +const github = __importStar(__nccwpck_require__(3228)); +const stream = __importStar(__nccwpck_require__(2203)); +const util_1 = __nccwpck_require__(9023); +const got_1 = __importDefault(__nccwpck_require__(6757)); +const asyncStream = (0, util_1.promisify)(stream.pipeline); +function getCheckRunContext() { + if (github.context.eventName === 'workflow_run') { + core.info('Action was triggered by workflow_run: using SHA and RUN_ID from triggering workflow'); + const event = github.context.payload; + if (!event.workflow_run) { + throw new Error("Event of type 'workflow_run' is missing 'workflow_run' field"); + } + return { + sha: event.workflow_run.head_commit.id, + runId: event.workflow_run.id + }; + } + const runId = github.context.runId; + if (github.context.payload.pull_request) { + core.info(`Action was triggered by ${github.context.eventName}: using SHA from head of source branch`); + const pr = github.context.payload.pull_request; + return { sha: pr.head.sha, runId }; + } + return { sha: github.context.sha, runId }; +} +async function downloadArtifact(octokit, artifactId, fileName, token) { + core.startGroup(`Downloading artifact ${fileName}`); + try { + core.info(`Artifact ID: ${artifactId}`); + const req = octokit.rest.actions.downloadArtifact.endpoint({ + ...github.context.repo, + artifact_id: artifactId, + archive_format: 'zip' + }); + const headers = { + Authorization: `Bearer ${token}` + }; + const downloadStream = got_1.default.stream(req.url, { headers }); + const fileWriterStream = (0, fs_1.createWriteStream)(fileName); + downloadStream.on('redirect', (response) => { + core.info(`Downloading ${response.headers.location}`); + }); + downloadStream.on('downloadProgress', (progress) => { + core.info(`Progress: ${progress.transferred} B`); + }); + await asyncStream(downloadStream, fileWriterStream); + } + finally { + core.endGroup(); + } +} +async function listFiles(octokit, sha) { + core.startGroup('Fetching list of tracked files from GitHub'); + try { + const commit = await octokit.rest.git.getCommit({ + commit_sha: sha, + ...github.context.repo + }); + const files = await listGitTree(octokit, commit.data.tree.sha, ''); + return files; + } + finally { + core.endGroup(); + } +} +async function listGitTree(octokit, sha, path) { + const pathLog = path ? ` at ${path}` : ''; + core.info(`Fetching tree ${sha}${pathLog}`); + let truncated = false; + let tree = await octokit.rest.git.getTree({ + recursive: 'true', + tree_sha: sha, + ...github.context.repo + }); + if (tree.data.truncated) { + truncated = true; + tree = await octokit.rest.git.getTree({ + tree_sha: sha, + ...github.context.repo + }); + } + const result = []; + for (const tr of tree.data.tree) { + const file = `${path}${tr.path}`; + if (tr.type === 'blob') { + result.push(file); + } + else if (tr.type === 'tree' && truncated) { + const files = await listGitTree(octokit, tr.sha, `${file}/`); + result.push(...files); + } + } + return result; +} + + +/***/ }), + +/***/ 5129: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Icon = exports.Align = void 0; +exports.link = link; +exports.table = table; +exports.tableEscape = tableEscape; +exports.fixEol = fixEol; +exports.ellipsis = ellipsis; +exports.formatTime = formatTime; +var Align; +(function (Align) { + Align["Left"] = ":---"; + Align["Center"] = ":---:"; + Align["Right"] = "---:"; + Align["None"] = "---"; +})(Align || (exports.Align = Align = {})); +exports.Icon = { + skip: '⚪', // ':white_circle:' + success: '✅', // ':white_check_mark:' + fail: '❌' // ':x:' +}; +function link(title, address) { + return `[${title}](${address})`; +} +function table(headers, align, ...rows) { + const headerRow = `|${headers.map(tableEscape).join('|')}|`; + const alignRow = `|${align.join('|')}|`; + const contentRows = rows.map(row => `|${row.map(tableEscape).join('|')}|`).join('\n'); + return [headerRow, alignRow, contentRows].join('\n'); +} +function tableEscape(content) { + return content.toString().replace('|', '\\|'); +} +function fixEol(text) { + return text?.replace(/\r/g, '') ?? ''; +} +function ellipsis(text, maxLength) { + if (text.length <= maxLength) { + return text; + } + return text.substr(0, maxLength - 3) + '...'; +} +function formatTime(ms) { + if (ms > 1000) { + return `${Math.round(ms / 1000)}s`; + } + return `${Math.round(ms)}ms`; +} + + +/***/ }), + +/***/ 5384: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_LOCALE = void 0; +exports.getExceptionSource = getExceptionSource; +const path_utils_1 = __nccwpck_require__(9132); +exports.DEFAULT_LOCALE = 'en-US'; +function getExceptionSource(stackTrace, trackedFiles, getRelativePath) { + const lines = stackTrace.split(/\r?\n/); + const re = /\((.*):(\d+):\d+\)$/; + for (const str of lines) { + const match = str.match(re); + if (match !== null) { + const [_, fileStr, lineStr] = match; + const filePath = (0, path_utils_1.normalizeFilePath)(fileStr); + if (filePath.startsWith('internal/') || filePath.includes('/node_modules/')) { + continue; + } + const path = getRelativePath(filePath); + if (!path) { + continue; + } + if (trackedFiles.includes(path)) { + const line = parseInt(lineStr); + return { path, line }; + } + } + } +} + + +/***/ }), + +/***/ 9633: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNetDuration = parseNetDuration; +exports.parseIsoDate = parseIsoDate; +exports.getFirstNonEmptyLine = getFirstNonEmptyLine; +function parseNetDuration(str) { + const durationRe = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)$/; + const durationMatch = str.match(durationRe); + if (durationMatch === null) { + throw new Error(`Invalid format: "${str}" is not NET duration`); + } + const [_, hourStr, minStr, secStr] = durationMatch; + return (parseInt(hourStr) * 3600 + parseInt(minStr) * 60 + parseFloat(secStr)) * 1000; +} +function parseIsoDate(str) { + const isoDateRe = /^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)$/; + if (str === undefined || !isoDateRe.test(str)) { + throw new Error(`Invalid format: "${str}" is not ISO date`); + } + return new Date(str); +} +function getFirstNonEmptyLine(stackTrace) { + const lines = stackTrace?.split(/\r?\n/g); + return lines?.find(str => !/^\s*$/.test(str)); +} + + +/***/ }), + +/***/ 9132: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.normalizeDirPath = normalizeDirPath; +exports.normalizeFilePath = normalizeFilePath; +exports.getBasePath = getBasePath; +function normalizeDirPath(path, addTrailingSlash) { + if (!path) { + return path; + } + path = normalizeFilePath(path); + if (addTrailingSlash && !path.endsWith('/')) { + path += '/'; + } + return path; +} +function normalizeFilePath(path) { + if (!path) { + return path; + } + return path.trim().replace(/\\/g, '/'); +} +function getBasePath(path, trackedFiles) { + if (trackedFiles.includes(path)) { + return ''; + } + let max = ''; + for (const file of trackedFiles) { + if (path.endsWith(file) && file.length > max.length) { + max = file; + } + } + if (max === '') { + return undefined; + } + const base = path.substr(0, path.length - max.length); + return base; +} + + +/***/ }), + +/***/ 9537: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slug = slug; +function slug(name, options) { + const slugId = name + .trim() + .replace(/_/g, '') + .replace(/[./\\]/g, '-') + .replace(/[^\w-]/g, ''); + const id = `user-content-${slugId}`; + // When using the Action Summary for display, links must include the "user-content-" prefix. + const link = options.useActionsSummary ? `#${id}` : `#${slugId}`; + return { id, link }; +} + + +/***/ }), + +/***/ 4914: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 7484: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -49,12 +2831,2099 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.HttpClientResponse = exports.HttpClientError = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -exports.getProxyUrl = getProxyUrl; -exports.isHttps = isHttps; +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(4914); +const file_command_1 = __nccwpck_require__(4753); +const utils_1 = __nccwpck_require__(302); +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const oidc_utils_1 = __nccwpck_require__(5306); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (exports.ExitCode = ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(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); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + (0, command_1.issueCommand)('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + (0, file_command_1.issueFileCommand)('PATH', inputPath); + } + else { + (0, command_1.issueCommand)('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + if (options && options.trimWhitespace === false) { + return val; + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + process.stdout.write(os.EOL); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + (0, command_1.issueCommand)('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + (0, command_1.issue)('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + (0, command_1.issue)('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(1847); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(1847); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(1976); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8968)); +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 4753: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +// For internal use, subject to change. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const crypto = __importStar(__nccwpck_require__(6982)); +const fs = __importStar(__nccwpck_require__(9896)); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); +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 (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 5306: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(4844); +const auth_1 = __nccwpck_require__(4552); +const core_1 = __nccwpck_require__(7484); +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'); + } + 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'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + 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 (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } +} +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map + +/***/ }), + +/***/ 1976: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(6928)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map + +/***/ }), + +/***/ 8968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(857)); +const exec = __importStar(__nccwpck_require__(5236)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[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 + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 1847: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(857); +const fs_1 = __nccwpck_require__(9896); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + 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 __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.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 (_a) { + 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}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * 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 __awaiter(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(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * 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(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map + +/***/ }), + +/***/ 302: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 5236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(3193); +const tr = __importStar(__nccwpck_require__(6665)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(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.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); +} +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.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); + } + }; + 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 exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map + +/***/ }), + +/***/ 6665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(857)); +const events = __importStar(__nccwpck_require__(4434)); +const child = __importStar(__nccwpck_require__(5317)); +const path = __importStar(__nccwpck_require__(6928)); +const io = __importStar(__nccwpck_require__(4994)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +const timers_1 = __nccwpck_require__(3557); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner 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]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } + } + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + 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(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + 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) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + 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 || 10000 + }; + 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 __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(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) + os.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', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } + })); + }); + } +} +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + 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; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + 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 = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = 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) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, 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 / + 1000} 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(); + } +} +//# sourceMappingURL=toolrunner.js.map + +/***/ }), + +/***/ 1648: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(9896); +const os_1 = __nccwpck_require__(857); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + 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 = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `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`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 3228: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(1648)); +const utils_1 = __nccwpck_require__(8006); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); +} +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 5156: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(4844)); +const undici_1 = __nccwpck_require__(6752); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +exports.getProxyAgentDispatcher = getProxyAgentDispatcher; +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +exports.getProxyFetch = getProxyFetch; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 8006: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(1648)); +const Utils = __importStar(__nccwpck_require__(5156)); +// octokit + plugins +const core_1 = __nccwpck_require__(1897); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(4935); +const plugin_paginate_rest_1 = __nccwpck_require__(8082); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl), + fetch: Utils.getProxyFetch(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 4552: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + 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'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + 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'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 4844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(8611)); const https = __importStar(__nccwpck_require__(5692)); -const pm = __importStar(__nccwpck_require__(3335)); +const pm = __importStar(__nccwpck_require__(4988)); const tunnel = __importStar(__nccwpck_require__(770)); const undici_1 = __nccwpck_require__(6752); var HttpCodes; @@ -104,6 +4973,7 @@ function getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } +exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, @@ -164,6 +5034,7 @@ function isHttps(requestUrl) { const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } +exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; @@ -174,7 +5045,7 @@ class HttpClient { this._maxRetries = 1; this._keepAlive = false; this._disposed = false; - this.userAgent = this._getUserAgentWithOrchestrationId(userAgent); + this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { @@ -246,39 +5117,36 @@ class HttpClient { * 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 __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { 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 __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { 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); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } - putJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { 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); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } - patchJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { 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); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); @@ -507,73 +5375,12 @@ class HttpClient { } return lowercaseKeys(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 = lowercaseKeys(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = - typeof headerValue === 'number' ? headerValue.toString() : headerValue; - } + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== undefined) { - return typeof additionalValue === 'number' - ? additionalValue.toString() - : additionalValue; - } - if (clientHeader !== undefined) { - 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 = lowercaseKeys(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 additionalValue = additionalHeaders[Headers.ContentType]; - // Return the first non-undefined value, converting numbers or arrays to strings if necessary - if (additionalValue !== undefined) { - if (typeof additionalValue === 'number') { - return String(additionalValue); - } - else if (Array.isArray(additionalValue)) { - return additionalValue.join(', '); - } - else { - return additionalValue; - } - } - if (clientHeader !== undefined) { - return clientHeader; - } - return _default; + return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; @@ -582,7 +5389,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (!useProxy) { + if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -614,12 +5421,16 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if tunneling agent isn't assigned create a new agent - if (!agent) { + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -641,7 +5452,7 @@ class HttpClient { } 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')}` + token: `${proxyUrl.username}:${proxyUrl.password}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { @@ -654,17 +5465,6 @@ class HttpClient { } return proxyAgent; } - _getUserAgentWithOrchestrationId(userAgent) { - const baseUserAgent = userAgent || 'actions/http-client'; - const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; - if (orchId) { - // Sanitize the orchestration ID to ensure it contains only valid characters - // Valid characters: 0-9, a-z, _, -, . - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; - } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -744,13 +5544,13 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 3335: +/***/ 4988: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getProxyUrl = getProxyUrl; -exports.checkBypass = checkBypass; +exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { @@ -766,17 +5566,18 @@ function getProxyUrl(reqUrl) { })(); if (proxyVar) { try { - return new DecodedURL(proxyVar); + return new URL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new DecodedURL(`http://${proxyVar}`); + return new URL(`http://${proxyVar}`); } } else { return undefined; } } +exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; @@ -820,6 +5621,7 @@ function checkBypass(reqUrl) { } return false; } +exports.checkBypass = checkBypass; function isLoopbackAddress(host) { const hostLower = host.toLowerCase(); return (hostLower === 'localhost' || @@ -827,26 +5629,510 @@ function isLoopbackAddress(host) { hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } -} //# sourceMappingURL=proxy.js.map /***/ }), +/***/ 5207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const path = __importStar(__nccwpck_require__(6928)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); +} +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); +} +exports.isDirectory = isDirectory; +/** + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). + */ +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); +} +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map + +/***/ }), + +/***/ 4994: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(2613); +const path = __importStar(__nccwpck_require__(6928)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +/** + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. + */ +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; + } + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.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 (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile(source, newDest, force); + } + }); +} +exports.cp = cp; +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.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(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); +} +exports.mv = mv; +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); +} +exports.rmRF = rmRF; +/** + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise + */ +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); +} +exports.mkdirP = mkdirP; +/** + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool + */ +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // recursive when check=true + if (check) { + const result = yield which(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 ''; + }); +} +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); +} +exports.findInPath = findInPath; +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 __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + 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()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + 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); + } + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + /***/ 2400: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; @@ -873,6 +6159,7 @@ exports.createFileSystemAdapter = createFileSystemAdapter; /***/ 2479: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; @@ -897,6 +6184,7 @@ exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_B /***/ 7198: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.scandirSync = exports.scandir = void 0; @@ -930,6 +6218,7 @@ function getSettings(settingsOrOptions = {}) { /***/ 7299: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; @@ -1041,6 +6330,7 @@ function callSuccessCallback(callback, result) { /***/ 8389: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = void 0; @@ -1061,6 +6351,7 @@ exports.joinPathSegments = joinPathSegments; /***/ 7200: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; @@ -1122,6 +6413,7 @@ exports.readdir = readdir; /***/ 2501: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(6928); @@ -1153,6 +6445,7 @@ exports["default"] = Settings; /***/ 5497: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDirentFromStats = void 0; @@ -1179,6 +6472,7 @@ exports.createDirentFromStats = createDirentFromStats; /***/ 1144: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fs = void 0; @@ -1191,6 +6485,7 @@ exports.fs = fs; /***/ 4368: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; @@ -1215,6 +6510,7 @@ exports.createFileSystemAdapter = createFileSystemAdapter; /***/ 1470: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.statSync = exports.stat = exports.Settings = void 0; @@ -1248,6 +6544,7 @@ function getSettings(settingsOrOptions = {}) { /***/ 1539: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; @@ -1291,6 +6588,7 @@ function callSuccessCallback(callback, result) { /***/ 6544: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; @@ -1321,6 +6619,7 @@ exports.read = read; /***/ 4853: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __nccwpck_require__(4368); @@ -1344,6 +6643,7 @@ exports["default"] = Settings; /***/ 9337: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; @@ -1385,6 +6685,7 @@ function getSettings(settingsOrOptions = {}) { /***/ 1936: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const async_1 = __nccwpck_require__(1906); @@ -1422,6 +6723,7 @@ function callSuccessCallback(callback, entries) { /***/ 8986: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2203); @@ -1463,6 +6765,7 @@ exports["default"] = StreamProvider; /***/ 8769: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const sync_1 = __nccwpck_require__(3431); @@ -1484,11 +6787,12 @@ exports["default"] = SyncProvider; /***/ 1906: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const events_1 = __nccwpck_require__(4434); const fsScandir = __nccwpck_require__(7198); -const fastq = __nccwpck_require__(3281); +const fastq = __nccwpck_require__(8230); const common = __nccwpck_require__(4449); const reader_1 = __nccwpck_require__(5903); class AsyncReader extends reader_1.default { @@ -1588,6 +6892,7 @@ exports["default"] = AsyncReader; /***/ 4449: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; @@ -1626,6 +6931,7 @@ exports.joinPathSegments = joinPathSegments; /***/ 5903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const common = __nccwpck_require__(4449); @@ -1644,6 +6950,7 @@ exports["default"] = Reader; /***/ 3431: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsScandir = __nccwpck_require__(7198); @@ -1710,6 +7017,7 @@ exports["default"] = SyncReader; /***/ 244: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(6928); @@ -1738,6 +7046,4276 @@ class Settings { exports["default"] = Settings; +/***/ }), + +/***/ 7864: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 1897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(index_exports); +var import_universal_user_agent = __nccwpck_require__(3843); +var import_before_after_hook = __nccwpck_require__(2732); +var import_request = __nccwpck_require__(8636); +var import_graphql = __nccwpck_require__(7); +var import_auth_token = __nccwpck_require__(7864); + +// pkg/dist-src/version.js +var VERSION = "5.2.1"; + +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var Octokit = class { + static { + this.VERSION = VERSION; + } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + } + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new import_before_after_hook.Collection(); + const requestDefaults = { + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: noop, + info: noop, + warn: consoleWarn, + error: consoleError + }, + options.log + ); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = (0, import_auth_token.createTokenAuth)(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "9.0.6"; + +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; + +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} + +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} + +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} + +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} + +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} + +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.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())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} + +// pkg/dist-src/parse.js +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} + +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} + +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 7: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(index_exports); +var import_request3 = __nccwpck_require__(8636); +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "7.1.1"; + +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(8636); + +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(8636); + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +}; + +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} + +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 8082: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/version.js +var VERSION = "9.2.2"; + +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; +} + +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; + try { + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} + +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} + +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); + +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; + +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } +} + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4935: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/version.js +var VERSION = "10.4.1"; + +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], + createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; +var endpoints_default = Endpoints; + +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} + +// pkg/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 3708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // 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 ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + RequestError: () => RequestError +}); +module.exports = __toCommonJS(dist_src_exports); +var import_deprecation = __nccwpck_require__(4150); +var import_once = __toESM(__nccwpck_require__(5560)); +var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + request: () => request +}); +module.exports = __toCommonJS(dist_src_exports); +var import_endpoint = __nccwpck_require__(4471); +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "8.4.1"; + +// pkg/dist-src/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(3708); + +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error) => { + if (error instanceof import_request_error.RequestError) + throw error; + else if (error.name === "AbortError") + throw error; + let message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json().catch(() => response.text()).catch(() => ""); + } + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); +} +function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} + +// pkg/dist-src/with-defaults.js +function withDefaults(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); +} + +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4001: +/***/ ((module, exports) => { + +"use strict"; + +/// +/// +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; +function isTypedArrayName(name) { + return typedArrayTypeNames.includes(name); +} +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + ...typedArrayTypeNames +]; +function isObjectTypeName(name) { + return objectTypeNames.includes(name); +} +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol' +]; +function isPrimitiveTypeName(name) { + return primitiveTypeNames.includes(name); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isOfType(type) { + return (value) => typeof value === type; +} +const { toString } = Object.prototype; +const getObjectType = (value) => { + const objectTypeName = toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { + return 'HTMLElement'; + } + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': + return 'undefined'; + case 'string': + return 'string'; + case 'number': + return 'number'; + case 'boolean': + return 'boolean'; + case 'function': + return 'Function'; + case 'bigint': + return 'bigint'; + case 'symbol': + return 'symbol'; + default: + } + if (is.observable(value)) { + return 'Observable'; + } + if (is.array(value)) { + return 'Array'; + } + if (is.buffer(value)) { + return 'Buffer'; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; +} +is.undefined = isOfType('undefined'); +is.string = isOfType('string'); +const isNumberType = isOfType('number'); +is.number = (value) => isNumberType(value) && !is.nan(value); +is.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is.function_ = isOfType('function'); +is.null_ = (value) => value === null; +is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); +is.boolean = (value) => value === true || value === false; +is.symbol = isOfType('symbol'); +is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +is.array = (value, assertion) => { + if (!Array.isArray(value)) { + return false; + } + if (!is.function_(assertion)) { + return true; + } + return value.every(assertion); +}; +is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; +is.blob = (value) => isObjectOfType('Blob')(value); +is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); +is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); +is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; +is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; +is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); }; +is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); +is.nativePromise = (value) => isObjectOfType('Promise')(value); +const hasPromiseAPI = (value) => { + var _a, _b; + return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && + is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); +}; +is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); +is.generatorFunction = isObjectOfType('GeneratorFunction'); +is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; +is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); +is.regExp = isObjectOfType('RegExp'); +is.date = isObjectOfType('Date'); +is.error = isObjectOfType('Error'); +is.map = (value) => isObjectOfType('Map')(value); +is.set = (value) => isObjectOfType('Set')(value); +is.weakMap = (value) => isObjectOfType('WeakMap')(value); +is.weakSet = (value) => isObjectOfType('WeakSet')(value); +is.int8Array = isObjectOfType('Int8Array'); +is.uint8Array = isObjectOfType('Uint8Array'); +is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); +is.int16Array = isObjectOfType('Int16Array'); +is.uint16Array = isObjectOfType('Uint16Array'); +is.int32Array = isObjectOfType('Int32Array'); +is.uint32Array = isObjectOfType('Uint32Array'); +is.float32Array = isObjectOfType('Float32Array'); +is.float64Array = isObjectOfType('Float64Array'); +is.bigInt64Array = isObjectOfType('BigInt64Array'); +is.bigUint64Array = isObjectOfType('BigUint64Array'); +is.arrayBuffer = isObjectOfType('ArrayBuffer'); +is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); +is.dataView = isObjectOfType('DataView'); +is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); +is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is.urlInstance = (value) => isObjectOfType('URL')(value); +is.urlString = (value) => { + if (!is.string(value)) { + return false; + } + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch (_a) { + return false; + } +}; +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is.truthy = (value) => Boolean(value); +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +is.falsy = (value) => !value; +is.nan = (value) => Number.isNaN(value); +is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); +is.integer = (value) => Number.isInteger(value); +is.safeInteger = (value) => Number.isSafeInteger(value); +is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (toString.call(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; +is.typedArray = (value) => isTypedArrayName(getObjectType(value)); +const isValidLength = (value) => is.safeInteger(value) && value >= 0; +is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); +is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; +const NODE_TYPE_ELEMENT = 1; +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue' +]; +is.domElement = (value) => { + return is.object(value) && + value.nodeType === NODE_TYPE_ELEMENT && + is.string(value.nodeName) && + !is.plainObject(value) && + DOM_PROPERTIES_TO_CHECK.every(property => property in value); +}; +is.observable = (value) => { + var _a, _b, _c, _d; + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { + return true; + } + if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { + return true; + } + return false; +}; +is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); +is.infinite = (value) => value === Infinity || value === -Infinity; +const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; +is.evenInteger = isAbsoluteMod2(0); +is.oddInteger = isAbsoluteMod2(1); +is.emptyArray = (value) => is.array(value) && value.length === 0; +is.nonEmptyArray = (value) => is.array(value) && value.length > 0; +is.emptyString = (value) => is.string(value) && value.length === 0; +const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); +is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyString = (value) => is.string(value) && value.length > 0; +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value); +is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; +is.emptySet = (value) => is.set(value) && value.size === 0; +is.nonEmptySet = (value) => is.set(value) && value.size > 0; +is.emptyMap = (value) => is.map(value) && value.size === 0; +is.nonEmptyMap = (value) => is.map(value) && value.size > 0; +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) +is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value); +is.formData = (value) => isObjectOfType('FormData')(value); +is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); +const predicateOnArray = (method, predicate, values) => { + if (!is.function_(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +}; +is.any = (predicate, ...values) => { + const predicates = is.array(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); +}; +is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); +const assertType = (condition, description, value, options = {}) => { + if (!condition) { + const { multipleValues } = options; + const valuesMessage = multipleValues ? + `received values of types ${[ + ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) + ].join(', ')}` : + `received value of type \`${is(value)}\``; + throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); + } +}; +exports.assert = { + // Unknowns. + undefined: (value) => assertType(is.undefined(value), 'undefined', value), + string: (value) => assertType(is.string(value), 'string', value), + number: (value) => assertType(is.number(value), 'number', value), + bigint: (value) => assertType(is.bigint(value), 'bigint', value), + // eslint-disable-next-line @typescript-eslint/ban-types + function_: (value) => assertType(is.function_(value), 'Function', value), + null_: (value) => assertType(is.null_(value), 'null', value), + class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), + boolean: (value) => assertType(is.boolean(value), 'boolean', value), + symbol: (value) => assertType(is.symbol(value), 'symbol', value), + numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is.array(value), 'Array', value); + if (assertion) { + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is.buffer(value), 'Buffer', value), + blob: (value) => assertType(is.blob(value), 'Blob', value), + nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), + object: (value) => assertType(is.object(value), 'Object', value), + iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), + asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), + generator: (value) => assertType(is.generator(value), 'Generator', value), + asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), + nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), + promise: (value) => assertType(is.promise(value), 'Promise', value), + generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), + asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), + regExp: (value) => assertType(is.regExp(value), 'RegExp', value), + date: (value) => assertType(is.date(value), 'Date', value), + error: (value) => assertType(is.error(value), 'Error', value), + map: (value) => assertType(is.map(value), 'Map', value), + set: (value) => assertType(is.set(value), 'Set', value), + weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), + weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), + int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), + uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), + uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), + int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), + uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), + int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), + uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), + float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), + float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), + bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), + bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), + arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), + sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), + dataView: (value) => assertType(is.dataView(value), 'DataView', value), + enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value), + urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), + urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), + truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), + falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), + nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), + primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), + integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), + safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), + plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), + typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), + arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), + domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), + observable: (value) => assertType(is.observable(value), 'Observable', value), + nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), + infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), + emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), + nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), + emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), + emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), + nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), + nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value), + emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), + nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), + emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), + nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), + emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), + nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), + propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value), + formData: (value) => assertType(is.formData(value), 'FormData', value), + urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value), + // Numbers. + evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), + oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), + // Two arguments. + directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), + inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), + // Variadic functions. + any: (predicate, ...values) => { + return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); + }, + all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) +}; +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is, { + class: { + value: is.class_ + }, + function: { + value: is.function_ + }, + null: { + value: is.null_ + } +}); +Object.defineProperties(exports.assert, { + class: { + value: exports.assert.class_ + }, + function: { + value: exports.assert.function_ + }, + null: { + value: exports.assert.null_ + } +}); +exports["default"] = is; +// For CommonJS default export support +module.exports = is; +module.exports["default"] = is; +module.exports.assert = exports.assert; + + +/***/ }), + +/***/ 4480: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const defer_to_connect_1 = __nccwpck_require__(2114); +const util_1 = __nccwpck_require__(9023); +const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); +const timer = (request) => { + if (request.timings) { + return request.timings; + } + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined + } + }; + request.timings = timings; + const handleError = (origin) => { + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + origin.emit = emit; + } + // Saves the original behavior + return emit(event, ...args); + }; + }; + handleError(request); + const onAbort = () => { + timings.abort = Date.now(); + // Let the `end` response event be responsible for setting the total phase, + // unless the Node.js major version is >= 13. + if (!timings.response || nodejsMajorVersion >= 13) { + timings.phases.total = Date.now() - timings.start; + } + }; + request.prependOnceListener('abort', onAbort); + const onSocket = (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + if (util_1.types.isProxy(socket)) { + return; + } + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + defer_to_connect_1.default(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + // This callback is called before flushing any data, + // so we don't need to set `timings.phases.request` here. + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + } + }); + }; + if (request.socket) { + onSocket(request.socket); + } + else { + request.prependOnceListener('socket', onSocket); + } + const onUpload = () => { + var _a; + timings.upload = Date.now(); + timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); + }; + const writableFinished = () => { + if (typeof request.writableFinished === 'boolean') { + return request.writableFinished; + } + // Node.js doesn't have `request.writableFinished` property + return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); + }; + if (writableFinished()) { + onUpload(); + } + else { + request.prependOnceListener('finish', onUpload); + } + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + response.prependOnceListener('aborted', onAbort); + }); + return timings; +}; +exports["default"] = timer; +// For CommonJS default export support +module.exports = timer; +module.exports["default"] = timer; + + /***/ }), /***/ 1316: @@ -1831,7 +11409,7 @@ module.exports = function (/**String*/ input, /** object */ options) { function fixPath(zipPath) { const { join, normalize, sep } = pth.posix; // convert windows file separators and normalize - return join(pth.isAbsolute(zipPath) ? "/": '.', normalize(sep + zipPath.split("\\").join(sep) + sep)); + return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep)); } function filenameFilter(filterfn) { @@ -2799,7 +12377,6 @@ module.exports = function () { return Utils.fromDOS2Date(this.timeval); }, set time(val) { - val = new Date(val); this.timeval = Utils.fromDate2DOS(val); }, @@ -2922,8 +12499,6 @@ module.exports = function () { _localHeader.version = data.readUInt16LE(Constants.LOCVER); // general purpose bit flag _localHeader.flags = data.readUInt16LE(Constants.LOCFLG); - // desc flag - _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0; // compression method _localHeader.method = data.readUInt16LE(Constants.LOCHOW); // modification time (2 bytes time, 2 bytes date) @@ -3320,6 +12895,7 @@ module.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) { /***/ 2689: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; // node crypt, we use it for generate salt @@ -3879,11 +13455,7 @@ Utils.prototype.makeDir = function (/*String*/ folder) { try { stat = self.fs.statSync(resolvedPath); } catch (e) { - if (e.message && e.message.startsWith('ENOENT')) { - self.fs.mkdirSync(resolvedPath); - } else { - throw e; - } + self.fs.mkdirSync(resolvedPath); } if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); }); @@ -4146,9 +13718,10 @@ Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* func }; Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) { - const lo = buffer.readUInt32LE(index); - const hi = buffer.readUInt32LE(index + 4); - return hi * 0x100000000 + lo; + var slice = Buffer.from(buffer.slice(index, index + 8)); + slice.swap64(); + + return parseInt(`0x${slice.toString("hex")}`); }; Utils.fromDOS2Date = function (val) { @@ -4206,7 +13779,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { function crc32OK(data) { // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written - if (!_centralHeader.flags_desc && !_centralHeader.localHeader.flags_desc) { + if (!_centralHeader.flags_desc) { if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { return false; } @@ -4362,7 +13935,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { } function readUInt64LE(buffer, offset) { - return Utils.readBigUInt64LE(buffer, offset); + return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset); } function parseExtra(data) { @@ -5034,11 +14607,193 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { }; +/***/ }), + +/***/ 2732: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var register = __nccwpck_require__(1063); +var addHook = __nccwpck_require__(2027); +var removeHook = __nccwpck_require__(9934); + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); + +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} + +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} + +function HookCollection() { + var state = { + registry: {}, + }; + + var hook = register.bind(null, state); + bindApi(hook, state); + + return hook; +} + +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); +} + +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); + +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; + + +/***/ }), + +/***/ 2027: +/***/ ((module) => { + +module.exports = addHook; + +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } + + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } + + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } + + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } + + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} + + +/***/ }), + +/***/ 1063: +/***/ ((module) => { + +module.exports = register; + +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } + + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} + + +/***/ }), + +/***/ 9934: +/***/ ((module) => { + +module.exports = removeHook; + +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); +} + + /***/ }), /***/ 748: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const stringify = __nccwpck_require__(3317); @@ -5216,6 +14971,7 @@ module.exports = braces; /***/ 1113: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const fill = __nccwpck_require__(877); @@ -5283,6 +15039,7 @@ module.exports = compile; /***/ 2477: /***/ ((module) => { +"use strict"; module.exports = { @@ -5347,6 +15104,7 @@ module.exports = { /***/ 5290: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const fill = __nccwpck_require__(877); @@ -5467,6 +15225,7 @@ module.exports = expand; /***/ 507: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const stringify = __nccwpck_require__(3317); @@ -5805,6 +15564,7 @@ module.exports = parse; /***/ 3317: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const utils = __nccwpck_require__(2257); @@ -5844,6 +15604,7 @@ module.exports = (ast, options = {}) => { /***/ 2257: /***/ ((__unused_webpack_module, exports) => { +"use strict"; exports.isInteger = num => { @@ -5968,11 +15729,1203 @@ exports.flatten = (...args) => { }; +/***/ }), + +/***/ 2417: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const { + V4MAPPED, + ADDRCONFIG, + ALL, + promises: { + Resolver: AsyncResolver + }, + lookup: dnsLookup +} = __nccwpck_require__(2250); +const {promisify} = __nccwpck_require__(9023); +const os = __nccwpck_require__(857); + +const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); +const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); +const kExpires = Symbol('expires'); + +const supportsALL = typeof ALL === 'number'; + +const verifyAgent = agent => { + if (!(agent && typeof agent.createConnection === 'function')) { + throw new Error('Expected an Agent instance as the first argument'); + } +}; + +const map4to6 = entries => { + for (const entry of entries) { + if (entry.family === 6) { + continue; + } + + entry.address = `::ffff:${entry.address}`; + entry.family = 6; + } +}; + +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; + + for (const device of Object.values(os.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } + + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } + + if (has4 && has6) { + return {has4, has6}; + } + } + } + + return {has4, has6}; +}; + +const isIterable = map => { + return Symbol.iterator in map; +}; + +const ttl = {ttl: true}; +const all = {all: true}; + +class CacheableLookup { + constructor({ + cache = new Map(), + maxTtl = Infinity, + fallbackDuration = 3600, + errorTtl = 0.15, + resolver = new AsyncResolver(), + lookup = dnsLookup + } = {}) { + this.maxTtl = maxTtl; + this.errorTtl = errorTtl; + + this._cache = cache; + this._resolver = resolver; + this._dnsLookup = promisify(lookup); + + if (this._resolver instanceof AsyncResolver) { + this._resolve4 = this._resolver.resolve4.bind(this._resolver); + this._resolve6 = this._resolver.resolve6.bind(this._resolver); + } else { + this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); + } + + this._iface = getIfaceInfo(); + + this._pending = {}; + this._nextRemovalTime = false; + this._hostnamesToFallback = new Set(); + + if (fallbackDuration < 1) { + this._fallback = false; + } else { + this._fallback = true; + + const interval = setInterval(() => { + this._hostnamesToFallback.clear(); + }, fallbackDuration * 1000); + + /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ + if (interval.unref) { + interval.unref(); + } + } + + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); + } + + set servers(servers) { + this.clear(); + + this._resolver.setServers(servers); + } + + get servers() { + return this._resolver.getServers(); + } + + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else if (typeof options === 'number') { + options = { + family: options + }; + } + + if (!callback) { + throw new Error('Callback must be a function.'); + } + + // eslint-disable-next-line promise/prefer-await-to-then + this.lookupAsync(hostname, options).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family, result.expires, result.ttl); + } + }, callback); + } + + async lookupAsync(hostname, options = {}) { + if (typeof options === 'number') { + options = { + family: options + }; + } + + let cached = await this.query(hostname); + + if (options.family === 6) { + const filtered = cached.filter(entry => entry.family === 6); + + if (options.hints & V4MAPPED) { + if ((supportsALL && options.hints & ALL) || filtered.length === 0) { + map4to6(cached); + } else { + cached = filtered; + } + } else { + cached = filtered; + } + } else if (options.family === 4) { + cached = cached.filter(entry => entry.family === 4); + } + + if (options.hints & ADDRCONFIG) { + const {_iface} = this; + cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); + } + + if (cached.length === 0) { + const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; + + throw error; + } + + if (options.all) { + return cached; + } + + return cached[0]; + } + + async query(hostname) { + let cached = await this._cache.get(hostname); + + if (!cached) { + const pending = this._pending[hostname]; + + if (pending) { + cached = await pending; + } else { + const newPromise = this.queryAndCache(hostname); + this._pending[hostname] = newPromise; + + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } + } + } + + cached = cached.map(entry => { + return {...entry}; + }); + + return cached; + } + + async _resolve(hostname) { + const wrap = async promise => { + try { + return await promise; + } catch (error) { + if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { + return []; + } + + throw error; + } + }; + + // ANY is unsafe as it doesn't trigger new queries in the underlying server. + const [A, AAAA] = await Promise.all([ + this._resolve4(hostname, ttl), + this._resolve6(hostname, ttl) + ].map(promise => wrap(promise))); + + let aTtl = 0; + let aaaaTtl = 0; + let cacheTtl = 0; + + const now = Date.now(); + + for (const entry of A) { + entry.family = 4; + entry.expires = now + (entry.ttl * 1000); + + aTtl = Math.max(aTtl, entry.ttl); + } + + for (const entry of AAAA) { + entry.family = 6; + entry.expires = now + (entry.ttl * 1000); + + aaaaTtl = Math.max(aaaaTtl, entry.ttl); + } + + if (A.length > 0) { + if (AAAA.length > 0) { + cacheTtl = Math.min(aTtl, aaaaTtl); + } else { + cacheTtl = aTtl; + } + } else { + cacheTtl = aaaaTtl; + } + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl + }; + } + + async _lookup(hostname) { + try { + const entries = await this._dnsLookup(hostname, { + all: true + }); + + return { + entries, + cacheTtl: 0 + }; + } catch (_) { + return { + entries: [], + cacheTtl: 0 + }; + } + } + + async _set(hostname, data, cacheTtl) { + if (this.maxTtl > 0 && cacheTtl > 0) { + cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; + data[kExpires] = Date.now() + cacheTtl; + + try { + await this._cache.set(hostname, data, cacheTtl); + } catch (error) { + this.lookupAsync = async () => { + const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); + cacheError.cause = error; + + throw cacheError; + }; + } + + if (isIterable(this._cache)) { + this._tick(cacheTtl); + } + } + } + + async queryAndCache(hostname) { + if (this._hostnamesToFallback.has(hostname)) { + return this._dnsLookup(hostname, all); + } + + let query = await this._resolve(hostname); + + if (query.entries.length === 0 && this._fallback) { + query = await this._lookup(hostname); + + if (query.entries.length !== 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); + } + } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; + } + + _tick(ms) { + const nextRemovalTime = this._nextRemovalTime; + + if (!nextRemovalTime || ms < nextRemovalTime) { + clearTimeout(this._removalTimeout); + + this._nextRemovalTime = ms; + + this._removalTimeout = setTimeout(() => { + this._nextRemovalTime = false; + + let nextExpiry = Infinity; + + const now = Date.now(); + + for (const [hostname, entries] of this._cache) { + const expires = entries[kExpires]; + + if (now >= expires) { + this._cache.delete(hostname); + } else if (expires < nextExpiry) { + nextExpiry = expires; + } + } + + if (nextExpiry !== Infinity) { + this._tick(nextExpiry - now); + } + }, ms); + + /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ + if (this._removalTimeout.unref) { + this._removalTimeout.unref(); + } + } + } + + install(agent) { + verifyAgent(agent); + + if (kCacheableLookupCreateConnection in agent) { + throw new Error('CacheableLookup has been already installed'); + } + + agent[kCacheableLookupCreateConnection] = agent.createConnection; + agent[kCacheableLookupInstance] = this; + + agent.createConnection = (options, callback) => { + if (!('lookup' in options)) { + options.lookup = this.lookup; + } + + return agent[kCacheableLookupCreateConnection](options, callback); + }; + } + + uninstall(agent) { + verifyAgent(agent); + + if (agent[kCacheableLookupCreateConnection]) { + if (agent[kCacheableLookupInstance] !== this) { + throw new Error('The agent is not owned by this CacheableLookup instance'); + } + + agent.createConnection = agent[kCacheableLookupCreateConnection]; + + delete agent[kCacheableLookupCreateConnection]; + delete agent[kCacheableLookupInstance]; + } + } + + updateInterfaceInfo() { + const {_iface} = this; + + this._iface = getIfaceInfo(); + + if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { + this._cache.clear(); + } + } + + clear(hostname) { + if (hostname) { + this._cache.delete(hostname); + return; + } + + this._cache.clear(); + } +} + +module.exports = CacheableLookup; +module.exports["default"] = CacheableLookup; + + +/***/ }), + +/***/ 6176: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const {PassThrough: PassThroughStream} = __nccwpck_require__(2203); + +module.exports = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; + + +/***/ }), + +/***/ 4921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const {constants: BufferConstants} = __nccwpck_require__(181); +const pump = __nccwpck_require__(7898); +const bufferStream = __nccwpck_require__(6176); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } + + resolve(); + }); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports["default"] = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; + + +/***/ }), + +/***/ 1487: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const EventEmitter = __nccwpck_require__(4434); +const urlLib = __nccwpck_require__(7016); +const normalizeUrl = __nccwpck_require__(7827); +const getStream = __nccwpck_require__(4921); +const CachePolicy = __nccwpck_require__(4584); +const Response = __nccwpck_require__(4145); +const lowercaseKeys = __nccwpck_require__(1364); +const cloneResponse = __nccwpck_require__(6358); +const Keyv = __nccwpck_require__(6018); + +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } + + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); + + return this.createCacheableRequest(request); + } + + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } + + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); + + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; + + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; + + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + + (async () => { + try { + const bodyPromise = getStream.buffer(response); + + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); + + if (requestErrored) { + return; + } + + const body = await bodyPromise; + + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } + + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; + + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + + (async () => { + const get = async opts => { + await Promise.resolve(); + + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } + + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; + + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; + + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); + + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } + + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + + return ee; + }; + } +} + +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} + +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} + +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } +}; + +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; + +module.exports = CacheableRequest; + + +/***/ }), + +/***/ 6358: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const PassThrough = (__nccwpck_require__(2203).PassThrough); +const mimicResponse = __nccwpck_require__(9991); + +const cloneResponse = response => { + if (!(response && response.pipe)) { + throw new TypeError('Parameter `response` must be a response stream.'); + } + + const clone = new PassThrough(); + mimicResponse(response, clone); + + return response.pipe(clone); +}; + +module.exports = cloneResponse; + + +/***/ }), + +/***/ 1373: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const {Transform, PassThrough} = __nccwpck_require__(2203); +const zlib = __nccwpck_require__(3106); +const mimicResponse = __nccwpck_require__(9382); + +module.exports = response => { + const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); + + if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { + return response; + } + + // TODO: Remove this when targeting Node.js 12. + const isBrotli = contentEncoding === 'br'; + if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { + response.destroy(new Error('Brotli is not supported on Node.js < 12')); + return response; + } + + let isEmpty = true; + + const checker = new Transform({ + transform(data, _encoding, callback) { + isEmpty = false; + + callback(null, data); + }, + + flush(callback) { + callback(); + } + }); + + const finalStream = new PassThrough({ + autoDestroy: false, + destroy(error, callback) { + response.destroy(); + + callback(error); + } + }); + + const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); + + decompressStream.once('error', error => { + if (isEmpty && !response.readable) { + finalStream.end(); + return; + } + + finalStream.destroy(error); + }); + + mimicResponse(response, finalStream); + response.pipe(checker).pipe(decompressStream).pipe(finalStream); + + return finalStream; +}; + + +/***/ }), + +/***/ 9382: +/***/ ((module) => { + +"use strict"; + + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' +]; + +module.exports = (fromStream, toStream) => { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + + const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); + + const properties = {}; + + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } + + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; + + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false + }; + } + + Object.defineProperties(toStream, properties); + + fromStream.once('aborted', () => { + toStream.destroy(); + + toStream.emit('aborted'); + }); + + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); + + return toStream; +}; + + +/***/ }), + +/***/ 2114: +/***/ ((module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isTLSSocket(socket) { + return socket.encrypted; +} +const deferToConnect = (socket, fn) => { + let listeners; + if (typeof fn === 'function') { + const connect = fn; + listeners = { connect }; + } + else { + listeners = fn; + } + const hasConnectListener = typeof listeners.connect === 'function'; + const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; + const hasCloseListener = typeof listeners.close === 'function'; + const onConnect = () => { + if (hasConnectListener) { + listeners.connect(); + } + if (isTLSSocket(socket) && hasSecureConnectListener) { + if (socket.authorized) { + listeners.secureConnect(); + } + else if (!socket.authorizationError) { + socket.once('secureConnect', listeners.secureConnect); + } + } + if (hasCloseListener) { + socket.once('close', listeners.close); + } + }; + if (socket.writable && !socket.connecting) { + onConnect(); + } + else if (socket.connecting) { + socket.once('connect', onConnect); + } + else if (socket.destroyed && hasCloseListener) { + listeners.close(socket._hadError); + } +}; +exports["default"] = deferToConnect; +// For CommonJS default export support +module.exports = deferToConnect; +module.exports["default"] = deferToConnect; + + +/***/ }), + +/***/ 4150: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; + + +/***/ }), + +/***/ 1424: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var once = __nccwpck_require__(5560); + +var noop = function() {}; + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + process.nextTick(onclosenexttick); + }; + + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; + + /***/ }), /***/ 8188: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; var isGlob = __nccwpck_require__(1925); @@ -6022,6 +16975,7 @@ module.exports = function globParent(str, opts) { /***/ 5648: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const taskManager = __nccwpck_require__(6599); const async_1 = __nccwpck_require__(645); @@ -6131,6 +17085,7 @@ module.exports = FastGlob; /***/ 6599: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; @@ -6248,6 +17203,7 @@ exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ 645: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const async_1 = __nccwpck_require__(2907); @@ -6278,6 +17234,7 @@ exports["default"] = ProviderAsync; /***/ 3591: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(6002); @@ -6347,6 +17304,7 @@ exports["default"] = DeepFilter; /***/ 4285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(6002); @@ -6439,6 +17397,7 @@ exports["default"] = EntryFilter; /***/ 1587: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(6002); @@ -6458,9 +17417,10 @@ exports["default"] = ErrorFilter; /***/ }), -/***/ 7827: +/***/ 208: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(6002); @@ -6513,9 +17473,10 @@ exports["default"] = Matcher; /***/ 5740: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const matcher_1 = __nccwpck_require__(7827); +const matcher_1 = __nccwpck_require__(208); class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); @@ -6558,6 +17519,7 @@ exports["default"] = PartialMatcher; /***/ 7792: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(6928); @@ -6613,6 +17575,7 @@ exports["default"] = Provider; /***/ 1969: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2203); @@ -6651,6 +17614,7 @@ exports["default"] = ProviderStream; /***/ 5894: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const sync_1 = __nccwpck_require__(264); @@ -6681,6 +17645,7 @@ exports["default"] = ProviderSync; /***/ 7094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(6002); @@ -6714,6 +17679,7 @@ exports["default"] = EntryTransformer; /***/ 2907: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsWalk = __nccwpck_require__(9337); @@ -6756,6 +17722,7 @@ exports["default"] = ReaderAsync; /***/ 1824: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(6928); @@ -6796,6 +17763,7 @@ exports["default"] = Reader; /***/ 87: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2203); @@ -6858,6 +17826,7 @@ exports["default"] = ReaderStream; /***/ 264: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsStat = __nccwpck_require__(1470); @@ -6908,6 +17877,7 @@ exports["default"] = ReaderSync; /***/ 879: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; @@ -6974,6 +17944,7 @@ exports["default"] = Settings; /***/ 5711: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitWhen = exports.flatten = void 0; @@ -7003,6 +17974,7 @@ exports.splitWhen = splitWhen; /***/ 9718: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isEnoentCodeError = void 0; @@ -7017,6 +17989,7 @@ exports.isEnoentCodeError = isEnoentCodeError; /***/ 6979: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDirentFromStats = void 0; @@ -7043,6 +18016,7 @@ exports.createDirentFromStats = createDirentFromStats; /***/ 6002: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; @@ -7067,6 +18041,7 @@ exports.string = string; /***/ 9283: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; @@ -7142,6 +18117,7 @@ exports.convertPosixPathToPattern = convertPosixPathToPattern; /***/ 1304: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; @@ -7355,6 +18331,7 @@ exports.isAbsolute = isAbsolute; /***/ 536: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.merge = void 0; @@ -7379,6 +18356,7 @@ function propagateCloseEventToSources(streams) { /***/ 7641: /***/ ((__unused_webpack_module, exports) => { +"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isEmpty = exports.isString = void 0; @@ -7392,11 +18370,309 @@ function isEmpty(input) { exports.isEmpty = isEmpty; +/***/ }), + +/***/ 8230: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +/* eslint-disable no-var */ + +var reusify = __nccwpck_require__(844) + +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker + worker = context + context = null + } + + if (concurrency < 1) { + throw new Error('fastqueue concurrency must be greater than 1') + } + + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 + var errorHandler = null + + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error + } + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true + } + + function length () { + var current = queueHead + var counter = 0 + + while (current) { + current = current.next + counter++ + } + + return counter + } + + function getQueue () { + var current = queueHead + var tasks = [] + + while (current) { + tasks.push(current.value) + current = current.next + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false + for (var i = 0; i < self.concurrency; i++) { + _running++ + release() + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function unshift (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } + } + + function kill () { + queueHead = null + queueTail = null + self.drain = noop + } + + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop + } + + function error (handler) { + errorHandler = handler + } +} + +function noop () {} + +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null + this.errorHandler = null + + var self = this + + this.worked = function worked (err, result) { + var callback = self.callback + var errorHandler = self.errorHandler + var val = self.value + self.value = null + self.callback = noop + if (self.errorHandler) { + errorHandler(err, val) + } + callback.call(self.context, err, result) + self.release(self) + } +} + +function queueAsPromised (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker + worker = context + context = null + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res) + }, cb) + } + + var queue = fastqueue(context, asyncWrapper, concurrency) + + var pushCb = queue.push + var unshiftCb = queue.unshift + + queue.push = push + queue.unshift = unshift + queue.drained = drained + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function drained () { + if (queue.idle()) { + return new Promise(function (resolve) { + resolve() + }) + } + + var previousDrain = queue.drain + + var p = new Promise(function (resolve) { + queue.drain = function () { + previousDrain() + resolve() + } + }) + + return p + } +} + +module.exports = fastqueue +module.exports.promise = queueAsPromised + + /***/ }), /***/ 877: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /*! * fill-range * @@ -7647,6 +18923,5046 @@ const fill = (start, end, step, options = {}) => { module.exports = fill; +/***/ }), + +/***/ 7814: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const types_1 = __nccwpck_require__(4707); +function createRejection(error, ...beforeErrorGroups) { + const promise = (async () => { + if (error instanceof types_1.RequestError) { + try { + for (const hooks of beforeErrorGroups) { + if (hooks) { + for (const hook of hooks) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } + } + catch (error_) { + error = error_; + } + } + throw error; + })(); + const returnPromise = () => promise; + promise.json = returnPromise; + promise.text = returnPromise; + promise.buffer = returnPromise; + promise.on = returnPromise; + return promise; +} +exports["default"] = createRejection; + + +/***/ }), + +/***/ 2126: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(4434); +const is_1 = __nccwpck_require__(4001); +const PCancelable = __nccwpck_require__(4533); +const types_1 = __nccwpck_require__(4707); +const parse_body_1 = __nccwpck_require__(5494); +const core_1 = __nccwpck_require__(6825); +const proxy_events_1 = __nccwpck_require__(7813); +const get_buffer_1 = __nccwpck_require__(4858); +const is_response_ok_1 = __nccwpck_require__(4350); +const proxiedRequestEvents = [ + 'request', + 'response', + 'redirect', + 'uploadProgress', + 'downloadProgress' +]; +function asPromise(normalizedOptions) { + let globalRequest; + let globalResponse; + const emitter = new events_1.EventEmitter(); + const promise = new PCancelable((resolve, reject, onCancel) => { + const makeRequest = (retryCount) => { + const request = new core_1.default(undefined, normalizedOptions); + request.retryCount = retryCount; + request._noPipe = true; + onCancel(() => request.destroy()); + onCancel.shouldReject = false; + onCancel(() => reject(new types_1.CancelError(request))); + globalRequest = request; + request.once('response', async (response) => { + var _a; + response.retryCount = retryCount; + if (response.request.aborted) { + // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error + return; + } + // Download body + let rawBody; + try { + rawBody = await get_buffer_1.default(request); + response.rawBody = rawBody; + } + catch (_b) { + // The same error is caught below. + // See request.once('error') + return; + } + if (request._isAboutToError) { + return; + } + // Parse body + const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); + const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = rawBody; + } + else { + try { + response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fallback to `utf8` + response.body = rawBody.toString(); + if (is_response_ok_1.isResponseOk(response)) { + request._beforeError(error); + return; + } + } + } + try { + for (const [index, hook] of options.hooks.afterResponse.entries()) { + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + const typedOptions = core_1.default.normalizeArguments(undefined, { + ...updatedOptions, + retry: { + calculateDelay: () => 0 + }, + throwHttpErrors: false, + resolveBodyOnly: false + }, options); + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index); + for (const hook of typedOptions.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedOptions); + } + const promise = asPromise(typedOptions); + onCancel(() => { + promise.catch(() => { }); + promise.cancel(); + }); + return promise; + }); + } + } + catch (error) { + request._beforeError(new types_1.RequestError(error.message, error, request)); + return; + } + globalResponse = response; + if (!is_response_ok_1.isResponseOk(response)) { + request._beforeError(new types_1.HTTPError(response)); + return; + } + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { + if (promise.isCanceled) { + return; + } + const { options } = request; + if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { + const { response } = error; + resolve(request.options.resolveBodyOnly ? response.body : response); + return; + } + reject(error); + }; + request.once('error', onError); + const previousBody = request.options.body; + request.once('retry', (newRetryCount, error) => { + var _a, _b; + if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { + onError(error); + return; + } + makeRequest(newRetryCount); + }); + proxy_events_1.default(request, emitter, proxiedRequestEvents); + }; + makeRequest(0); + }); + promise.on = (event, fn) => { + emitter.on(event, fn); + return promise; + }; + const shortcut = (responseType) => { + const newPromise = (async () => { + // Wait until downloading has ended + await promise; + const { options } = globalResponse.request; + return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); + })(); + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && headers.accept === undefined) { + headers.accept = 'application/json'; + } + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; +} +exports["default"] = asPromise; +__exportStar(__nccwpck_require__(4707), exports); + + +/***/ }), + +/***/ 6364: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(4001); +const normalizeArguments = (options, defaults) => { + if (is_1.default.null_(options.encoding)) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); + // `options.responseType` + if (options.responseType === undefined) { + options.responseType = 'text'; + } + // `options.retry` + const { retry } = options; + if (defaults) { + options.retry = { ...defaults.retry }; + } + else { + options.retry = { + calculateDelay: retryObject => retryObject.computedValue, + limit: 0, + methods: [], + statusCodes: [], + errorCodes: [], + maxRetryAfter: undefined + }; + } + if (is_1.default.object(retry)) { + options.retry = { + ...options.retry, + ...retry + }; + options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; + options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; + options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; + } + else if (is_1.default.number(retry)) { + options.retry.limit = retry; + } + if (is_1.default.undefined(options.retry.maxRetryAfter)) { + options.retry.maxRetryAfter = Math.min( + // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); + } + // `options.pagination` + if (is_1.default.object(options.pagination)) { + if (defaults) { + options.pagination = { + ...defaults.pagination, + ...options.pagination + }; + } + const { pagination } = options; + if (!is_1.default.function_(pagination.transform)) { + throw new Error('`options.pagination.transform` must be implemented'); + } + if (!is_1.default.function_(pagination.shouldContinue)) { + throw new Error('`options.pagination.shouldContinue` must be implemented'); + } + if (!is_1.default.function_(pagination.filter)) { + throw new TypeError('`options.pagination.filter` must be implemented'); + } + if (!is_1.default.function_(pagination.paginate)) { + throw new Error('`options.pagination.paginate` must be implemented'); + } + } + // JSON mode + if (options.responseType === 'json' && options.headers.accept === undefined) { + options.headers.accept = 'application/json'; + } + return options; +}; +exports["default"] = normalizeArguments; + + +/***/ }), + +/***/ 5494: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const types_1 = __nccwpck_require__(4707); +const parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); + } + if (responseType === 'buffer') { + return rawBody; + } + throw new types_1.ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error' + }, response); + } + catch (error) { + throw new types_1.ParseError(error, response); + } +}; +exports["default"] = parseBody; + + +/***/ }), + +/***/ 4707: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CancelError = exports.ParseError = void 0; +const core_1 = __nccwpck_require__(6825); +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class ParseError extends core_1.RequestError { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code; + } +} +exports.ParseError = ParseError; +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class CancelError extends core_1.RequestError { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + this.code = 'ERR_CANCELED'; + } + get isCanceled() { + return true; + } +} +exports.CancelError = CancelError; +__exportStar(__nccwpck_require__(6825), exports); + + +/***/ }), + +/***/ 3024: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.retryAfterStatusCodes = void 0; +exports.retryAfterStatusCodes = new Set([413, 429, 503]); +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { + return 0; + } + return retryAfter; + } + if (error.response.statusCode === 413) { + return 0; + } + } + const noise = Math.random() * 100; + return ((2 ** (attemptCount - 1)) * 1000) + noise; +}; +exports["default"] = calculateRetryDelay; + + +/***/ }), + +/***/ 6825: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; +const util_1 = __nccwpck_require__(9023); +const stream_1 = __nccwpck_require__(2203); +const fs_1 = __nccwpck_require__(9896); +const url_1 = __nccwpck_require__(7016); +const http = __nccwpck_require__(8611); +const http_1 = __nccwpck_require__(8611); +const https = __nccwpck_require__(5692); +const http_timer_1 = __nccwpck_require__(4480); +const cacheable_lookup_1 = __nccwpck_require__(2417); +const CacheableRequest = __nccwpck_require__(1487); +const decompressResponse = __nccwpck_require__(1373); +// @ts-expect-error Missing types +const http2wrapper = __nccwpck_require__(4956); +const lowercaseKeys = __nccwpck_require__(1364); +const is_1 = __nccwpck_require__(4001); +const get_body_size_1 = __nccwpck_require__(9296); +const is_form_data_1 = __nccwpck_require__(6751); +const proxy_events_1 = __nccwpck_require__(7813); +const timed_out_1 = __nccwpck_require__(4501); +const url_to_options_1 = __nccwpck_require__(3873); +const options_to_url_1 = __nccwpck_require__(5743); +const weakable_map_1 = __nccwpck_require__(7791); +const get_buffer_1 = __nccwpck_require__(4858); +const dns_ip_version_1 = __nccwpck_require__(1037); +const is_response_ok_1 = __nccwpck_require__(4350); +const deprecation_warning_1 = __nccwpck_require__(9796); +const normalize_arguments_1 = __nccwpck_require__(6364); +const calculate_retry_delay_1 = __nccwpck_require__(3024); +let globalDnsCache; +const kRequest = Symbol('request'); +const kResponse = Symbol('response'); +const kResponseSize = Symbol('responseSize'); +const kDownloadedSize = Symbol('downloadedSize'); +const kBodySize = Symbol('bodySize'); +const kUploadedSize = Symbol('uploadedSize'); +const kServerResponsesPiped = Symbol('serverResponsesPiped'); +const kUnproxyEvents = Symbol('unproxyEvents'); +const kIsFromCache = Symbol('isFromCache'); +const kCancelTimeouts = Symbol('cancelTimeouts'); +const kStartedReading = Symbol('startedReading'); +const kStopReading = Symbol('stopReading'); +const kTriggerRead = Symbol('triggerRead'); +const kBody = Symbol('body'); +const kJobs = Symbol('jobs'); +const kOriginalResponse = Symbol('originalResponse'); +const kRetryTimeout = Symbol('retryTimeout'); +exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); +const supportsBrotli = is_1.default.string(process.versions.brotli); +exports.withoutBody = new Set(['GET', 'HEAD']); +exports.knownHookEvents = [ + 'init', + 'beforeRequest', + 'beforeRedirect', + 'beforeError', + 'beforeRetry', + // Promise-Only + 'afterResponse' +]; +function validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { + throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); + } + } +} +function isClientRequest(clientRequest) { + return is_1.default.object(clientRequest) && !('statusCode' in clientRequest); +} +const cacheableStore = new weakable_map_1.default(); +const waitForOpenFile = async (file) => new Promise((resolve, reject) => { + const onError = (error) => { + reject(error); + }; + // Node.js 12 has incomplete types + if (!file.pending) { + resolve(); + } + file.once('error', onError); + file.once('ready', () => { + file.off('error', onError); + resolve(); + }); +}); +const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const nonEnumerableProperties = [ + 'context', + 'body', + 'json', + 'form' +]; +exports.setNonEnumerableProperties = (sources, to) => { + // Non enumerable properties shall not be merged + const properties = {}; + for (const source of sources) { + if (!source) { + continue; + } + for (const name of nonEnumerableProperties) { + if (!(name in source)) { + continue; + } + properties[name] = { + writable: true, + configurable: true, + enumerable: false, + // @ts-expect-error TS doesn't see the check above + value: source[name] + }; + } + } + Object.defineProperties(to, properties); +}; +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +class RequestError extends Error { + constructor(message, error, self) { + var _a, _b; + super(message); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR'; + if (self instanceof Request) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self[kResponse] + }); + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self.options + }); + } + else { + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self + }); + } + this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings; + // Recover the original stacktrace + if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } + } +} +exports.RequestError = RequestError; +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +class MaxRedirectsError extends RequestError { + constructor(request) { + super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); + this.name = 'MaxRedirectsError'; + this.code = 'ERR_TOO_MANY_REDIRECTS'; + } +} +exports.MaxRedirectsError = MaxRedirectsError; +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +class HTTPError extends RequestError { + constructor(response) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); + this.name = 'HTTPError'; + this.code = 'ERR_NON_2XX_3XX_RESPONSE'; + } +} +exports.HTTPError = HTTPError; +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +class CacheError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'CacheError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; + } +} +exports.CacheError = CacheError; +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +class UploadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'UploadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; + } +} +exports.UploadError = UploadError; +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +class TimeoutError extends RequestError { + constructor(error, timings, request) { + super(error.message, error, request); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; + } +} +exports.TimeoutError = TimeoutError; +/** +An error to be thrown when reading from response stream fails. +*/ +class ReadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'ReadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; + } +} +exports.ReadError = ReadError; +/** +An error to be thrown when given an unsupported protocol. +*/ +class UnsupportedProtocolError extends RequestError { + constructor(options) { + super(`Unsupported protocol "${options.url.protocol}"`, {}, options); + this.name = 'UnsupportedProtocolError'; + this.code = 'ERR_UNSUPPORTED_PROTOCOL'; + } +} +exports.UnsupportedProtocolError = UnsupportedProtocolError; +const proxiedRequestEvents = [ + 'socket', + 'connect', + 'continue', + 'information', + 'upgrade', + 'timeout' +]; +class Request extends stream_1.Duplex { + constructor(url, options = {}, defaults) { + super({ + // This must be false, to enable throwing after destroy + // It is used for retry logic in Promise API + autoDestroy: false, + // It needs to be zero because we're just proxying the data to another stream + highWaterMark: 0 + }); + this[kDownloadedSize] = 0; + this[kUploadedSize] = 0; + this.requestInitialized = false; + this[kServerResponsesPiped] = new Set(); + this.redirects = []; + this[kStopReading] = false; + this[kTriggerRead] = false; + this[kJobs] = []; + this.retryCount = 0; + // TODO: Remove this when targeting Node.js >= 12 + this._progressCallbacks = []; + const unlockWrite = () => this._unlockWrite(); + const lockWrite = () => this._lockWrite(); + this.on('pipe', (source) => { + source.prependListener('data', unlockWrite); + source.on('data', lockWrite); + source.prependListener('end', unlockWrite); + source.on('end', lockWrite); + }); + this.on('unpipe', (source) => { + source.off('data', unlockWrite); + source.off('data', lockWrite); + source.off('end', unlockWrite); + source.off('end', lockWrite); + }); + this.on('pipe', source => { + if (source instanceof http_1.IncomingMessage) { + this.options.headers = { + ...source.headers, + ...this.options.headers + }; + } + }); + const { json, body, form } = options; + if (json || body || form) { + this._lockWrite(); + } + if (exports.kIsNormalizedAlready in options) { + this.options = options; + } + else { + try { + // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible + this.options = this.constructor.normalizeArguments(url, options, defaults); + } + catch (error) { + // TODO: Move this to `_destroy()` + if (is_1.default.nodeStream(options.body)) { + options.body.destroy(); + } + this.destroy(error); + return; + } + } + (async () => { + var _a; + try { + if (this.options.body instanceof fs_1.ReadStream) { + await waitForOpenFile(this.options.body); + } + const { url: normalizedURL } = this.options; + if (!normalizedURL) { + throw new TypeError('Missing `url` property'); + } + this.requestUrl = normalizedURL.toString(); + decodeURI(this.requestUrl); + await this._finalizeBody(); + await this._makeRequest(); + if (this.destroyed) { + (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy(); + return; + } + // Queued writes etc. + for (const job of this[kJobs]) { + job(); + } + // Prevent memory leak + this[kJobs].length = 0; + this.requestInitialized = true; + } + catch (error) { + if (error instanceof RequestError) { + this._beforeError(error); + return; + } + // This is a workaround for https://github.com/nodejs/node/issues/33335 + if (!this.destroyed) { + this.destroy(error); + } + } + })(); + } + static normalizeArguments(url, options, defaults) { + var _a, _b, _c, _d, _e; + const rawOptions = options; + if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { + options = { ...defaults, ...url, ...options }; + } + else { + if (url && options && options.url !== undefined) { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); + } + options = { ...defaults, ...options }; + if (url !== undefined) { + options.url = url; + } + if (is_1.default.urlInstance(options.url)) { + options.url = new url_1.URL(options.url.toString()); + } + } + // TODO: Deprecate URL options in Got 12. + // Support extend-specific options + if (options.cache === false) { + options.cache = undefined; + } + if (options.dnsCache === false) { + options.dnsCache = undefined; + } + // Nice type assertions + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers); + is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache); + is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect); + is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress); + is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized); + if (options.https) { + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized); + is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); + is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); + } + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); + // `options.method` + if (is_1.default.string(options.method)) { + options.method = options.method.toUpperCase(); + } + else { + options.method = 'GET'; + } + // `options.headers` + if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) { + options.headers = { ...options.headers }; + } + else { + options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers }); + } + // Disallow legacy `url.Url` + if ('slashes' in options) { + throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.'); + } + // `options.auth` + if ('auth' in options) { + throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + // `options.searchParams` + if ('searchParams' in options) { + if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { + let searchParameters; + if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { + searchParameters = new url_1.URLSearchParams(options.searchParams); + } + else { + validateSearchParameters(options.searchParams); + searchParameters = new url_1.URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in options.searchParams) { + const value = options.searchParams[key]; + if (value === null) { + searchParameters.append(key, ''); + } + else if (value !== undefined) { + searchParameters.append(key, value); + } + } + } + // `normalizeArguments()` is also used to merge options + (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { + // Only use default if one isn't already defined + if (!searchParameters.has(key)) { + searchParameters.append(key, value); + } + }); + options.searchParams = searchParameters; + } + } + // `options.username` & `options.password` + options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; + options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; + // `options.prefixUrl` & `options.url` + if (is_1.default.undefined(options.prefixUrl)) { + options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; + } + else { + options.prefixUrl = options.prefixUrl.toString(); + if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { + options.prefixUrl += '/'; + } + } + if (is_1.default.string(options.url)) { + if (options.url.startsWith('/')) { + throw new Error('`input` must not start with a slash when using `prefixUrl`'); + } + options.url = options_to_url_1.default(options.prefixUrl + options.url, options); + } + else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) { + options.url = options_to_url_1.default(options.prefixUrl, options); + } + if (options.url) { + if ('port' in options) { + delete options.port; + } + // Make it possible to change `options.prefixUrl` + let { prefixUrl } = options; + Object.defineProperty(options, 'prefixUrl', { + set: (value) => { + const url = options.url; + if (!url.href.startsWith(value)) { + throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`); + } + options.url = new url_1.URL(value + url.href.slice(prefixUrl.length)); + prefixUrl = value; + }, + get: () => prefixUrl + }); + // Support UNIX sockets + let { protocol } = options.url; + if (protocol === 'unix:') { + protocol = 'http:'; + options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`); + } + // Set search params + if (options.searchParams) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + options.url.search = options.searchParams.toString(); + } + // Protocol check + if (protocol !== 'http:' && protocol !== 'https:') { + throw new UnsupportedProtocolError(options); + } + // Update `username` + if (options.username === '') { + options.username = options.url.username; + } + else { + options.url.username = options.username; + } + // Update `password` + if (options.password === '') { + options.password = options.url.password; + } + else { + options.url.password = options.password; + } + } + // `options.cookieJar` + const { cookieJar } = options; + if (cookieJar) { + let { setCookie, getCookieString } = cookieJar; + is_1.assert.function_(setCookie); + is_1.assert.function_(getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); + getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); + options.cookieJar = { + setCookie, + getCookieString: getCookieString + }; + } + } + // `options.cache` + const { cache } = options; + if (cache) { + if (!cacheableStore.has(cache)) { + cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { + const result = requestOptions[kRequest](requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is_1.default.promise(result)) { + // @ts-expect-error + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + result.once = (event, handler) => { + if (event === 'error') { + result.catch(handler); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch (_a) { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache)); + } + } + // `options.cacheOptions` + options.cacheOptions = { ...options.cacheOptions }; + // `options.dnsCache` + if (options.dnsCache === true) { + if (!globalDnsCache) { + globalDnsCache = new cacheable_lookup_1.default(); + } + options.dnsCache = globalDnsCache; + } + else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { + throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); + } + // `options.timeout` + if (is_1.default.number(options.timeout)) { + options.timeout = { request: options.timeout }; + } + else if (defaults && options.timeout !== defaults.timeout) { + options.timeout = { + ...defaults.timeout, + ...options.timeout + }; + } + else { + options.timeout = { ...options.timeout }; + } + // `options.context` + if (!options.context) { + options.context = {}; + } + // `options.hooks` + const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks); + options.hooks = { ...options.hooks }; + for (const event of exports.knownHookEvents) { + if (event in options.hooks) { + if (is_1.default.array(options.hooks[event])) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [...options.hooks[event]]; + } + else { + throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is_1.default(options.hooks[event])}`); + } + } + else { + options.hooks[event] = []; + } + } + if (defaults && !areHooksDefault) { + for (const event of exports.knownHookEvents) { + const defaultHooks = defaults.hooks[event]; + if (defaultHooks.length > 0) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [ + ...defaults.hooks[event], + ...options.hooks[event] + ]; + } + } + } + // DNS options + if ('family' in options) { + deprecation_warning_1.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'); + } + // HTTPS options + if (defaults === null || defaults === void 0 ? void 0 : defaults.https) { + options.https = { ...defaults.https, ...options.https }; + } + if ('rejectUnauthorized' in options) { + deprecation_warning_1.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'); + } + if ('checkServerIdentity' in options) { + deprecation_warning_1.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'); + } + if ('ca' in options) { + deprecation_warning_1.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'); + } + if ('key' in options) { + deprecation_warning_1.default('"options.key" was never documented, please use "options.https.key"'); + } + if ('cert' in options) { + deprecation_warning_1.default('"options.cert" was never documented, please use "options.https.certificate"'); + } + if ('passphrase' in options) { + deprecation_warning_1.default('"options.passphrase" was never documented, please use "options.https.passphrase"'); + } + if ('pfx' in options) { + deprecation_warning_1.default('"options.pfx" was never documented, please use "options.https.pfx"'); + } + // Other options + if ('followRedirects' in options) { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + if (options.agent) { + for (const key in options.agent) { + if (key !== 'http' && key !== 'https' && key !== 'http2') { + throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${key}\``); + } + } + } + options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; + // Set non-enumerable properties + exports.setNonEnumerableProperties([defaults, rawOptions], options); + return normalize_arguments_1.default(options, defaults); + } + _lockWrite() { + const onLockedWrite = () => { + throw new TypeError('The payload has been already provided'); + }; + this.write = onLockedWrite; + this.end = onLockedWrite; + } + _unlockWrite() { + this.write = super.write; + this.end = super.end; + } + async _finalizeBody() { + const { options } = this; + const { headers } = options; + const isForm = !is_1.default.undefined(options.form); + const isJSON = !is_1.default.undefined(options.json); + const isBody = !is_1.default.undefined(options.body); + const hasPayload = isForm || isJSON || isBody; + const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + this._cannotHaveBody = cannotHaveBody; + if (hasPayload) { + if (cannotHaveBody) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { + throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); + } + if (isBody && + !(options.body instanceof stream_1.Readable) && + !is_1.default.string(options.body) && + !is_1.default.buffer(options.body) && + !is_form_data_1.default(options.body)) { + throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); + } + if (isForm && !is_1.default.object(options.form)) { + throw new TypeError('The `form` option must be an Object'); + } + { + // Serialize body + const noContentType = !is_1.default.string(headers['content-type']); + if (isBody) { + // Special case for https://github.com/form-data/form-data + if (is_form_data_1.default(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + this[kBody] = options.body; + } + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + this[kBody] = (new url_1.URLSearchParams(options.form)).toString(); + } + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + this[kBody] = options.stringifyJson(options.json); + } + const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { + if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } + } + } + } + else if (cannotHaveBody) { + this._lockWrite(); + } + else { + this._unlockWrite(); + } + this[kBodySize] = Number(headers['content-length']) || undefined; + } + async _onResponseBase(response) { + const { options } = this; + const { url } = options; + this[kOriginalResponse] = response; + if (options.decompress) { + response = decompressResponse(response); + } + const statusCode = response.statusCode; + const typedResponse = response; + typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode]; + typedResponse.url = options.url.toString(); + typedResponse.requestUrl = this.requestUrl; + typedResponse.redirectUrls = this.redirects; + typedResponse.request = this; + typedResponse.isFromCache = response.fromCache || false; + typedResponse.ip = this.ip; + typedResponse.retryCount = this.retryCount; + this[kIsFromCache] = typedResponse.isFromCache; + this[kResponseSize] = Number(response.headers['content-length']) || undefined; + this[kResponse] = response; + response.once('end', () => { + this[kResponseSize] = this[kDownloadedSize]; + this.emit('downloadProgress', this.downloadProgress); + }); + response.once('error', (error) => { + // Force clean-up, because some packages don't do this. + // TODO: Fix decompress-response + response.destroy(); + this._beforeError(new ReadError(error, this)); + }); + response.once('aborted', () => { + this._beforeError(new ReadError({ + name: 'Error', + message: 'The server aborted pending request', + code: 'ECONNRESET' + }, this)); + }); + this.emit('downloadProgress', this.downloadProgress); + const rawCookies = response.headers['set-cookie']; + if (is_1.default.object(options.cookieJar) && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); + if (options.ignoreInvalidCookies) { + promises = promises.map(async (p) => p.catch(() => { })); + } + try { + await Promise.all(promises); + } + catch (error) { + this._beforeError(error); + return; + } + } + if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { + // We're being redirected, we don't care about the response. + // It'd be best to abort the request, but we can't because + // we would have to sacrifice the TCP connection. We don't want that. + response.resume(); + if (this[kRequest]) { + this[kCancelTimeouts](); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this[kRequest]; + this[kUnproxyEvents](); + } + const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD'; + if (shouldBeGet || !options.methodRewriting) { + // Server responded with "see other", indicating that the resource exists at another location, + // and the client should request it from that location via GET or HEAD. + options.method = 'GET'; + if ('body' in options) { + delete options.body; + } + if ('json' in options) { + delete options.json; + } + if ('form' in options) { + delete options.form; + } + this[kBody] = undefined; + delete options.headers['content-length']; + } + if (this.redirects.length >= options.maxRedirects) { + this._beforeError(new MaxRedirectsError(this)); + return; + } + try { + // Do not remove. See https://github.com/sindresorhus/got/pull/214 + const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); + // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 + const redirectUrl = new url_1.URL(redirectBuffer, url); + const redirectString = redirectUrl.toString(); + decodeURI(redirectString); + // eslint-disable-next-line no-inner-declarations + function isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; + } + if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { + this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in options.headers) { + delete options.headers.host; + } + if ('cookie' in options.headers) { + delete options.headers.cookie; + } + if ('authorization' in options.headers) { + delete options.headers.authorization; + } + if (options.username || options.password) { + options.username = ''; + options.password = ''; + } + } + else { + redirectUrl.username = options.username; + redirectUrl.password = options.password; + } + this.redirects.push(redirectString); + options.url = redirectUrl; + for (const hook of options.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(options, typedResponse); + } + this.emit('redirect', typedResponse, options); + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); + return; + } + return; + } + if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { + this._beforeError(new HTTPError(typedResponse)); + return; + } + response.on('readable', () => { + if (this[kTriggerRead]) { + this._read(); + } + }); + this.on('resume', () => { + response.resume(); + }); + this.on('pause', () => { + response.pause(); + }); + response.once('end', () => { + this.push(null); + }); + this.emit('response', response); + for (const destination of this[kServerResponsesPiped]) { + if (destination.headersSent) { + continue; + } + // eslint-disable-next-line guard-for-in + for (const key in response.headers) { + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + const value = response.headers[key]; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = statusCode; + } + } + async _onResponse(response) { + try { + await this._onResponseBase(response); + } + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); + } + } + _onRequest(request) { + const { options } = this; + const { timeout, url } = options; + http_timer_1.default(request); + this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); + const responseEventName = options.cache ? 'cacheableResponse' : 'response'; + request.once(responseEventName, (response) => { + void this._onResponse(response); + }); + request.once('error', (error) => { + var _a; + // Force clean-up, because some packages (e.g. nock) don't do this. + request.destroy(); + // Node.js <= 12.18.2 mistakenly emits the response `end` first. + (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); + error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); + this._beforeError(error); + }); + this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); + this[kRequest] = request; + this.emit('uploadProgress', this.uploadProgress); + // Send body + const body = this[kBody]; + const currentRequest = this.redirects.length === 0 ? this : request; + if (is_1.default.nodeStream(body)) { + body.pipe(currentRequest); + body.once('error', (error) => { + this._beforeError(new UploadError(error, this)); + }); + } + else { + this._unlockWrite(); + if (!is_1.default.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + this._lockWrite(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + this._lockWrite(); + } + } + this.emit('request', request); + } + async _createCacheableRequest(url, options) { + return new Promise((resolve, reject) => { + // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed + Object.assign(options, url_to_options_1.default(url)); + // `http-cache-semantics` checks this + // TODO: Fix this ignore. + // @ts-expect-error + delete options.url; + let request; + // This is ugly + const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { + // TODO: Fix `cacheable-response` + response._readableState.autoDestroy = false; + if (request) { + (await request).emit('cacheableResponse', response); + } + resolve(response); + }); + // Restore options + options.url = url; + cacheRequest.once('error', reject); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); + }); + } + async _makeRequest() { + var _a, _b, _c, _d, _e; + const { options } = this; + const { headers } = options; + for (const key in headers) { + if (is_1.default.undefined(headers[key])) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete headers[key]; + } + else if (is_1.default.null_(headers[key])) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } + } + if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; + } + // Set cookies + if (options.cookieJar) { + const cookieString = await options.cookieJar.getCookieString(options.url.toString()); + if (is_1.default.nonEmptyString(cookieString)) { + options.headers.cookie = cookieString; + } + } + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(options); + if (!is_1.default.undefined(result)) { + // @ts-expect-error Skip the type mismatch to support abstract responses + options.request = () => result; + break; + } + } + if (options.body && this[kBody] !== options.body) { + this[kBody] = options.body; + } + const { agent, request, timeout, url } = options; + if (options.dnsCache && !('lookup' in options)) { + options.lookup = options.dnsCache.lookup; + } + // UNIX sockets + if (url.hostname === 'unix') { + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches === null || matches === void 0 ? void 0 : matches.groups) { + const { socketPath, path } = matches.groups; + Object.assign(options, { + socketPath, + path, + host: '' + }); + } + } + const isHttps = url.protocol === 'https:'; + // Fallback function + let fallbackFn; + if (options.http2) { + fallbackFn = http2wrapper.auto; + } + else { + fallbackFn = isHttps ? https.request : http.request; + } + const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn; + // Cache support + const fn = options.cache ? this._createCacheableRequest : realFn; + // Pass an agent directly when HTTP2 is disabled + if (agent && !options.http2) { + options.agent = agent[isHttps ? 'https' : 'http']; + } + // Prepare plain HTTP request options + options[kRequest] = realFn; + delete options.request; + // TODO: Fix this ignore. + // @ts-expect-error + delete options.timeout; + const requestOptions = options; + requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; + requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; + requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; + requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; + // If `dnsLookupIpVersion` is not present do not override `family` + if (options.dnsLookupIpVersion !== undefined) { + try { + requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); + } + catch (_f) { + throw new Error('Invalid `dnsLookupIpVersion` option value'); + } + } + // HTTPS options remapping + if (options.https) { + if ('rejectUnauthorized' in options.https) { + requestOptions.rejectUnauthorized = options.https.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + requestOptions.checkServerIdentity = options.https.checkServerIdentity; + } + if (options.https.certificateAuthority) { + requestOptions.ca = options.https.certificateAuthority; + } + if (options.https.certificate) { + requestOptions.cert = options.https.certificate; + } + if (options.https.key) { + requestOptions.key = options.https.key; + } + if (options.https.passphrase) { + requestOptions.passphrase = options.https.passphrase; + } + if (options.https.pfx) { + requestOptions.pfx = options.https.pfx; + } + } + try { + let requestOrResponse = await fn(url, requestOptions); + if (is_1.default.undefined(requestOrResponse)) { + requestOrResponse = fallbackFn(url, requestOptions); + } + // Restore options + options.request = request; + options.timeout = timeout; + options.agent = agent; + // HTTPS options restore + if (options.https) { + if ('rejectUnauthorized' in options.https) { + delete requestOptions.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + // @ts-expect-error - This one will be removed when we remove the alias. + delete requestOptions.checkServerIdentity; + } + if (options.https.certificateAuthority) { + delete requestOptions.ca; + } + if (options.https.certificate) { + delete requestOptions.cert; + } + if (options.https.key) { + delete requestOptions.key; + } + if (options.https.passphrase) { + delete requestOptions.passphrase; + } + if (options.https.pfx) { + delete requestOptions.pfx; + } + } + if (isClientRequest(requestOrResponse)) { + this._onRequest(requestOrResponse); + // Emit the response after the stream has been ended + } + else if (this.writable) { + this.once('finish', () => { + void this._onResponse(requestOrResponse); + }); + this._unlockWrite(); + this.end(); + this._lockWrite(); + } + else { + void this._onResponse(requestOrResponse); + } + } + catch (error) { + if (error instanceof CacheableRequest.CacheError) { + throw new CacheError(error, this); + } + throw new RequestError(error.message, error, this); + } + } + async _error(error) { + try { + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + catch (error_) { + error = new RequestError(error_.message, error_, this); + } + this.destroy(error); + } + _beforeError(error) { + if (this[kStopReading]) { + return; + } + const { options } = this; + const retryCount = this.retryCount + 1; + this[kStopReading] = true; + if (!(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + const typedError = error; + const { response } = typedError; + void (async () => { + if (response && !response.body) { + response.setEncoding(this._readableState.encoding); + try { + response.rawBody = await get_buffer_1.default(response); + response.body = response.rawBody.toString(); + } + catch (_a) { } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + backoff = await options.retry.calculateDelay({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: calculate_retry_delay_1.default({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: 0 + }) + }); + } + catch (error_) { + void this._error(new RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + const retry = async () => { + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(this.options, typedError, retryCount); + } + } + catch (error_) { + void this._error(new RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', retryCount, error); + }; + this[kRetryTimeout] = setTimeout(retry, backoff); + return; + } + } + void this._error(typedError); + })(); + } + _read() { + this[kTriggerRead] = true; + const response = this[kResponse]; + if (response && !this[kStopReading]) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this[kTriggerRead] = false; + } + let data; + while ((data = response.read()) !== null) { + this[kDownloadedSize] += data.length; + this[kStartedReading] = true; + const progress = this.downloadProgress; + if (progress.percent < 1) { + this.emit('downloadProgress', progress); + } + this.push(data); + } + } + } + // Node.js 12 has incorrect types, so the encoding must be a string + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this.requestInitialized) { + write(); + } + else { + this[kJobs].push(write); + } + } + _writeRequest(chunk, encoding, callback) { + if (this[kRequest].destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._progressCallbacks.push(() => { + this[kUploadedSize] += Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); + } + }); + // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. + this[kRequest].write(chunk, encoding, (error) => { + if (!error && this._progressCallbacks.length > 0) { + this._progressCallbacks.shift()(); + } + callback(error); + }); + } + _final(callback) { + const endRequest = () => { + // FIX: Node.js 10 calls the write callback AFTER the end callback! + while (this._progressCallbacks.length !== 0) { + this._progressCallbacks.shift()(); + } + // We need to check if `this[kRequest]` is present, + // because it isn't when we use cache. + if (!(kRequest in this)) { + callback(); + return; + } + if (this[kRequest].destroyed) { + callback(); + return; + } + this[kRequest].end((error) => { + if (!error) { + this[kBodySize] = this[kUploadedSize]; + this.emit('uploadProgress', this.uploadProgress); + this[kRequest].emit('upload-complete'); + } + callback(error); + }); + }; + if (this.requestInitialized) { + endRequest(); + } + else { + this[kJobs].push(endRequest); + } + } + _destroy(error, callback) { + var _a; + this[kStopReading] = true; + // Prevent further retries + clearTimeout(this[kRetryTimeout]); + if (kRequest in this) { + this[kCancelTimeouts](); + // TODO: Remove the next `if` when these get fixed: + // - https://github.com/nodejs/node/issues/32851 + if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) { + this[kRequest].destroy(); + } + } + if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + callback(error); + } + get _isAboutToError() { + return this[kStopReading]; + } + /** + The remote IP address. + */ + get ip() { + var _a; + return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; + } + /** + Indicates whether the request has been aborted or not. + */ + get aborted() { + var _a, _b, _c; + return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); + } + get socket() { + var _a, _b; + return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; + } + /** + Progress event for downloading (receiving a response). + */ + get downloadProgress() { + let percent; + if (this[kResponseSize]) { + percent = this[kDownloadedSize] / this[kResponseSize]; + } + else if (this[kResponseSize] === this[kDownloadedSize]) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this[kDownloadedSize], + total: this[kResponseSize] + }; + } + /** + Progress event for uploading (sending a request). + */ + get uploadProgress() { + let percent; + if (this[kBodySize]) { + percent = this[kUploadedSize] / this[kBodySize]; + } + else if (this[kBodySize] === this[kUploadedSize]) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this[kUploadedSize], + total: this[kBodySize] + }; + } + /** + The object contains the following properties: + + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + + If something has not been measured yet, it will be `undefined`. + + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + get timings() { + var _a; + return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; + } + /** + Whether the response was retrieved from the cache. + */ + get isFromCache() { + return this[kIsFromCache]; + } + pipe(destination, options) { + if (this[kStartedReading]) { + throw new Error('Failed to pipe. The response has been emitted already.'); + } + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].add(destination); + } + return super.pipe(destination, options); + } + unpipe(destination) { + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].delete(destination); + } + super.unpipe(destination); + return this; + } +} +exports["default"] = Request; + + +/***/ }), + +/***/ 1037: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; +const conversionTable = { + auto: 0, + ipv4: 4, + ipv6: 6 +}; +exports.isDnsLookupIpVersion = (value) => { + return value in conversionTable; +}; +exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => { + if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) { + return conversionTable[dnsLookupIpVersion]; + } + throw new Error('Invalid DNS lookup IP version'); +}; + + +/***/ }), + +/***/ 9296: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs_1 = __nccwpck_require__(9896); +const util_1 = __nccwpck_require__(9023); +const is_1 = __nccwpck_require__(4001); +const is_form_data_1 = __nccwpck_require__(6751); +const statAsync = util_1.promisify(fs_1.stat); +exports["default"] = async (body, headers) => { + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); + } + if (!body) { + return 0; + } + if (is_1.default.string(body)) { + return Buffer.byteLength(body); + } + if (is_1.default.buffer(body)) { + return body.length; + } + if (is_form_data_1.default(body)) { + return util_1.promisify(body.getLength.bind(body))(); + } + if (body instanceof fs_1.ReadStream) { + const { size } = await statAsync(body.path); + if (size === 0) { + return undefined; + } + return size; + } + return undefined; +}; + + +/***/ }), + +/***/ 4858: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// TODO: Update https://github.com/sindresorhus/get-stream +const getBuffer = async (stream) => { + const chunks = []; + let length = 0; + for await (const chunk of stream) { + chunks.push(chunk); + length += Buffer.byteLength(chunk); + } + if (Buffer.isBuffer(chunks[0])) { + return Buffer.concat(chunks, length); + } + return Buffer.from(chunks.join('')); +}; +exports["default"] = getBuffer; + + +/***/ }), + +/***/ 6751: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(4001); +exports["default"] = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); + + +/***/ }), + +/***/ 4350: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isResponseOk = void 0; +exports.isResponseOk = (response) => { + const { statusCode } = response; + const limitStatusCode = response.request.options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; +}; + + +/***/ }), + +/***/ 5743: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* istanbul ignore file: deprecated */ +const url_1 = __nccwpck_require__(7016); +const keys = [ + 'protocol', + 'host', + 'hostname', + 'port', + 'pathname', + 'search' +]; +exports["default"] = (origin, options) => { + var _a, _b; + if (options.path) { + if (options.pathname) { + throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); + } + if (options.search) { + throw new TypeError('Parameters `path` and `search` are mutually exclusive.'); + } + if (options.searchParams) { + throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.'); + } + } + if (options.search && options.searchParams) { + throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.'); + } + if (!origin) { + if (!options.protocol) { + throw new TypeError('No URL protocol specified'); + } + origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`; + } + const url = new url_1.URL(origin); + if (options.path) { + const searchIndex = options.path.indexOf('?'); + if (searchIndex === -1) { + options.pathname = options.path; + } + else { + options.pathname = options.path.slice(0, searchIndex); + options.search = options.path.slice(searchIndex + 1); + } + delete options.path; + } + for (const key of keys) { + if (options[key]) { + url[key] = options[key].toString(); + } + } + return url; +}; + + +/***/ }), + +/***/ 7813: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +function default_1(from, to, events) { + const fns = {}; + for (const event of events) { + fns[event] = (...args) => { + to.emit(event, ...args); + }; + from.on(event, fns[event]); + } + return () => { + for (const event of events) { + from.off(event, fns[event]); + } + }; +} +exports["default"] = default_1; + + +/***/ }), + +/***/ 4501: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TimeoutError = void 0; +const net = __nccwpck_require__(9278); +const unhandle_1 = __nccwpck_require__(9246); +const reentry = Symbol('reentry'); +const noop = () => { }; +class TimeoutError extends Error { + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; + } +} +exports.TimeoutError = TimeoutError; +exports["default"] = (request, delays, options) => { + if (reentry in request) { + return noop; + } + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle_1.default(); + const addTimeout = (delay, callback, event) => { + var _a; + const timeout = setTimeout(callback, delay, delay, event); + (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; + } + }); + request.once('close', cancelTimeouts); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeouts); + }); + if (typeof delays.request !== 'undefined') { + addTimeout(delays.request, timeoutHandler, 'request'); + } + if (typeof delays.socket !== 'undefined') { + const socketTimeoutHandler = () => { + timeoutHandler(delays.socket, 'socket'); + }; + request.setTimeout(delays.socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); + } + once(request, 'socket', (socket) => { + var _a; + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0); + if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (typeof delays.connect !== 'undefined') { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (typeof delays.send !== 'undefined') { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); + if (typeof delays.response !== 'undefined') { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); + } + return cancelTimeouts; +}; + + +/***/ }), + +/***/ 9246: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +exports["default"] = () => { + const handlers = []; + return { + once(origin, event, fn) { + origin.once(event, fn); + handlers.push({ origin, event, fn }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + } + }; +}; + + +/***/ }), + +/***/ 3873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(4001); +exports["default"] = (url) => { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; + if (is_1.default.string(url.port) && url.port.length > 0) { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } + return options; +}; + + +/***/ }), + +/***/ 7791: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class WeakableMap { + constructor() { + this.weakMap = new WeakMap(); + this.map = new Map(); + } + set(key, value) { + if (typeof key === 'object') { + this.weakMap.set(key, value); + } + else { + this.map.set(key, value); + } + } + get(key) { + if (typeof key === 'object') { + return this.weakMap.get(key); + } + return this.map.get(key); + } + has(key) { + if (typeof key === 'object') { + return this.weakMap.has(key); + } + return this.map.has(key); + } +} +exports["default"] = WeakableMap; + + +/***/ }), + +/***/ 9941: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultHandler = void 0; +const is_1 = __nccwpck_require__(4001); +const as_promise_1 = __nccwpck_require__(2126); +const create_rejection_1 = __nccwpck_require__(7814); +const core_1 = __nccwpck_require__(6825); +const deep_freeze_1 = __nccwpck_require__(2949); +const errors = { + RequestError: as_promise_1.RequestError, + CacheError: as_promise_1.CacheError, + ReadError: as_promise_1.ReadError, + HTTPError: as_promise_1.HTTPError, + MaxRedirectsError: as_promise_1.MaxRedirectsError, + TimeoutError: as_promise_1.TimeoutError, + ParseError: as_promise_1.ParseError, + CancelError: as_promise_1.CancelError, + UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, + UploadError: as_promise_1.UploadError +}; +// The `delay` package weighs 10KB (!) +const delay = async (ms) => new Promise(resolve => { + setTimeout(resolve, ms); +}); +const { normalizeArguments } = core_1.default; +const mergeOptions = (...sources) => { + let mergedOptions; + for (const source of sources) { + mergedOptions = normalizeArguments(undefined, source, mergedOptions); + } + return mergedOptions; +}; +const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); +const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); +const aliases = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete' +]; +exports.defaultHandler = (options, next) => next(options); +const callInitHooks = (hooks, options) => { + if (hooks) { + for (const hook of hooks) { + hook(options); + } + } +}; +const create = (defaults) => { + // Proxy properties from next handlers + defaults._rawHandlers = defaults.handlers; + defaults.handlers = defaults.handlers.map(fn => ((options, next) => { + // This will be assigned by assigning result + let root; + const result = fn(options, newOptions => { + root = next(newOptions); + return root; + }); + if (result !== root && !options.isStream && root) { + const typedResult = result; + const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult; + Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root)); + Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root)); + // These should point to the new promise + // eslint-disable-next-line promise/prefer-await-to-then + typedResult.then = promiseThen; + typedResult.catch = promiseCatch; + typedResult.finally = promiseFianlly; + } + return result; + })); + // Got interface + const got = ((url, options = {}, _defaults) => { + var _a, _b; + let iteration = 0; + const iterateHandlers = (newOptions) => { + return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); + }; + // TODO: Remove this in Got 12. + if (is_1.default.plainObject(url)) { + const mergedOptions = { + ...url, + ...options + }; + core_1.setNonEnumerableProperties([url, options], mergedOptions); + options = mergedOptions; + url = undefined; + } + try { + // Call `init` hooks + let initHookError; + try { + callInitHooks(defaults.options.hooks.init, options); + callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); + } + catch (error) { + initHookError = error; + } + // Normalize options & call handlers + const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); + normalizedOptions[core_1.kIsNormalizedAlready] = true; + if (initHookError) { + throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); + } + return iterateHandlers(normalizedOptions); + } + catch (error) { + if (options.isStream) { + throw error; + } + else { + return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); + } + } + }); + got.extend = (...instancesOrOptions) => { + const optionsArray = [defaults.options]; + let handlers = [...defaults._rawHandlers]; + let isMutableDefaults; + for (const value of instancesOrOptions) { + if (isGotInstance(value)) { + optionsArray.push(value.defaults.options); + handlers.push(...value.defaults._rawHandlers); + isMutableDefaults = value.defaults.mutableDefaults; + } + else { + optionsArray.push(value); + if ('handlers' in value) { + handlers.push(...value.handlers); + } + isMutableDefaults = value.mutableDefaults; + } + } + handlers = handlers.filter(handler => handler !== exports.defaultHandler); + if (handlers.length === 0) { + handlers.push(exports.defaultHandler); + } + return create({ + options: mergeOptions(...optionsArray), + handlers, + mutableDefaults: Boolean(isMutableDefaults) + }); + }; + // Pagination + const paginateEach = (async function* (url, options) { + // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. + // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. + // @ts-expect-error + let normalizedOptions = normalizeArguments(url, options, defaults.options); + normalizedOptions.resolveBodyOnly = false; + const pagination = normalizedOptions.pagination; + if (!is_1.default.object(pagination)) { + throw new TypeError('`options.pagination` must be implemented'); + } + const all = []; + let { countLimit } = pagination; + let numberOfRequests = 0; + while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await delay(pagination.backoff); + } + // @ts-expect-error FIXME! + // TODO: Throw when result is not an instance of Response + // eslint-disable-next-line no-await-in-loop + const result = (await got(undefined, undefined, normalizedOptions)); + // eslint-disable-next-line no-await-in-loop + const parsed = await pagination.transform(result); + const current = []; + for (const item of parsed) { + if (pagination.filter(item, all, current)) { + if (!pagination.shouldContinue(item, all, current)) { + return; + } + yield item; + if (pagination.stackAllItems) { + all.push(item); + } + current.push(item); + if (--countLimit <= 0) { + return; + } + } + } + const optionsToMerge = pagination.paginate(result, all, current); + if (optionsToMerge === false) { + return; + } + if (optionsToMerge === result.request.options) { + normalizedOptions = result.request.options; + } + else if (optionsToMerge !== undefined) { + normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions); + } + numberOfRequests++; + } + }); + got.paginate = paginateEach; + got.paginate.all = (async (url, options) => { + const results = []; + for await (const item of paginateEach(url, options)) { + results.push(item); + } + return results; + }); + // For those who like very descriptive names + got.paginate.each = paginateEach; + // Stream API + got.stream = ((url, options) => got(url, { ...options, isStream: true })); + // Shortcuts + for (const method of aliases) { + got[method] = ((url, options) => got(url, { ...options, method })); + got.stream[method] = ((url, options) => { + return got(url, { ...options, method, isStream: true }); + }); + } + Object.assign(got, errors); + Object.defineProperty(got, 'defaults', { + value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), + writable: defaults.mutableDefaults, + configurable: defaults.mutableDefaults, + enumerable: true + }); + got.mergeOptions = mergeOptions; + return got; +}; +exports["default"] = create; +__exportStar(__nccwpck_require__(9612), exports); + + +/***/ }), + +/***/ 6757: +/***/ (function(module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(7016); +const create_1 = __nccwpck_require__(9941); +const defaults = { + options: { + method: 'GET', + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE' + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524 + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN' + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue + }, + timeout: {}, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)' + }, + hooks: { + init: [], + beforeRequest: [], + beforeRedirect: [], + beforeRetry: [], + beforeError: [], + afterResponse: [] + }, + cache: undefined, + dnsCache: undefined, + decompress: true, + throwHttpErrors: true, + followRedirect: true, + isStream: false, + responseType: 'text', + resolveBodyOnly: false, + maxRedirects: 10, + prefixUrl: '', + methodRewriting: true, + ignoreInvalidCookies: false, + context: {}, + // TODO: Set this to `true` when Got 12 gets released + http2: false, + allowGetBody: false, + https: undefined, + pagination: { + transform: (response) => { + if (response.request.options.responseType === 'json') { + return response.body; + } + return JSON.parse(response.body); + }, + paginate: response => { + if (!Reflect.has(response.headers, 'link')) { + return false; + } + const items = response.headers.link.split(','); + let next; + for (const item of items) { + const parsed = item.split(';'); + if (parsed[1].includes('next')) { + next = parsed[0].trimStart().trim(); + next = next.slice(1, -1); + break; + } + } + if (next) { + const options = { + url: new url_1.URL(next) + }; + return options; + } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Infinity, + backoff: 0, + requestLimit: 10000, + stackAllItems: true + }, + parseJson: (text) => JSON.parse(text), + stringifyJson: (object) => JSON.stringify(object), + cacheOptions: {} + }, + handlers: [create_1.defaultHandler], + mutableDefaults: false +}; +const got = create_1.default(defaults); +exports["default"] = got; +// For CommonJS default export support +module.exports = got; +module.exports["default"] = got; +module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 +__exportStar(__nccwpck_require__(9941), exports); +__exportStar(__nccwpck_require__(2126), exports); + + +/***/ }), + +/***/ 9612: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 2949: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(4001); +function deepFreeze(object) { + for (const value of Object.values(object)) { + if (is_1.default.plainObject(value) || is_1.default.array(value)) { + deepFreeze(value); + } + } + return Object.freeze(object); +} +exports["default"] = deepFreeze; + + +/***/ }), + +/***/ 9796: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const alreadyWarned = new Set(); +exports["default"] = (message) => { + if (alreadyWarned.has(message)) { + return; + } + alreadyWarned.add(message); + // @ts-expect-error Missing types. + process.emitWarning(`Got: ${message}`, { + type: 'DeprecationWarning' + }); +}; + + +/***/ }), + +/***/ 4584: +/***/ ((module) => { + +"use strict"; + +// rfc7231 6.1 +const statusCodeCacheableByDefault = new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +// This implementation does not understand partial responses (206) +const understoodStatuses = new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +const errorStatusCodes = new Set([ + 500, + 502, + 503, + 504, +]); + +const hopByHopHeaders = { + date: true, // included, because we add Age update Date + connection: true, + 'keep-alive': true, + 'proxy-authenticate': true, + 'proxy-authorization': true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, +}; + +const excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + 'content-length': true, + 'content-encoding': true, + 'transfer-encoding': true, + 'content-range': true, +}; + +function toNumberOrZero(s) { + const n = parseInt(s, 10); + return isFinite(n) ? n : 0; +} + +// RFC 5861 +function isErrorResponse(response) { + // consider undefined response as faulty + if(!response) { + return true + } + return errorStatusCodes.has(response.status); +} + +function parseCacheControl(header) { + const cc = {}; + if (!header) return cc; + + // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), + // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale + const parts = header.trim().split(/,/); + for (const part of parts) { + const [k, v] = part.split(/=/, 2); + cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); + } + + return cc; +} + +function formatCacheControl(cc) { + let parts = []; + for (const k in cc) { + const v = cc[k]; + parts.push(v === true ? k : k + '=' + v); + } + if (!parts.length) { + return undefined; + } + return parts.join(', '); +} + +module.exports = class CachePolicy { + constructor( + req, + res, + { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject, + } = {} + ) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } + + if (!res || !res.headers) { + throw Error('Response headers missing'); + } + this._assertRequestHasHeaders(req); + + this._responseTime = this.now(); + this._isShared = shared !== false; + this._cacheHeuristic = + undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + this._immutableMinTtl = + undefined !== immutableMinTimeToLive + ? immutableMinTimeToLive + : 24 * 3600 * 1000; + + this._status = 'status' in res ? res.status : 200; + this._resHeaders = res.headers; + this._rescc = parseCacheControl(res.headers['cache-control']); + this._method = 'method' in req ? req.method : 'GET'; + this._url = req.url; + this._host = req.headers.host; + this._noAuthorization = !req.headers.authorization; + this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used + this._reqcc = parseCacheControl(req.headers['cache-control']); + + // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, + // so there's no point stricly adhering to the blindly copy&pasted directives. + if ( + ignoreCargoCult && + 'pre-check' in this._rescc && + 'post-check' in this._rescc + ) { + delete this._rescc['pre-check']; + delete this._rescc['post-check']; + delete this._rescc['no-cache']; + delete this._rescc['no-store']; + delete this._rescc['must-revalidate']; + this._resHeaders = Object.assign({}, this._resHeaders, { + 'cache-control': formatCacheControl(this._rescc), + }); + delete this._resHeaders.expires; + delete this._resHeaders.pragma; + } + + // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive + // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). + if ( + res.headers['cache-control'] == null && + /no-cache/.test(res.headers.pragma) + ) { + this._rescc['no-cache'] = true; + } + } + + now() { + return Date.now(); + } + + storable() { + // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. + return !!( + !this._reqcc['no-store'] && + // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + ('GET' === this._method || + 'HEAD' === this._method || + ('POST' === this._method && this._hasExplicitExpiration())) && + // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && + // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc['no-store'] && + // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && + // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || + this._noAuthorization || + this._allowsStoringAuthenticated()) && + // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || + // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc['max-age'] || + (this._isShared && this._rescc['s-maxage']) || + this._rescc.public || + // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status)) + ); + } + + _hasExplicitExpiration() { + // 4.2.1 Calculating Freshness Lifetime + return ( + (this._isShared && this._rescc['s-maxage']) || + this._rescc['max-age'] || + this._resHeaders.expires + ); + } + + _assertRequestHasHeaders(req) { + if (!req || !req.headers) { + throw Error('Request headers missing'); + } + } + + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); + + // When presented with a request, a cache MUST NOT reuse a stored response, unless: + // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, + // unless the stored response is successfully validated (Section 4.3), and + const requestCC = parseCacheControl(req.headers['cache-control']); + if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { + return false; + } + + if (requestCC['max-age'] && this.age() > requestCC['max-age']) { + return false; + } + + if ( + requestCC['min-fresh'] && + this.timeToLive() < 1000 * requestCC['min-fresh'] + ) { + return false; + } + + // the stored response is either: + // fresh, or allowed to be served stale + if (this.stale()) { + const allowsStale = + requestCC['max-stale'] && + !this._rescc['must-revalidate'] && + (true === requestCC['max-stale'] || + requestCC['max-stale'] > this.age() - this.maxAge()); + if (!allowsStale) { + return false; + } + } + + return this._requestMatches(req, false); + } + + _requestMatches(req, allowHeadMethod) { + // The presented effective request URI and that of the stored response match, and + return ( + (!this._url || this._url === req.url) && + this._host === req.headers.host && + // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || + this._method === req.method || + (allowHeadMethod && 'HEAD' === req.method)) && + // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req) + ); + } + + _allowsStoringAuthenticated() { + // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. + return ( + this._rescc['must-revalidate'] || + this._rescc.public || + this._rescc['s-maxage'] + ); + } + + _varyMatches(req) { + if (!this._resHeaders.vary) { + return true; + } + + // A Vary header field-value of "*" always fails to match + if (this._resHeaders.vary === '*') { + return false; + } + + const fields = this._resHeaders.vary + .trim() + .toLowerCase() + .split(/\s*,\s*/); + for (const name of fields) { + if (req.headers[name] !== this._reqHeaders[name]) return false; + } + return true; + } + + _copyWithoutHopByHopHeaders(inHeaders) { + const headers = {}; + for (const name in inHeaders) { + if (hopByHopHeaders[name]) continue; + headers[name] = inHeaders[name]; + } + // 9.1. Connection + if (inHeaders.connection) { + const tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (const name of tokens) { + delete headers[name]; + } + } + if (headers.warning) { + const warnings = headers.warning.split(/,/).filter(warning => { + return !/^\s*1[0-9][0-9]/.test(warning); + }); + if (!warnings.length) { + delete headers.warning; + } else { + headers.warning = warnings.join(',').trim(); + } + } + return headers; + } + + responseHeaders() { + const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); + const age = this.age(); + + // A cache SHOULD generate 113 warning if it heuristically chose a freshness + // lifetime greater than 24 hours and the response's age is greater than 24 hours. + if ( + age > 3600 * 24 && + !this._hasExplicitExpiration() && + this.maxAge() > 3600 * 24 + ) { + headers.warning = + (headers.warning ? `${headers.warning}, ` : '') + + '113 - "rfc7234 5.5.4"'; + } + headers.age = `${Math.round(age)}`; + headers.date = new Date(this.now()).toUTCString(); + return headers; + } + + /** + * Value of the Date response header or current time if Date was invalid + * @return timestamp + */ + date() { + const serverDate = Date.parse(this._resHeaders.date); + if (isFinite(serverDate)) { + return serverDate; + } + return this._responseTime; + } + + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(); + + const residentTime = (this.now() - this._responseTime) / 1000; + return age + residentTime; + } + + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } + + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc['no-cache']) { + return 0; + } + + // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default + // so this implementation requires explicit opt-in via public header + if ( + this._isShared && + (this._resHeaders['set-cookie'] && + !this._rescc.public && + !this._rescc.immutable) + ) { + return 0; + } + + if (this._resHeaders.vary === '*') { + return 0; + } + + if (this._isShared) { + if (this._rescc['proxy-revalidate']) { + return 0; + } + // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. + if (this._rescc['s-maxage']) { + return toNumberOrZero(this._rescc['s-maxage']); + } + } + + // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. + if (this._rescc['max-age']) { + return toNumberOrZero(this._rescc['max-age']); + } + + const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + + const serverDate = this.date(); + if (this._resHeaders.expires) { + const expires = Date.parse(this._resHeaders.expires); + // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). + if (Number.isNaN(expires) || expires < serverDate) { + return 0; + } + return Math.max(defaultMinTtl, (expires - serverDate) / 1000); + } + + if (this._resHeaders['last-modified']) { + const lastModified = Date.parse(this._resHeaders['last-modified']); + if (isFinite(lastModified) && serverDate > lastModified) { + return Math.max( + defaultMinTtl, + ((serverDate - lastModified) / 1000) * this._cacheHeuristic + ); + } + } + + return defaultMinTtl; + } + + timeToLive() { + const age = this.maxAge() - this.age(); + const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); + const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; + } + + stale() { + return this.maxAge() <= this.age(); + } + + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); + } + + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + } + + static fromObject(obj) { + return new this(undefined, undefined, { _fromObject: obj }); + } + + _fromObject(obj) { + if (this._responseTime) throw Error('Reinitialized'); + if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + + this._responseTime = obj.t; + this._isShared = obj.sh; + this._cacheHeuristic = obj.ch; + this._immutableMinTtl = + obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; + this._status = obj.st; + this._resHeaders = obj.resh; + this._rescc = obj.rescc; + this._method = obj.m; + this._url = obj.u; + this._host = obj.h; + this._noAuthorization = obj.a; + this._reqHeaders = obj.reqh; + this._reqcc = obj.reqcc; + } + + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc, + }; + } + + /** + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. + */ + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + + // This implementation does not understand range requests + delete headers['if-range']; + + if (!this._requestMatches(incomingReq, true) || !this.storable()) { + // revalidation allowed via HEAD + // not for the same resource, or wasn't allowed to be cached anyway + delete headers['if-none-match']; + delete headers['if-modified-since']; + return headers; + } + + /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ + if (this._resHeaders.etag) { + headers['if-none-match'] = headers['if-none-match'] + ? `${headers['if-none-match']}, ${this._resHeaders.etag}` + : this._resHeaders.etag; + } + + // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. + const forbidsWeakValidators = + headers['accept-ranges'] || + headers['if-match'] || + headers['if-unmodified-since'] || + (this._method && this._method != 'GET'); + + /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. + Note: This implementation does not understand partial responses (206) */ + if (forbidsWeakValidators) { + delete headers['if-modified-since']; + + if (headers['if-none-match']) { + const etags = headers['if-none-match'] + .split(/,/) + .filter(etag => { + return !/^\s*W\//.test(etag); + }); + if (!etags.length) { + delete headers['if-none-match']; + } else { + headers['if-none-match'] = etags.join(',').trim(); + } + } + } else if ( + this._resHeaders['last-modified'] && + !headers['if-modified-since'] + ) { + headers['if-modified-since'] = this._resHeaders['last-modified']; + } + + return headers; + } + + /** + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} + */ + revalidatedPolicy(request, response) { + this._assertRequestHasHeaders(request); + if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful + return { + modified: false, + matches: false, + policy: this, + }; + } + if (!response || !response.headers) { + throw Error('Response headers missing'); + } + + // These aren't going to be supported exactly, since one CachePolicy object + // doesn't know about all the other cached objects. + let matches = false; + if (response.status !== undefined && response.status != 304) { + matches = false; + } else if ( + response.headers.etag && + !/^\s*W\//.test(response.headers.etag) + ) { + // "All of the stored responses with the same strong validator are selected. + // If none of the stored responses contain the same strong validator, + // then the cache MUST NOT use the new response to update any stored responses." + matches = + this._resHeaders.etag && + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag; + } else if (this._resHeaders.etag && response.headers.etag) { + // "If the new response contains a weak validator and that validator corresponds + // to one of the cache's stored responses, + // then the most recent of those matching stored responses is selected for update." + matches = + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag.replace(/^\s*W\//, ''); + } else if (this._resHeaders['last-modified']) { + matches = + this._resHeaders['last-modified'] === + response.headers['last-modified']; + } else { + // If the new response does not include any form of validator (such as in the case where + // a client generates an If-Modified-Since request from a source other than the Last-Modified + // response header field), and there is only one stored response, and that stored response also + // lacks a validator, then that stored response is selected for update. + if ( + !this._resHeaders.etag && + !this._resHeaders['last-modified'] && + !response.headers.etag && + !response.headers['last-modified'] + ) { + matches = true; + } + } + + if (!matches) { + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: false, + }; + } + + // use other header fields provided in the 304 (Not Modified) response to replace all instances + // of the corresponding header fields in the stored response. + const headers = {}; + for (const k in this._resHeaders) { + headers[k] = + k in response.headers && !excludedFromRevalidationUpdate[k] + ? response.headers[k] + : this._resHeaders[k]; + } + + const newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers, + }); + return { + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl, + }), + modified: false, + matches: true, + }; + } +}; + + +/***/ }), + +/***/ 685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const EventEmitter = __nccwpck_require__(4434); +const tls = __nccwpck_require__(4756); +const http2 = __nccwpck_require__(5675); +const QuickLRU = __nccwpck_require__(5475); + +const kCurrentStreamsCount = Symbol('currentStreamsCount'); +const kRequest = Symbol('request'); +const kOriginSet = Symbol('cachedOriginSet'); +const kGracefullyClosing = Symbol('gracefullyClosing'); + +const nameKeys = [ + // `http2.connect()` options + 'maxDeflateDynamicTableSize', + 'maxSessionMemory', + 'maxHeaderListPairs', + 'maxOutstandingPings', + 'maxReservedRemoteStreams', + 'maxSendHeaderBlockLength', + 'paddingStrategy', + + // `tls.connect()` options + 'localAddress', + 'path', + 'rejectUnauthorized', + 'minDHSize', + + // `tls.createSecureContext()` options + 'ca', + 'cert', + 'clientCertEngine', + 'ciphers', + 'key', + 'pfx', + 'servername', + 'minVersion', + 'maxVersion', + 'secureProtocol', + 'crl', + 'honorCipherOrder', + 'ecdhCurve', + 'dhparam', + 'secureOptions', + 'sessionIdContext' +]; + +const getSortedIndex = (array, value, compare) => { + let low = 0; + let high = array.length; + + while (low < high) { + const mid = (low + high) >>> 1; + + /* istanbul ignore next */ + if (compare(array[mid], value)) { + // This never gets called because we use descending sort. Better to have this anyway. + low = mid + 1; + } else { + high = mid; + } + } + + return low; +}; + +const compareSessions = (a, b) => { + return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; +}; + +// See https://tools.ietf.org/html/rfc8336 +const closeCoveredSessions = (where, session) => { + // Clients SHOULD NOT emit new requests on any connection whose Origin + // Set is a proper subset of another connection's Origin Set, and they + // SHOULD close it once all outstanding requests are satisfied. + for (const coveredSession of where) { + if ( + // The set is a proper subset when its length is less than the other set. + coveredSession[kOriginSet].length < session[kOriginSet].length && + + // And the other set includes all elements of the subset. + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && + + // Makes sure that the session can handle all requests from the covered session. + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams + ) { + // This allows pending requests to finish and prevents making new requests. + gracefullyClose(coveredSession); + } + } +}; + +// This is basically inverted `closeCoveredSessions(...)`. +const closeSessionIfCovered = (where, coveredSession) => { + for (const session of where) { + if ( + coveredSession[kOriginSet].length < session[kOriginSet].length && + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams + ) { + gracefullyClose(coveredSession); + } + } +}; + +const getSessions = ({agent, isFree}) => { + const result = {}; + + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in agent.sessions) { + const sessions = agent.sessions[normalizedOptions]; + + const filtered = sessions.filter(session => { + const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + + return isFree ? result : !result; + }); + + if (filtered.length !== 0) { + result[normalizedOptions] = filtered; + } + } + + return result; +}; + +const gracefullyClose = session => { + session[kGracefullyClosing] = true; + + if (session[kCurrentStreamsCount] === 0) { + session.close(); + } +}; + +class Agent extends EventEmitter { + constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { + super(); + + // A session is considered busy when its current streams count + // is equal to or greater than the `maxConcurrentStreams` value. + + // A session is considered free when its current streams count + // is less than the `maxConcurrentStreams` value. + + // SESSIONS[NORMALIZED_OPTIONS] = []; + this.sessions = {}; + + // The queue for creating new sessions. It looks like this: + // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION + // + // The entry function has `listeners`, `completed` and `destroyed` properties. + // `listeners` is an array of objects containing `resolve` and `reject` functions. + // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. + // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. + this.queue = {}; + + // Each session will use this timeout value. + this.timeout = timeout; + + // Max sessions in total + this.maxSessions = maxSessions; + + // Max free sessions in total + // TODO: decreasing `maxFreeSessions` should close some sessions + this.maxFreeSessions = maxFreeSessions; + + this._freeSessionsCount = 0; + this._sessionsCount = 0; + + // We don't support push streams by default. + this.settings = { + enablePush: false + }; + + // Reusing TLS sessions increases performance. + this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); + } + + static normalizeOrigin(url, servername) { + if (typeof url === 'string') { + url = new URL(url); + } + + if (servername && url.hostname !== servername) { + url.hostname = servername; + } + + return url.origin; + } + + normalizeOptions(options) { + let normalized = ''; + + if (options) { + for (const key of nameKeys) { + if (options[key]) { + normalized += `:${options[key]}`; + } + } + } + + return normalized; + } + + _tryToCreateNewSession(normalizedOptions, normalizedOrigin) { + if (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) { + return; + } + + const item = this.queue[normalizedOptions][normalizedOrigin]; + + // The entry function can be run only once. + // BUG: The session may be never created when: + // - the first condition is false AND + // - this function is never called with the same arguments in the future. + if (this._sessionsCount < this.maxSessions && !item.completed) { + item.completed = true; + + item(); + } + } + + getSession(origin, options, listeners) { + return new Promise((resolve, reject) => { + if (Array.isArray(listeners)) { + listeners = [...listeners]; + + // Resolve the current promise ASAP, we're just moving the listeners. + // They will be executed at a different time. + resolve(); + } else { + listeners = [{resolve, reject}]; + } + + const normalizedOptions = this.normalizeOptions(options); + const normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername); + + if (normalizedOrigin === undefined) { + for (const {reject} of listeners) { + reject(new TypeError('The `origin` argument needs to be a string or an URL object')); + } + + return; + } + + if (normalizedOptions in this.sessions) { + const sessions = this.sessions[normalizedOptions]; + + let maxConcurrentStreams = -1; + let currentStreamsCount = -1; + let optimalSession; + + // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. + // Additionally, we are looking for session which has biggest current pending streams count. + for (const session of sessions) { + const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; + + if (sessionMaxConcurrentStreams < maxConcurrentStreams) { + break; + } + + if (session[kOriginSet].includes(normalizedOrigin)) { + const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; + + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || + session[kGracefullyClosing] || + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + session.destroyed + ) { + continue; + } + + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } + + // We're looking for the session which has biggest current pending stream count, + // in order to minimalize the amount of active sessions. + if (sessionCurrentStreamsCount > currentStreamsCount) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } + } + } + + if (optimalSession) { + /* istanbul ignore next: safety check */ + if (listeners.length !== 1) { + for (const {reject} of listeners) { + const error = new Error( + `Expected the length of listeners to be 1, got ${listeners.length}.\n` + + 'Please report this to https://github.com/szmarczak/http2-wrapper/' + ); + + reject(error); + } + + return; + } + + listeners[0].resolve(optimalSession); + return; + } + } + + if (normalizedOptions in this.queue) { + if (normalizedOrigin in this.queue[normalizedOptions]) { + // There's already an item in the queue, just attach ourselves to it. + this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + + // This shouldn't be executed here. + // See the comment inside _tryToCreateNewSession. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + return; + } + } else { + this.queue[normalizedOptions] = {}; + } + + // The entry must be removed from the queue IMMEDIATELY when: + // 1. the session connects successfully, + // 2. an error occurs. + const removeFromQueue = () => { + // Our entry can be replaced. We cannot remove the new one. + if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { + delete this.queue[normalizedOptions][normalizedOrigin]; + + if (Object.keys(this.queue[normalizedOptions]).length === 0) { + delete this.queue[normalizedOptions]; + } + } + }; + + // The main logic is here + const entry = () => { + const name = `${normalizedOrigin}:${normalizedOptions}`; + let receivedSettings = false; + + try { + const session = http2.connect(origin, { + createConnection: this.createConnection, + settings: this.settings, + session: this.tlsSessionCache.get(name), + ...options + }); + session[kCurrentStreamsCount] = 0; + session[kGracefullyClosing] = false; + + const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + let wasFree = true; + + session.socket.once('session', tlsSession => { + this.tlsSessionCache.set(name, tlsSession); + }); + + session.once('error', error => { + // Listeners are empty when the session successfully connected. + for (const {reject} of listeners) { + reject(error); + } + + // The connection got broken, purge the cache. + this.tlsSessionCache.delete(name); + }); + + session.setTimeout(this.timeout, () => { + // Terminates all streams owned by this session. + // TODO: Maybe the streams should have a "Session timed out" error? + session.destroy(); + }); + + session.once('close', () => { + if (receivedSettings) { + // 1. If it wasn't free then no need to decrease because + // it has been decreased already in session.request(). + // 2. `stream.once('close')` won't increment the count + // because the session is already closed. + if (wasFree) { + this._freeSessionsCount--; + } + + this._sessionsCount--; + + // This cannot be moved to the stream logic, + // because there may be a session that hadn't made a single request. + const where = this.sessions[normalizedOptions]; + where.splice(where.indexOf(session), 1); + + if (where.length === 0) { + delete this.sessions[normalizedOptions]; + } + } else { + // Broken connection + const error = new Error('Session closed without receiving a SETTINGS frame'); + error.code = 'HTTP2WRAPPER_NOSETTINGS'; + + for (const {reject} of listeners) { + reject(error); + } + + removeFromQueue(); + } + + // There may be another session awaiting. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + }); + + // Iterates over the queue and processes listeners. + const processListeners = () => { + if (!(normalizedOptions in this.queue) || !isFree()) { + return; + } + + for (const origin of session[kOriginSet]) { + if (origin in this.queue[normalizedOptions]) { + const {listeners} = this.queue[normalizedOptions][origin]; + + // Prevents session overloading. + while (listeners.length !== 0 && isFree()) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners.shift().resolve(session); + } + + const where = this.queue[normalizedOptions]; + if (where[origin].listeners.length === 0) { + delete where[origin]; + + if (Object.keys(where).length === 0) { + delete this.queue[normalizedOptions]; + break; + } + } + + // We're no longer free, no point in continuing. + if (!isFree()) { + break; + } + } + } + }; + + // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. + session.on('origin', () => { + session[kOriginSet] = session.originSet; + + if (!isFree()) { + // The session is full. + return; + } + + processListeners(); + + // Close covered sessions (if possible). + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + + session.once('remoteSettings', () => { + // Fix Node.js bug preventing the process from exiting + session.ref(); + session.unref(); + + this._sessionsCount++; + + // The Agent could have been destroyed already. + if (entry.destroyed) { + const error = new Error('Agent has been destroyed'); + + for (const listener of listeners) { + listener.reject(error); + } + + session.destroy(); + return; + } + + session[kOriginSet] = session.originSet; + + { + const where = this.sessions; + + if (normalizedOptions in where) { + const sessions = where[normalizedOptions]; + sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); + } else { + where[normalizedOptions] = [session]; + } + } + + this._freeSessionsCount += 1; + receivedSettings = true; + + this.emit('session', session); + + processListeners(); + removeFromQueue(); + + // TODO: Close last recently used (or least used?) session + if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { + session.close(); + } + + // Check if we haven't managed to execute all listeners. + if (listeners.length !== 0) { + // Request for a new session with predefined listeners. + this.getSession(normalizedOrigin, options, listeners); + listeners.length = 0; + } + + // `session.remoteSettings.maxConcurrentStreams` might get increased + session.on('remoteSettings', () => { + processListeners(); + + // In case the Origin Set changes + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + }); + + // Shim `session.request()` in order to catch all streams + session[kRequest] = session.request; + session.request = (headers, streamOptions) => { + if (session[kGracefullyClosing]) { + throw new Error('The session is gracefully closing. No new streams are allowed.'); + } + + const stream = session[kRequest](headers, streamOptions); + + // The process won't exit until the session is closed or all requests are gone. + session.ref(); + + ++session[kCurrentStreamsCount]; + + if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { + this._freeSessionsCount--; + } + + stream.once('close', () => { + wasFree = isFree(); + + --session[kCurrentStreamsCount]; + + if (!session.destroyed && !session.closed) { + closeSessionIfCovered(this.sessions[normalizedOptions], session); + + if (isFree() && !session.closed) { + if (!wasFree) { + this._freeSessionsCount++; + + wasFree = true; + } + + const isEmpty = session[kCurrentStreamsCount] === 0; + + if (isEmpty) { + session.unref(); + } + + if ( + isEmpty && + ( + this._freeSessionsCount > this.maxFreeSessions || + session[kGracefullyClosing] + ) + ) { + session.close(); + } else { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); + } + } + } + }); + + return stream; + }; + } catch (error) { + for (const listener of listeners) { + listener.reject(error); + } + + removeFromQueue(); + } + }; + + entry.listeners = listeners; + entry.completed = false; + entry.destroyed = false; + + this.queue[normalizedOptions][normalizedOrigin] = entry; + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + }); + } + + request(origin, options, headers, streamOptions) { + return new Promise((resolve, reject) => { + this.getSession(origin, options, [{ + reject, + resolve: session => { + try { + resolve(session.request(headers, streamOptions)); + } catch (error) { + reject(error); + } + } + }]); + }); + } + + createConnection(origin, options) { + return Agent.connect(origin, options); + } + + static connect(origin, options) { + options.ALPNProtocols = ['h2']; + + const port = origin.port || 443; + const host = origin.hostname || origin.host; + + if (typeof options.servername === 'undefined') { + options.servername = host; + } + + return tls.connect(port, host, options); + } + + closeFreeSessions() { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + if (session[kCurrentStreamsCount] === 0) { + session.close(); + } + } + } + } + + destroy(reason) { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + session.destroy(reason); + } + } + + for (const entriesOfAuthority of Object.values(this.queue)) { + for (const entry of Object.values(entriesOfAuthority)) { + entry.destroyed = true; + } + } + + // New requests should NOT attach to destroyed sessions + this.queue = {}; + } + + get freeSessions() { + return getSessions({agent: this, isFree: true}); + } + + get busySessions() { + return getSessions({agent: this, isFree: false}); + } +} + +Agent.kCurrentStreamsCount = kCurrentStreamsCount; +Agent.kGracefullyClosing = kGracefullyClosing; + +module.exports = { + Agent, + globalAgent: new Agent() +}; + + +/***/ }), + +/***/ 9213: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const http = __nccwpck_require__(8611); +const https = __nccwpck_require__(5692); +const resolveALPN = __nccwpck_require__(8824); +const QuickLRU = __nccwpck_require__(5475); +const Http2ClientRequest = __nccwpck_require__(7605); +const calculateServerName = __nccwpck_require__(2850); +const urlToOptions = __nccwpck_require__(4734); + +const cache = new QuickLRU({maxSize: 100}); +const queue = new Map(); + +const installSocket = (agent, socket, options) => { + socket._httpMessage = {shouldKeepAlive: true}; + + const onFree = () => { + agent.emit('free', socket, options); + }; + + socket.on('free', onFree); + + const onClose = () => { + agent.removeSocket(socket, options); + }; + + socket.on('close', onClose); + + const onRemove = () => { + agent.removeSocket(socket, options); + socket.off('close', onClose); + socket.off('free', onFree); + socket.off('agentRemove', onRemove); + }; + + socket.on('agentRemove', onRemove); + + agent.emit('free', socket, options); +}; + +const resolveProtocol = async options => { + const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; + + if (!cache.has(name)) { + if (queue.has(name)) { + const result = await queue.get(name); + return result.alpnProtocol; + } + + const {path, agent} = options; + options.path = options.socketPath; + + const resultPromise = resolveALPN(options); + queue.set(name, resultPromise); + + try { + const {socket, alpnProtocol} = await resultPromise; + cache.set(name, alpnProtocol); + + options.path = path; + + if (alpnProtocol === 'h2') { + // https://github.com/nodejs/node/issues/33343 + socket.destroy(); + } else { + const {globalAgent} = https; + const defaultCreateConnection = https.Agent.prototype.createConnection; + + if (agent) { + if (agent.createConnection === defaultCreateConnection) { + installSocket(agent, socket, options); + } else { + socket.destroy(); + } + } else if (globalAgent.createConnection === defaultCreateConnection) { + installSocket(globalAgent, socket, options); + } else { + socket.destroy(); + } + } + + queue.delete(name); + + return alpnProtocol; + } catch (error) { + queue.delete(name); + + throw error; + } + } + + return cache.get(name); +}; + +module.exports = async (input, options, callback) => { + if (typeof input === 'string' || input instanceof URL) { + input = urlToOptions(new URL(input)); + } + + if (typeof options === 'function') { + callback = options; + options = undefined; + } + + options = { + ALPNProtocols: ['h2', 'http/1.1'], + ...input, + ...options, + resolveSocket: true + }; + + if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { + throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + } + + options.protocol = options.protocol || 'https:'; + const isHttps = options.protocol === 'https:'; + + options.host = options.hostname || options.host || 'localhost'; + options.session = options.tlsSession; + options.servername = options.servername || calculateServerName(options); + options.port = options.port || (isHttps ? 443 : 80); + options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; + + const agents = options.agent; + + if (agents) { + if (agents.addRequest) { + throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); + } + + options.agent = agents[isHttps ? 'https' : 'http']; + } + + if (isHttps) { + const protocol = await resolveProtocol(options); + + if (protocol === 'h2') { + if (agents) { + options.agent = agents.http2; + } + + return new Http2ClientRequest(options, callback); + } + } + + return http.request(options, callback); +}; + +module.exports.protocolCache = cache; + + +/***/ }), + +/***/ 7605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const http2 = __nccwpck_require__(5675); +const {Writable} = __nccwpck_require__(2203); +const {Agent, globalAgent} = __nccwpck_require__(685); +const IncomingMessage = __nccwpck_require__(2156); +const urlToOptions = __nccwpck_require__(4734); +const proxyEvents = __nccwpck_require__(118); +const isRequestPseudoHeader = __nccwpck_require__(6365); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_PROTOCOL, + ERR_HTTP_HEADERS_SENT, + ERR_INVALID_HTTP_TOKEN, + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_INVALID_CHAR +} = __nccwpck_require__(9731); + +const { + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_METHOD_CONNECT +} = http2.constants; + +const kHeaders = Symbol('headers'); +const kOrigin = Symbol('origin'); +const kSession = Symbol('session'); +const kOptions = Symbol('options'); +const kFlushedHeaders = Symbol('flushedHeaders'); +const kJobs = Symbol('jobs'); + +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; +const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; + +class ClientRequest extends Writable { + constructor(input, options, callback) { + super({ + autoDestroy: false + }); + + const hasInput = typeof input === 'string' || input instanceof URL; + if (hasInput) { + input = urlToOptions(input instanceof URL ? input : new URL(input)); + } + + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = hasInput ? input : {...input}; + } else { + // (input, options, callback) + options = {...input, ...options}; + } + + if (options.h2session) { + this[kSession] = options.h2session; + } else if (options.agent === false) { + this.agent = new Agent({maxFreeSessions: 0}); + } else if (typeof options.agent === 'undefined' || options.agent === null) { + if (typeof options.createConnection === 'function') { + // This is a workaround - we don't have to create the session on our own. + this.agent = new Agent({maxFreeSessions: 0}); + this.agent.createConnection = options.createConnection; + } else { + this.agent = globalAgent; + } + } else if (typeof options.agent.request === 'function') { + this.agent = options.agent; + } else { + throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); + } + + if (options.protocol && options.protocol !== 'https:') { + throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); + } + + const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + const host = options.hostname || options.host || 'localhost'; + + // Don't enforce the origin via options. It may be changed in an Agent. + delete options.hostname; + delete options.host; + delete options.port; + + const {timeout} = options; + options.timeout = undefined; + + this[kHeaders] = Object.create(null); + this[kJobs] = []; + + this.socket = null; + this.connection = null; + + this.method = options.method || 'GET'; + this.path = options.path; + + this.res = null; + this.aborted = false; + this.reusedSocket = false; + + if (options.headers) { + for (const [header, value] of Object.entries(options.headers)) { + this.setHeader(header, value); + } + } + + if (options.auth && !('authorization' in this[kHeaders])) { + this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); + } + + options.session = options.tlsSession; + options.path = options.socketPath; + + this[kOptions] = options; + + // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. + if (port === 443) { + this[kOrigin] = `https://${host}`; + + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = host; + } + } else { + this[kOrigin] = `https://${host}:${port}`; + + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = `${host}:${port}`; + } + } + + if (timeout) { + this.setTimeout(timeout); + } + + if (callback) { + this.once('response', callback); + } + + this[kFlushedHeaders] = false; + } + + get method() { + return this[kHeaders][HTTP2_HEADER_METHOD]; + } + + set method(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); + } + } + + get path() { + return this[kHeaders][HTTP2_HEADER_PATH]; + } + + set path(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_PATH] = value; + } + } + + get _mustNotHaveABody() { + return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; + } + + _write(chunk, encoding, callback) { + // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 + if (this._mustNotHaveABody) { + callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); + /* istanbul ignore next: Node.js 12 throws directly */ + return; + } + + this.flushHeaders(); + + const callWrite = () => this._request.write(chunk, encoding, callback); + if (this._request) { + callWrite(); + } else { + this[kJobs].push(callWrite); + } + } + + _final(callback) { + if (this.destroyed) { + return; + } + + this.flushHeaders(); + + const callEnd = () => { + // For GET, HEAD and DELETE + if (this._mustNotHaveABody) { + callback(); + return; + } + + this._request.end(callback); + }; + + if (this._request) { + callEnd(); + } else { + this[kJobs].push(callEnd); + } + } + + abort() { + if (this.res && this.res.complete) { + return; + } + + if (!this.aborted) { + process.nextTick(() => this.emit('abort')); + } + + this.aborted = true; + + this.destroy(); + } + + _destroy(error, callback) { + if (this.res) { + this.res._dump(); + } + + if (this._request) { + this._request.destroy(); + } + + callback(error); + } + + async flushHeaders() { + if (this[kFlushedHeaders] || this.destroyed) { + return; + } + + this[kFlushedHeaders] = true; + + const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; + + // The real magic is here + const onStream = stream => { + this._request = stream; + + if (this.destroyed) { + stream.destroy(); + return; + } + + // Forwards `timeout`, `continue`, `close` and `error` events to this instance. + if (!isConnectMethod) { + proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); + } + + // Wait for the `finish` event. We don't want to emit the `response` event + // before `request.end()` is called. + const waitForEnd = fn => { + return (...args) => { + if (!this.writable && !this.destroyed) { + fn(...args); + } else { + this.once('finish', () => { + fn(...args); + }); + } + }; + }; + + // This event tells we are ready to listen for the data. + stream.once('response', waitForEnd((headers, flags, rawHeaders) => { + // If we were to emit raw request stream, it would be as fast as the native approach. + // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). + const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); + this.res = response; + + response.req = this; + response.statusCode = headers[HTTP2_HEADER_STATUS]; + response.headers = headers; + response.rawHeaders = rawHeaders; + + response.once('end', () => { + if (this.aborted) { + response.aborted = true; + response.emit('aborted'); + } else { + response.complete = true; + + // Has no effect, just be consistent with the Node.js behavior + response.socket = null; + response.connection = null; + } + }); + + if (isConnectMethod) { + response.upgrade = true; + + // The HTTP1 API says the socket is detached here, + // but we can't do that so we pass the original HTTP2 request. + if (this.emit('connect', response, stream, Buffer.alloc(0))) { + this.emit('close'); + } else { + // No listeners attached, destroy the original request. + stream.destroy(); + } + } else { + // Forwards data + stream.on('data', chunk => { + if (!response._dumped && !response.push(chunk)) { + stream.pause(); + } + }); + + stream.once('end', () => { + response.push(null); + }); + + if (!this.emit('response', response)) { + // No listeners attached, dump the response. + response._dump(); + } + } + })); + + // Emits `information` event + stream.once('headers', waitForEnd( + headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) + )); + + stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { + const {res} = this; + + // Assigns trailers to the response object. + res.trailers = trailers; + res.rawTrailers = rawTrailers; + })); + + const {socket} = stream.session; + this.socket = socket; + this.connection = socket; + + for (const job of this[kJobs]) { + job(); + } + + this.emit('socket', this.socket); + }; + + // Makes a HTTP2 request + if (this[kSession]) { + try { + onStream(this[kSession].request(this[kHeaders])); + } catch (error) { + this.emit('error', error); + } + } else { + this.reusedSocket = true; + + try { + onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders])); + } catch (error) { + this.emit('error', error); + } + } + } + + getHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } + + return this[kHeaders][name.toLowerCase()]; + } + + get headersSent() { + return this[kFlushedHeaders]; + } + + removeHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } + + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('remove'); + } + + delete this[kHeaders][name.toLowerCase()]; + } + + setHeader(name, value) { + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('set'); + } + + if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); + } + + if (typeof value === 'undefined') { + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); + } + + if (isInvalidHeaderValue.test(value)) { + throw new ERR_INVALID_CHAR('header content', name); + } + + this[kHeaders][name.toLowerCase()] = value; + } + + setNoDelay() { + // HTTP2 sockets cannot be malformed, do nothing. + } + + setSocketKeepAlive() { + // HTTP2 sockets cannot be malformed, do nothing. + } + + setTimeout(ms, callback) { + const applyTimeout = () => this._request.setTimeout(ms, callback); + + if (this._request) { + applyTimeout(); + } else { + this[kJobs].push(applyTimeout); + } + + return this; + } + + get maxHeadersCount() { + if (!this.destroyed && this._request) { + return this._request.session.localSettings.maxHeaderListSize; + } + + return undefined; + } + + set maxHeadersCount(_value) { + // Updating HTTP2 settings would affect all requests, do nothing. + } +} + +module.exports = ClientRequest; + + +/***/ }), + +/***/ 2156: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const {Readable} = __nccwpck_require__(2203); + +class IncomingMessage extends Readable { + constructor(socket, highWaterMark) { + super({ + highWaterMark, + autoDestroy: false + }); + + this.statusCode = null; + this.statusMessage = ''; + this.httpVersion = '2.0'; + this.httpVersionMajor = 2; + this.httpVersionMinor = 0; + this.headers = {}; + this.trailers = {}; + this.req = null; + + this.aborted = false; + this.complete = false; + this.upgrade = null; + + this.rawHeaders = []; + this.rawTrailers = []; + + this.socket = socket; + this.connection = socket; + + this._dumped = false; + } + + _destroy(error) { + this.req._request.destroy(error); + } + + setTimeout(ms, callback) { + this.req.setTimeout(ms, callback); + return this; + } + + _dump() { + if (!this._dumped) { + this._dumped = true; + + this.removeAllListeners('data'); + this.resume(); + } + } + + _read() { + if (this.req) { + this.req._request.resume(); + } + } +} + +module.exports = IncomingMessage; + + +/***/ }), + +/***/ 4956: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const http2 = __nccwpck_require__(5675); +const agent = __nccwpck_require__(685); +const ClientRequest = __nccwpck_require__(7605); +const IncomingMessage = __nccwpck_require__(2156); +const auto = __nccwpck_require__(9213); + +const request = (url, options, callback) => { + return new ClientRequest(url, options, callback); +}; + +const get = (url, options, callback) => { + // eslint-disable-next-line unicorn/prevent-abbreviations + const req = new ClientRequest(url, options, callback); + req.end(); + + return req; +}; + +module.exports = { + ...http2, + ClientRequest, + IncomingMessage, + ...agent, + request, + get, + auto +}; + + +/***/ }), + +/***/ 2850: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const net = __nccwpck_require__(9278); +/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */ + +module.exports = options => { + let servername = options.host; + const hostHeader = options.headers && options.headers.host; + + if (hostHeader) { + if (hostHeader.startsWith('[')) { + const index = hostHeader.indexOf(']'); + if (index === -1) { + servername = hostHeader; + } else { + servername = hostHeader.slice(1, -1); + } + } else { + servername = hostHeader.split(':', 1)[0]; + } + } + + if (net.isIP(servername)) { + return ''; + } + + return servername; +}; + + +/***/ }), + +/***/ 9731: +/***/ ((module) => { + +"use strict"; + +/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ + +const makeError = (Base, key, getMessage) => { + module.exports[key] = class NodeError extends Base { + constructor(...args) { + super(typeof getMessage === 'string' ? getMessage : getMessage(args)); + this.name = `${super.name} [${key}]`; + this.code = key; + } + }; +}; + +makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { + const type = args[0].includes('.') ? 'property' : 'argument'; + + let valid = args[1]; + const isManyTypes = Array.isArray(valid); + + if (isManyTypes) { + valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; + } + + return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; +}); + +makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => { + return `Protocol "${args[0]}" not supported. Expected "${args[1]}"`; +}); + +makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => { + return `Cannot ${args[0]} headers after they are sent to the client`; +}); + +makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => { + return `${args[0]} must be a valid HTTP token [${args[1]}]`; +}); + +makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => { + return `Invalid value "${args[0]} for header "${args[1]}"`; +}); + +makeError(TypeError, 'ERR_INVALID_CHAR', args => { + return `Invalid character in ${args[0]} [${args[1]}]`; +}); + + +/***/ }), + +/***/ 6365: +/***/ ((module) => { + +"use strict"; + + +module.exports = header => { + switch (header) { + case ':method': + case ':scheme': + case ':authority': + case ':path': + return true; + default: + return false; + } +}; + + +/***/ }), + +/***/ 118: +/***/ ((module) => { + +"use strict"; + + +module.exports = (from, to, events) => { + for (const event of events) { + from.on(event, (...args) => to.emit(event, ...args)); + } +}; + + +/***/ }), + +/***/ 4734: +/***/ ((module) => { + +"use strict"; + +/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */ + +module.exports = url => { + const options = { + protocol: url.protocol, + hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; + + if (typeof url.port === 'string' && url.port.length !== 0) { + options.port = Number(url.port); + } + + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } + + return options; +}; + + /***/ }), /***/ 5540: @@ -7836,6 +24152,7 @@ module.exports = function isGlob(str, options) { /***/ 3102: /***/ ((module) => { +"use strict"; /*! * is-number * @@ -7856,11 +24173,367 @@ module.exports = function(num) { }; +/***/ }), + +/***/ 5563: +/***/ ((__unused_webpack_module, exports) => { + +//TODO: handle reviver/dehydrate function like normal +//and handle indentation, like normal. +//if anyone needs this... please send pull request. + +exports.stringify = function stringify (o) { + if('undefined' == typeof o) return o + + if(o && Buffer.isBuffer(o)) + return JSON.stringify(':base64:' + o.toString('base64')) + + if(o && o.toJSON) + o = o.toJSON() + + if(o && 'object' === typeof o) { + var s = '' + var array = Array.isArray(o) + s = array ? '[' : '{' + var first = true + + for(var k in o) { + var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) + if(Object.hasOwnProperty.call(o, k) && !ignore) { + if(!first) + s += ',' + first = false + if (array) { + if(o[k] == undefined) + s += 'null' + else + s += stringify(o[k]) + } else if (o[k] !== void(0)) { + s += stringify(k) + ':' + stringify(o[k]) + } + } + } + + s += array ? ']' : '}' + + return s + } else if ('string' === typeof o) { + return JSON.stringify(/^:/.test(o) ? ':' + o : o) + } else if ('undefined' === typeof o) { + return 'null'; + } else + return JSON.stringify(o) +} + +exports.parse = function (s) { + return JSON.parse(s, function (key, value) { + if('string' === typeof value) { + if(/^:base64:/.test(value)) + return Buffer.from(value.substring(8), 'base64') + else + return /^:/.test(value) ? value.substring(1) : value + } + return value + }) +} + + +/***/ }), + +/***/ 6018: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const EventEmitter = __nccwpck_require__(4434); +const JSONB = __nccwpck_require__(5563); + +const loadStore = options => { + const adapters = { + redis: '@keyv/redis', + rediss: '@keyv/redis', + mongodb: '@keyv/mongo', + mongo: '@keyv/mongo', + sqlite: '@keyv/sqlite', + postgresql: '@keyv/postgres', + postgres: '@keyv/postgres', + mysql: '@keyv/mysql', + etcd: '@keyv/etcd', + offline: '@keyv/offline', + tiered: '@keyv/tiered', + }; + if (options.adapter || options.uri) { + const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; + return new (require(adapters[adapter]))(options); + } + + return new Map(); +}; + +const iterableAdapters = [ + 'sqlite', + 'postgres', + 'mysql', + 'mongo', + 'redis', + 'tiered', +]; + +class Keyv extends EventEmitter { + constructor(uri, {emitErrors = true, ...options} = {}) { + super(); + this.opts = { + namespace: 'keyv', + serialize: JSONB.stringify, + deserialize: JSONB.parse, + ...((typeof uri === 'string') ? {uri} : uri), + ...options, + }; + + if (!this.opts.store) { + const adapterOptions = {...this.opts}; + this.opts.store = loadStore(adapterOptions); + } + + if (this.opts.compression) { + const compression = this.opts.compression; + this.opts.serialize = compression.serialize.bind(compression); + this.opts.deserialize = compression.deserialize.bind(compression); + } + + if (typeof this.opts.store.on === 'function' && emitErrors) { + this.opts.store.on('error', error => this.emit('error', error)); + } + + this.opts.store.namespace = this.opts.namespace; + + const generateIterator = iterator => async function * () { + for await (const [key, raw] of typeof iterator === 'function' + ? iterator(this.opts.store.namespace) + : iterator) { + const data = await this.opts.deserialize(raw); + if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { + continue; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + this.delete(key); + continue; + } + + yield [this._getKeyUnprefix(key), data.value]; + } + }; + + // Attach iterators + if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { + this.iterator = generateIterator(this.opts.store); + } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts + && this._checkIterableAdaptar()) { + this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); + } + } + + _checkIterableAdaptar() { + return iterableAdapters.includes(this.opts.store.opts.dialect) + || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; + } + + _getKeyPrefix(key) { + return `${this.opts.namespace}:${key}`; + } + + _getKeyPrefixArray(keys) { + return keys.map(key => `${this.opts.namespace}:${key}`); + } + + _getKeyUnprefix(key) { + return key + .split(':') + .splice(1) + .join(':'); + } + + get(key, options) { + const {store} = this.opts; + const isArray = Array.isArray(key); + const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); + if (isArray && store.getMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(Promise.resolve() + .then(() => store.get(key)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } + + return (options && options.raw) ? data : data.value; + }), + ); + } + + return Promise.allSettled(promises) + .then(values => { + const data = []; + for (const value of values) { + data.push(value.value); + } + + return data; + }); + } + + return Promise.resolve() + .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } + + if (isArray) { + const result = []; + + for (let row of data) { + if ((typeof row === 'string')) { + row = this.opts.deserialize(row); + } + + if (row === undefined || row === null) { + result.push(undefined); + continue; + } + + if (typeof row.expires === 'number' && Date.now() > row.expires) { + this.delete(key).then(() => undefined); + result.push(undefined); + } else { + result.push((options && options.raw) ? row : row.value); + } + } + + return result; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } + + return (options && options.raw) ? data : data.value; + }); + } + + set(key, value, ttl) { + const keyPrefixed = this._getKeyPrefix(key); + if (typeof ttl === 'undefined') { + ttl = this.opts.ttl; + } + + if (ttl === 0) { + ttl = undefined; + } + + const {store} = this.opts; + + return Promise.resolve() + .then(() => { + const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; + if (typeof value === 'symbol') { + this.emit('error', 'symbol cannot be serialized'); + } + + value = {value, expires}; + return this.opts.serialize(value); + }) + .then(value => store.set(keyPrefixed, value, ttl)) + .then(() => true); + } + + delete(key) { + const {store} = this.opts; + if (Array.isArray(key)) { + const keyPrefixed = this._getKeyPrefixArray(key); + if (store.deleteMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(store.delete(key)); + } + + return Promise.allSettled(promises) + .then(values => values.every(x => x.value === true)); + } + + return Promise.resolve() + .then(() => store.deleteMany(keyPrefixed)); + } + + const keyPrefixed = this._getKeyPrefix(key); + return Promise.resolve() + .then(() => store.delete(keyPrefixed)); + } + + clear() { + const {store} = this.opts; + return Promise.resolve() + .then(() => store.clear()); + } + + has(key) { + const keyPrefixed = this._getKeyPrefix(key); + const {store} = this.opts; + return Promise.resolve() + .then(async () => { + if (typeof store.has === 'function') { + return store.has(keyPrefixed); + } + + const value = await store.get(keyPrefixed); + return value !== undefined; + }); + } + + disconnect() { + const {store} = this.opts; + if (typeof store.disconnect === 'function') { + return store.disconnect(); + } + } +} + +module.exports = Keyv; + + +/***/ }), + +/***/ 1364: +/***/ ((module) => { + +"use strict"; + +module.exports = object => { + const result = {}; + + for (const [key, value] of Object.entries(object)) { + result[key.toLowerCase()] = value; + } + + return result; +}; + + /***/ }), /***/ 754: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /* * merge2 @@ -8012,6 +24685,7 @@ function pauseStreams (streams, options) { /***/ 8785: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const util = __nccwpck_require__(9023); @@ -8493,6 +25167,7 @@ module.exports = micromatch; /***/ 6377: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; module.exports = __nccwpck_require__(9639); @@ -8503,14 +25178,13 @@ module.exports = __nccwpck_require__(9639); /***/ 9560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const path = __nccwpck_require__(6928); const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; -const DEFAULT_MAX_EXTGLOB_RECURSION = 0; - /** * Posix glob regex */ @@ -8574,7 +25248,6 @@ const WINDOWS_CHARS = { */ const POSIX_REGEX_SOURCE = { - __proto__: null, alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', @@ -8592,7 +25265,6 @@ const POSIX_REGEX_SOURCE = { }; module.exports = { - DEFAULT_MAX_EXTGLOB_RECURSION, MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, @@ -8606,7 +25278,6 @@ module.exports = { // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { - __proto__: null, '***': '*', '**/**': '**', '**/**/**': '**' @@ -8694,6 +25365,7 @@ module.exports = { /***/ 7430: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const constants = __nccwpck_require__(9560); @@ -8741,277 +25413,6 @@ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; -const splitTopLevel = input => { - const parts = []; - let bracket = 0; - let paren = 0; - let quote = 0; - let value = ''; - let escaped = false; - - for (const ch of input) { - if (escaped === true) { - value += ch; - escaped = false; - continue; - } - - if (ch === '\\') { - value += ch; - escaped = true; - continue; - } - - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - value += ch; - continue; - } - - if (quote === 0) { - if (ch === '[') { - bracket++; - } else if (ch === ']' && bracket > 0) { - bracket--; - } else if (bracket === 0) { - if (ch === '(') { - paren++; - } else if (ch === ')' && paren > 0) { - paren--; - } else if (ch === '|' && paren === 0) { - parts.push(value); - value = ''; - continue; - } - } - } - - value += ch; - } - - parts.push(value); - return parts; -}; - -const isPlainBranch = branch => { - let escaped = false; - - for (const ch of branch) { - if (escaped === true) { - escaped = false; - continue; - } - - if (ch === '\\') { - escaped = true; - continue; - } - - if (/[?*+@!()[\]{}]/.test(ch)) { - return false; - } - } - - return true; -}; - -const normalizeSimpleBranch = branch => { - let value = branch.trim(); - let changed = true; - - while (changed === true) { - changed = false; - - if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { - value = value.slice(2, -1); - changed = true; - } - } - - if (!isPlainBranch(value)) { - return; - } - - return value.replace(/\\(.)/g, '$1'); -}; - -const hasRepeatedCharPrefixOverlap = branches => { - const values = branches.map(normalizeSimpleBranch).filter(Boolean); - - for (let i = 0; i < values.length; i++) { - for (let j = i + 1; j < values.length; j++) { - const a = values[i]; - const b = values[j]; - const char = a[0]; - - if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { - continue; - } - - if (a === b || a.startsWith(b) || b.startsWith(a)) { - return true; - } - } - } - - return false; -}; - -const parseRepeatedExtglob = (pattern, requireEnd = true) => { - if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') { - return; - } - - let bracket = 0; - let paren = 0; - let quote = 0; - let escaped = false; - - for (let i = 1; i < pattern.length; i++) { - const ch = pattern[i]; - - if (escaped === true) { - escaped = false; - continue; - } - - if (ch === '\\') { - escaped = true; - continue; - } - - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - continue; - } - - if (quote === 1) { - continue; - } - - if (ch === '[') { - bracket++; - continue; - } - - if (ch === ']' && bracket > 0) { - bracket--; - continue; - } - - if (bracket > 0) { - continue; - } - - if (ch === '(') { - paren++; - continue; - } - - if (ch === ')') { - paren--; - - if (paren === 0) { - if (requireEnd === true && i !== pattern.length - 1) { - return; - } - - return { - type: pattern[0], - body: pattern.slice(2, i), - end: i - }; - } - } - } -}; - -const getStarExtglobSequenceOutput = pattern => { - let index = 0; - const chars = []; - - while (index < pattern.length) { - const match = parseRepeatedExtglob(pattern.slice(index), false); - - if (!match || match.type !== '*') { - return; - } - - const branches = splitTopLevel(match.body).map(branch => branch.trim()); - if (branches.length !== 1) { - return; - } - - const branch = normalizeSimpleBranch(branches[0]); - if (!branch || branch.length !== 1) { - return; - } - - chars.push(branch); - index += match.end + 1; - } - - if (chars.length < 1) { - return; - } - - const source = chars.length === 1 - ? utils.escapeRegex(chars[0]) - : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`; - - return `${source}*`; -}; - -const repeatedExtglobRecursion = pattern => { - let depth = 0; - let value = pattern.trim(); - let match = parseRepeatedExtglob(value); - - while (match) { - depth++; - value = match.body.trim(); - match = parseRepeatedExtglob(value); - } - - return depth; -}; - -const analyzeRepeatedExtglob = (body, options) => { - if (options.maxExtglobRecursion === false) { - return { risky: false }; - } - - const max = - typeof options.maxExtglobRecursion === 'number' - ? options.maxExtglobRecursion - : constants.DEFAULT_MAX_EXTGLOB_RECURSION; - - const branches = splitTopLevel(body).map(branch => branch.trim()); - - if (branches.length > 1) { - if ( - branches.some(branch => branch === '') || - branches.some(branch => /^[*?]+$/.test(branch)) || - hasRepeatedCharPrefixOverlap(branches) - ) { - return { risky: true }; - } - } - - for (const branch of branches) { - const safeOutput = getStarExtglobSequenceOutput(branch); - if (safeOutput) { - return { risky: true, safeOutput }; - } - - if (repeatedExtglobRecursion(branch) > max) { - return { risky: true }; - } - } - - return { risky: false }; -}; - /** * Parse the given input string. * @param {String} input @@ -9193,8 +25594,6 @@ const parse = (input, options) => { token.prev = prev; token.parens = state.parens; token.output = state.output; - token.startIndex = state.index; - token.tokensIndex = tokens.length; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); @@ -9204,34 +25603,6 @@ const parse = (input, options) => { }; const extglobClose = token => { - const literal = input.slice(token.startIndex, state.index + 1); - const body = input.slice(token.startIndex + 2, state.index); - const analysis = analyzeRepeatedExtglob(body, opts); - - if ((token.type === 'plus' || token.type === 'star') && analysis.risky) { - const safeOutput = analysis.safeOutput - ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) - : undefined; - const open = tokens[token.tokensIndex]; - - open.type = 'text'; - open.value = literal; - open.output = safeOutput || utils.escapeRegex(literal); - - for (let i = token.tokensIndex + 1; i < tokens.length; i++) { - tokens[i].value = ''; - tokens[i].output = ''; - delete tokens[i].suffix; - } - - state.output = token.output + open.output; - state.backtrack = true; - - push({ type: 'paren', extglob: true, value, output: '' }); - decrement('parens'); - return; - } - let output = token.close + (opts.capture ? ')' : ''); let rest; @@ -10093,6 +26464,7 @@ module.exports = parse; /***/ 9639: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const path = __nccwpck_require__(6928); @@ -10442,6 +26814,7 @@ module.exports = picomatch; /***/ 6028: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const utils = __nccwpck_require__(8604); @@ -10840,6 +27213,7 @@ module.exports = scan; /***/ 8604: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; const path = __nccwpck_require__(6928); @@ -10906,11 +27280,444 @@ exports.wrapOutput = (input, state = {}, options = {}) => { }; +/***/ }), + +/***/ 9991: +/***/ ((module) => { + +"use strict"; + + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProps = [ + 'destroy', + 'setTimeout', + 'socket', + 'headers', + 'trailers', + 'rawHeaders', + 'statusCode', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'rawTrailers', + 'statusMessage' +]; + +module.exports = (fromStream, toStream) => { + const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); + + for (const prop of fromProps) { + // Don't overwrite existing properties + if (prop in toStream) { + continue; + } + + toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; + } +}; + + +/***/ }), + +/***/ 7827: +/***/ ((module) => { + +"use strict"; + + +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs +const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; +const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; + +const testParameter = (name, filters) => { + return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); +}; + +const normalizeDataURL = (urlString, {stripHash}) => { + const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); + + if (!match) { + throw new Error(`Invalid URL: ${urlString}`); + } + + let {type, data, hash} = match.groups; + const mediaType = type.split(';'); + hash = stripHash ? '' : hash; + + let isBase64 = false; + if (mediaType[mediaType.length - 1] === 'base64') { + mediaType.pop(); + isBase64 = true; + } + + // Lowercase MIME type + const mimeType = (mediaType.shift() || '').toLowerCase(); + const attributes = mediaType + .map(attribute => { + let [key, value = ''] = attribute.split('=').map(string => string.trim()); + + // Lowercase `charset` + if (key === 'charset') { + value = value.toLowerCase(); + + if (value === DATA_URL_DEFAULT_CHARSET) { + return ''; + } + } + + return `${key}${value ? `=${value}` : ''}`; + }) + .filter(Boolean); + + const normalizedMediaType = [ + ...attributes + ]; + + if (isBase64) { + normalizedMediaType.push('base64'); + } + + if (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { + normalizedMediaType.unshift(mimeType); + } + + return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; +}; + +const normalizeUrl = (urlString, options) => { + options = { + defaultProtocol: 'http:', + normalizeProtocol: true, + forceHttp: false, + forceHttps: false, + stripAuthentication: true, + stripHash: false, + stripTextFragment: true, + stripWWW: true, + removeQueryParameters: [/^utm_\w+/i], + removeTrailingSlash: true, + removeSingleSlash: true, + removeDirectoryIndex: false, + sortQueryParameters: true, + ...options + }; + + urlString = urlString.trim(); + + // Data URL + if (/^data:/i.test(urlString)) { + return normalizeDataURL(urlString, options); + } + + if (/^view-source:/i.test(urlString)) { + throw new Error('`view-source:` is not supported as it is a non-standard protocol'); + } + + const hasRelativeProtocol = urlString.startsWith('//'); + const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); + + // Prepend protocol + if (!isRelativeUrl) { + urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); + } + + const urlObj = new URL(urlString); + + if (options.forceHttp && options.forceHttps) { + throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); + } + + if (options.forceHttp && urlObj.protocol === 'https:') { + urlObj.protocol = 'http:'; + } + + if (options.forceHttps && urlObj.protocol === 'http:') { + urlObj.protocol = 'https:'; + } + + // Remove auth + if (options.stripAuthentication) { + urlObj.username = ''; + urlObj.password = ''; + } + + // Remove hash + if (options.stripHash) { + urlObj.hash = ''; + } else if (options.stripTextFragment) { + urlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, ''); + } + + // Remove duplicate slashes if not preceded by a protocol + if (urlObj.pathname) { + urlObj.pathname = urlObj.pathname.replace(/(? 0) { + let pathComponents = urlObj.pathname.split('/'); + const lastComponent = pathComponents[pathComponents.length - 1]; + + if (testParameter(lastComponent, options.removeDirectoryIndex)) { + pathComponents = pathComponents.slice(0, pathComponents.length - 1); + urlObj.pathname = pathComponents.slice(1).join('/') + '/'; + } + } + + if (urlObj.hostname) { + // Remove trailing dot + urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); + + // Remove `www.` + if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) { + // Each label should be max 63 at length (min: 1). + // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names + // Each TLD should be up to 63 characters long (min: 2). + // It is technically possible to have a single character TLD, but none currently exist. + urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); + } + } + + // Remove query unwanted parameters + if (Array.isArray(options.removeQueryParameters)) { + for (const key of [...urlObj.searchParams.keys()]) { + if (testParameter(key, options.removeQueryParameters)) { + urlObj.searchParams.delete(key); + } + } + } + + if (options.removeQueryParameters === true) { + urlObj.search = ''; + } + + // Sort query parameters + if (options.sortQueryParameters) { + urlObj.searchParams.sort(); + } + + if (options.removeTrailingSlash) { + urlObj.pathname = urlObj.pathname.replace(/\/$/, ''); + } + + const oldUrlString = urlString; + + // Take advantage of many of the Node `url` normalizations + urlString = urlObj.toString(); + + if (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') { + urlString = urlString.replace(/\/$/, ''); + } + + // Remove ending `/` unless removeSingleSlash is false + if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) { + urlString = urlString.replace(/\/$/, ''); + } + + // Restore relative protocol, if applicable + if (hasRelativeProtocol && !options.normalizeProtocol) { + urlString = urlString.replace(/^http:\/\//, '//'); + } + + // Remove http/https + if (options.stripProtocol) { + urlString = urlString.replace(/^(?:https?:)?\/\//, ''); + } + + return urlString; +}; + +module.exports = normalizeUrl; + + +/***/ }), + +/***/ 5560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(8264) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} + + +/***/ }), + +/***/ 4533: +/***/ ((module) => { + +"use strict"; + + +class CancelError extends Error { + constructor(reason) { + super(reason || 'Promise was canceled'); + this.name = 'CancelError'; + } + + get isCanceled() { + return true; + } +} + +class PCancelable { + static fn(userFn) { + return (...arguments_) => { + return new PCancelable((resolve, reject, onCancel) => { + arguments_.push(onCancel); + // eslint-disable-next-line promise/prefer-await-to-then + userFn(...arguments_).then(resolve, reject); + }); + }; + } + + constructor(executor) { + this._cancelHandlers = []; + this._isPending = true; + this._isCanceled = false; + this._rejectOnCancel = true; + + this._promise = new Promise((resolve, reject) => { + this._reject = reject; + + const onResolve = value => { + if (!this._isCanceled || !onCancel.shouldReject) { + this._isPending = false; + resolve(value); + } + }; + + const onReject = error => { + this._isPending = false; + reject(error); + }; + + const onCancel = handler => { + if (!this._isPending) { + throw new Error('The `onCancel` handler was attached after the promise settled.'); + } + + this._cancelHandlers.push(handler); + }; + + Object.defineProperties(onCancel, { + shouldReject: { + get: () => this._rejectOnCancel, + set: boolean => { + this._rejectOnCancel = boolean; + } + } + }); + + return executor(onResolve, onReject, onCancel); + }); + } + + then(onFulfilled, onRejected) { + // eslint-disable-next-line promise/prefer-await-to-then + return this._promise.then(onFulfilled, onRejected); + } + + catch(onRejected) { + return this._promise.catch(onRejected); + } + + finally(onFinally) { + return this._promise.finally(onFinally); + } + + cancel(reason) { + if (!this._isPending || this._isCanceled) { + return; + } + + this._isCanceled = true; + + if (this._cancelHandlers.length > 0) { + try { + for (const handler of this._cancelHandlers) { + handler(); + } + } catch (error) { + this._reject(error); + return; + } + } + + if (this._rejectOnCancel) { + this._reject(new CancelError(reason)); + } + } + + get isCanceled() { + return this._isCanceled; + } +} + +Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + +module.exports = PCancelable; +module.exports.CancelError = CancelError; + + /***/ }), /***/ 4006: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const pico = __nccwpck_require__(8016); @@ -10935,13 +27742,12 @@ module.exports = picomatch; /***/ 5595: /***/ ((module) => { +"use strict"; const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; -const DEFAULT_MAX_EXTGLOB_RECURSION = 0; - /** * Posix glob regex */ @@ -11008,7 +27814,6 @@ const WINDOWS_CHARS = { */ const POSIX_REGEX_SOURCE = { - __proto__: null, alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', @@ -11026,7 +27831,6 @@ const POSIX_REGEX_SOURCE = { }; module.exports = { - DEFAULT_MAX_EXTGLOB_RECURSION, MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, @@ -11040,7 +27844,6 @@ module.exports = { // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { - __proto__: null, '***': '*', '**/**': '**', '**/**/**': '**' @@ -11126,6 +27929,7 @@ module.exports = { /***/ 8265: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const constants = __nccwpck_require__(5595); @@ -11173,277 +27977,6 @@ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; -const splitTopLevel = input => { - const parts = []; - let bracket = 0; - let paren = 0; - let quote = 0; - let value = ''; - let escaped = false; - - for (const ch of input) { - if (escaped === true) { - value += ch; - escaped = false; - continue; - } - - if (ch === '\\') { - value += ch; - escaped = true; - continue; - } - - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - value += ch; - continue; - } - - if (quote === 0) { - if (ch === '[') { - bracket++; - } else if (ch === ']' && bracket > 0) { - bracket--; - } else if (bracket === 0) { - if (ch === '(') { - paren++; - } else if (ch === ')' && paren > 0) { - paren--; - } else if (ch === '|' && paren === 0) { - parts.push(value); - value = ''; - continue; - } - } - } - - value += ch; - } - - parts.push(value); - return parts; -}; - -const isPlainBranch = branch => { - let escaped = false; - - for (const ch of branch) { - if (escaped === true) { - escaped = false; - continue; - } - - if (ch === '\\') { - escaped = true; - continue; - } - - if (/[?*+@!()[\]{}]/.test(ch)) { - return false; - } - } - - return true; -}; - -const normalizeSimpleBranch = branch => { - let value = branch.trim(); - let changed = true; - - while (changed === true) { - changed = false; - - if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { - value = value.slice(2, -1); - changed = true; - } - } - - if (!isPlainBranch(value)) { - return; - } - - return value.replace(/\\(.)/g, '$1'); -}; - -const hasRepeatedCharPrefixOverlap = branches => { - const values = branches.map(normalizeSimpleBranch).filter(Boolean); - - for (let i = 0; i < values.length; i++) { - for (let j = i + 1; j < values.length; j++) { - const a = values[i]; - const b = values[j]; - const char = a[0]; - - if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { - continue; - } - - if (a === b || a.startsWith(b) || b.startsWith(a)) { - return true; - } - } - } - - return false; -}; - -const parseRepeatedExtglob = (pattern, requireEnd = true) => { - if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') { - return; - } - - let bracket = 0; - let paren = 0; - let quote = 0; - let escaped = false; - - for (let i = 1; i < pattern.length; i++) { - const ch = pattern[i]; - - if (escaped === true) { - escaped = false; - continue; - } - - if (ch === '\\') { - escaped = true; - continue; - } - - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - continue; - } - - if (quote === 1) { - continue; - } - - if (ch === '[') { - bracket++; - continue; - } - - if (ch === ']' && bracket > 0) { - bracket--; - continue; - } - - if (bracket > 0) { - continue; - } - - if (ch === '(') { - paren++; - continue; - } - - if (ch === ')') { - paren--; - - if (paren === 0) { - if (requireEnd === true && i !== pattern.length - 1) { - return; - } - - return { - type: pattern[0], - body: pattern.slice(2, i), - end: i - }; - } - } - } -}; - -const getStarExtglobSequenceOutput = pattern => { - let index = 0; - const chars = []; - - while (index < pattern.length) { - const match = parseRepeatedExtglob(pattern.slice(index), false); - - if (!match || match.type !== '*') { - return; - } - - const branches = splitTopLevel(match.body).map(branch => branch.trim()); - if (branches.length !== 1) { - return; - } - - const branch = normalizeSimpleBranch(branches[0]); - if (!branch || branch.length !== 1) { - return; - } - - chars.push(branch); - index += match.end + 1; - } - - if (chars.length < 1) { - return; - } - - const source = chars.length === 1 - ? utils.escapeRegex(chars[0]) - : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`; - - return `${source}*`; -}; - -const repeatedExtglobRecursion = pattern => { - let depth = 0; - let value = pattern.trim(); - let match = parseRepeatedExtglob(value); - - while (match) { - depth++; - value = match.body.trim(); - match = parseRepeatedExtglob(value); - } - - return depth; -}; - -const analyzeRepeatedExtglob = (body, options) => { - if (options.maxExtglobRecursion === false) { - return { risky: false }; - } - - const max = - typeof options.maxExtglobRecursion === 'number' - ? options.maxExtglobRecursion - : constants.DEFAULT_MAX_EXTGLOB_RECURSION; - - const branches = splitTopLevel(body).map(branch => branch.trim()); - - if (branches.length > 1) { - if ( - branches.some(branch => branch === '') || - branches.some(branch => /^[*?]+$/.test(branch)) || - hasRepeatedCharPrefixOverlap(branches) - ) { - return { risky: true }; - } - } - - for (const branch of branches) { - const safeOutput = getStarExtglobSequenceOutput(branch); - if (safeOutput) { - return { risky: true, safeOutput }; - } - - if (repeatedExtglobRecursion(branch) > max) { - return { risky: true }; - } - } - - return { risky: false }; -}; - /** * Parse the given input string. * @param {String} input @@ -11624,8 +28157,6 @@ const parse = (input, options) => { token.prev = prev; token.parens = state.parens; token.output = state.output; - token.startIndex = state.index; - token.tokensIndex = tokens.length; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); @@ -11635,34 +28166,6 @@ const parse = (input, options) => { }; const extglobClose = token => { - const literal = input.slice(token.startIndex, state.index + 1); - const body = input.slice(token.startIndex + 2, state.index); - const analysis = analyzeRepeatedExtglob(body, opts); - - if ((token.type === 'plus' || token.type === 'star') && analysis.risky) { - const safeOutput = analysis.safeOutput - ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) - : undefined; - const open = tokens[token.tokensIndex]; - - open.type = 'text'; - open.value = literal; - open.output = safeOutput || utils.escapeRegex(literal); - - for (let i = token.tokensIndex + 1; i < tokens.length; i++) { - tokens[i].value = ''; - tokens[i].output = ''; - delete tokens[i].suffix; - } - - state.output = token.output + open.output; - state.backtrack = true; - - push({ type: 'paren', extglob: true, value, output: '' }); - decrement('parens'); - return; - } - let output = token.close + (opts.capture ? ')' : ''); let rest; @@ -12519,6 +29022,7 @@ module.exports = parse; /***/ 8016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const scan = __nccwpck_require__(1781); @@ -12754,14 +29258,6 @@ picomatch.scan = (input, options) => scan(input, options); * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * - * ```js - * const picomatch = require('picomatch'); - * const state = picomatch.parse('*.js'); - * // picomatch.compileRe(state[, options]); - * - * console.log(picomatch.compileRe(state)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. @@ -12797,10 +29293,10 @@ picomatch.compileRe = (state, options, returnOutput = false, returnState = false * * ```js * const picomatch = require('picomatch'); - * // picomatch.makeRe(state[, options]); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); * - * const result = picomatch.makeRe('*.js'); - * console.log(result); + * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. @@ -12875,6 +29371,7 @@ module.exports = picomatch; /***/ 1781: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; const utils = __nccwpck_require__(4059); @@ -13273,6 +29770,7 @@ module.exports = scan; /***/ 4059: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; /*global navigator*/ @@ -13347,6 +29845,95 @@ exports.basename = (path, { windows } = {}) => { }; +/***/ }), + +/***/ 7898: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var once = __nccwpck_require__(5560) +var eos = __nccwpck_require__(1424) +var fs = __nccwpck_require__(9896) // we only need fs to get the ReadStream and WriteStream prototypes + +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' +} + +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} + +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} + +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) + + var closed = false + stream.on('close', function () { + closed = true + }) + + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) + + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } +} + +var call = function (fn) { + fn() +} + +var pipe = function (from, to) { + return from.pipe(to) +} + +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') + + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) +} + +module.exports = pump + + /***/ }), /***/ 4351: @@ -13363,11 +29950,236 @@ module.exports = typeof queueMicrotask === 'function' .catch(err => setTimeout(() => { throw err }, 0)) +/***/ }), + +/***/ 5475: +/***/ ((module) => { + +"use strict"; + + +class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + this.maxSize = options.maxSize; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + + _set(key, value) { + this.cache.set(key, value); + this._size++; + + if (this._size >= this.maxSize) { + this._size = 0; + + if (typeof this.onEviction === 'function') { + for (const [key, value] of this.oldCache.entries()) { + this.onEviction(key, value); + } + } + + this.oldCache = this.cache; + this.cache = new Map(); + } + } + + get(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + const value = this.oldCache.get(key); + this.oldCache.delete(key); + this._set(key, value); + return value; + } + } + + set(key, value) { + if (this.cache.has(key)) { + this.cache.set(key, value); + } else { + this._set(key, value); + } + + return this; + } + + has(key) { + return this.cache.has(key) || this.oldCache.has(key); + } + + peek(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + return this.oldCache.get(key); + } + } + + delete(key) { + const deleted = this.cache.delete(key); + if (deleted) { + this._size--; + } + + return this.oldCache.delete(key) || deleted; + } + + clear() { + this.cache.clear(); + this.oldCache.clear(); + this._size = 0; + } + + * keys() { + for (const [key] of this) { + yield key; + } + } + + * values() { + for (const [, value] of this) { + yield value; + } + } + + * [Symbol.iterator]() { + for (const item of this.cache) { + yield item; + } + + for (const item of this.oldCache) { + const [key] = item; + if (!this.cache.has(key)) { + yield item; + } + } + } + + get size() { + let oldCacheSize = 0; + for (const key of this.oldCache.keys()) { + if (!this.cache.has(key)) { + oldCacheSize++; + } + } + + return Math.min(this._size + oldCacheSize, this.maxSize); + } +} + +module.exports = QuickLRU; + + +/***/ }), + +/***/ 8824: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const tls = __nccwpck_require__(4756); + +module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => { + let timeout = false; + + let socket; + + const callback = async () => { + await socketPromise; + + socket.off('timeout', onTimeout); + socket.off('error', reject); + + if (options.resolveSocket) { + resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); + + if (timeout) { + await Promise.resolve(); + socket.emit('timeout'); + } + } else { + socket.destroy(); + resolve({alpnProtocol: socket.alpnProtocol, timeout}); + } + }; + + const onTimeout = async () => { + timeout = true; + callback(); + }; + + const socketPromise = (async () => { + try { + socket = await connect(options, callback); + + socket.on('error', reject); + socket.once('timeout', onTimeout); + } catch (error) { + reject(error); + } + })(); +}); + + +/***/ }), + +/***/ 4145: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Readable = (__nccwpck_require__(2203).Readable); +const lowercaseKeys = __nccwpck_require__(1364); + +class Response extends Readable { + constructor(statusCode, headers, body, url) { + if (typeof statusCode !== 'number') { + throw new TypeError('Argument `statusCode` should be a number'); + } + if (typeof headers !== 'object') { + throw new TypeError('Argument `headers` should be an object'); + } + if (!(body instanceof Buffer)) { + throw new TypeError('Argument `body` should be a buffer'); + } + if (typeof url !== 'string') { + throw new TypeError('Argument `url` should be a string'); + } + + super(); + this.statusCode = statusCode; + this.headers = lowercaseKeys(headers); + this.body = body; + this.url = url; + } + + _read() { + this.push(this.body); + this.push(null); + } +} + +module.exports = Response; + + /***/ }), /***/ 844: /***/ ((module) => { +"use strict"; function reusify (Constructor) { @@ -13466,11 +30278,8 @@ function runParallel (tasks, cb) { /***/ 2560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -;(function (sax) { - // wrapper for non-node envs - sax.parser = function (strict, opt) { - return new SAXParser(strict, opt) - } +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } sax.SAXParser = SAXParser sax.SAXStream = SAXStream sax.createStream = createStream @@ -13487,18 +30296,9 @@ function runParallel (tasks, cb) { sax.MAX_BUFFER_LENGTH = 64 * 1024 var buffers = [ - 'comment', - 'sgmlDecl', - 'textNode', - 'tagName', - 'doctype', - 'procInstName', - 'procInstBody', - 'entity', - 'attribName', - 'attribValue', - 'cdata', - 'script', + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' ] sax.EVENTS = [ @@ -13519,10 +30319,10 @@ function runParallel (tasks, cb) { 'ready', 'script', 'opennamespace', - 'closenamespace', + 'closenamespace' ] - function SAXParser(strict, opt) { + function SAXParser (strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt) } @@ -13531,13 +30331,9 @@ function runParallel (tasks, cb) { clearBuffers(parser) parser.q = parser.c = '' parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - parser.encoding = null; parser.opt = opt || {} parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' - parser.opt.maxEntityCount = parser.opt.maxEntityCount || 512 - parser.opt.maxEntityDepth = parser.opt.maxEntityDepth || 4 - parser.entityCount = parser.entityDepth = 0 parser.tags = [] parser.closed = parser.closedRoot = parser.sawRoot = false parser.tag = parser.error = null @@ -13545,10 +30341,7 @@ function runParallel (tasks, cb) { parser.noscript = !!(strict || parser.opt.noscript) parser.state = S.BEGIN parser.strictEntities = parser.opt.strictEntities - parser.ENTITIES = - parser.strictEntities ? - Object.create(sax.XML_ENTITIES) - : Object.create(sax.ENTITIES) + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) parser.attribList = [] // namespaces form a prototype chain. @@ -13558,12 +30351,6 @@ function runParallel (tasks, cb) { parser.ns = Object.create(rootNS) } - // disallow unquoted attribute values if not otherwise configured - // and strict mode is true - if (parser.opt.unquotedAttributeValues === undefined) { - parser.opt.unquotedAttributeValues = !strict - } - // mostly just for error reporting parser.trackPosition = parser.opt.position !== false if (parser.trackPosition) { @@ -13574,7 +30361,7 @@ function runParallel (tasks, cb) { if (!Object.create) { Object.create = function (o) { - function F() {} + function F () {} F.prototype = o var newf = new F() return newf @@ -13589,7 +30376,7 @@ function runParallel (tasks, cb) { } } - function checkBufferLength(parser) { + function checkBufferLength (parser) { var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) var maxActual = 0 for (var i = 0, l = buffers.length; i < l; i++) { @@ -13625,13 +30412,13 @@ function runParallel (tasks, cb) { parser.bufferCheckPosition = m + parser.position } - function clearBuffers(parser) { + function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i++) { parser[buffers[i]] = '' } } - function flushBuffers(parser) { + function flushBuffers (parser) { closeText(parser) if (parser.cdata !== '') { emitNode(parser, 'oncdata', parser.cdata) @@ -13644,20 +30431,11 @@ function runParallel (tasks, cb) { } SAXParser.prototype = { - end: function () { - end(this) - }, + end: function () { end(this) }, write: write, - resume: function () { - this.error = null - return this - }, - close: function () { - return this.write(null) - }, - flush: function () { - flushBuffers(this) - }, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } } var Stream @@ -13666,50 +30444,16 @@ function runParallel (tasks, cb) { } catch (ex) { Stream = function () {} } - if (!Stream) Stream = function () {} var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' }) - function createStream(strict, opt) { + function createStream (strict, opt) { return new SAXStream(strict, opt) } - function determineBufferEncoding(data, isEnd) { - // BOM-based detection is the most reliable signal when present. - if (data.length >= 2) { - if (data[0] === 0xff && data[1] === 0xfe) { - return 'utf-16le' - } - - if (data[0] === 0xfe && data[1] === 0xff) { - return 'utf-16be' - } - } - - if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) { - return 'utf8' - } - - if (data.length >= 4) { - // XML documents without a BOM still start with "' || isWhitespace(c) } - function isMatch(regex, c) { + function isMatch (regex, c) { return regex.test(c) } - function notMatch(regex, c) { + function notMatch (regex, c) { return !isMatch(regex, c) } @@ -13929,271 +30620,271 @@ function runParallel (tasks, cb) { CLOSE_TAG: S++, // SCRIPT: S++, //