diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ca885e0..04de9970 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,17 @@ # Changelog -# V1.5 (next release) +# V2.0 (next release) -Link +[Link](https://github.com/kiegroup/github-action-build-chain/releases/tag/v2.0) ## Enhancements: -- To be able to define a dependency with a different flow file name -- To be able to define a dependency with a different job identifier - artifacts in case of failure +- centralized flow definition file +- definition-file input added +- rest of inputs removed since they are not needed anymore +- default configuration for every project +- before and after commands added # V1.4 diff --git a/README.md b/README.md index e015e5db..2d6595e4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Let's consider you have a project hierarchy like: and you want to upstream/downstream build whatever project from this hierarchy, **Github Action Build Chain** provides you the mechanism to easily do it. You can check [Usage example](#usage-example). -Just defining the **build chain** flow in every project from the chain, the tool will get meta-info from them and will compose but a chain build means for you and will execute in a single github action. +Just defining the **build chain** flow in every project you want to trigger, the tool will get build information from `dependency-file` input and will execute every command from every project in a single github action. ## Build Chain Flows @@ -21,7 +21,7 @@ Just defining the **build chain** flow in every project from the chain, the tool - It merges the TARGET_GROUP:PROJECT:TARGET_BRANCH into the SOURCE_GROUP:PROJECT:SOURCE_BRANCH from the pull request triggering the job. > **_Warning:_** It will fail in case it can't be done automatically, properly informing to please resolve conflicts. -- It recursively checks out and read workflow information for the rest of the `parent-dependencies` defined in every YAML flow file. +- It recursively checks out the rest of the dependant projects defined in `definition-file`. - For each parent dependency: - It will look for forked project belonging same github group as the one triggering the job. @@ -30,9 +30,7 @@ Just defining the **build chain** flow in every project from the chain, the tool - If previous checkout fails, it will checkout TARGET_GROUP:PROJECT:TARGET_BRANCH. > **_Warning:_** It will fail in case it can't be done automatically, properly informing to please resolve conflicts. -- Once all the projects are checked out, it will run as many commands are defined in `build-command-upstream` input (it will take `build-command` input in case there's no `build-command-upstream` defined) for every parent dependency starting from the highest level of the hierarchy to the lowest one. - -- It will run as many commands are defined in `build-command`for the project triggering the job. +- Once all the projects are checked out, it will run as many commands are defined in `before`, `after` or root level properties from `build` section for every parent dependency starting from the highest level of the hierarchy to the lowest one. - It will archive artifacts in case `archive-artifacts-path` input is defined. @@ -41,153 +39,35 @@ Just defining the **build chain** flow in every project from the chain, the tool It is just to add the step (replacing dependencies and commands): ``` -- name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - parent-dependencies: 'projectA' - child-dependencies: | - projectC - projectD - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" +- name: Build Chain ${{ matrix.java-version }} + id: build-chain + uses: ginxo/github-action-build-chain@BXMSPROD-1025 + with: + definition-file: https://raw.githubusercontent.com/${GROUP}/droolsjbpm-build-bootstrap/${BRANCH}/.ci/pull-request-config.yaml + env: + GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" ``` -to your existing yaml flow definition or to create a new one. Do the same for the rest of the projects you need. The `@actions/checkout` step is not needed since is the tool the one which is going to handle what to checkout for every project in the chain. +to your existing yaml flow definition or to create a new one. Do the same for the rest of the projects you need. + +> **_Note:_** The `@actions/checkout` step is not needed since is the tool the one which is going to handle what to checkout for every project in the chain. ## Input Fields See [action.yml](action.yml) -- **parent-dependencies** (optional): `[group/]projectName[@branchSource:branchTarget][|[flowfile.yaml][:jobId]]]` The parent projects dependencies to depend on. You can defined several depencies thanks to the [yaml block scalar functionality](https://yaml.org/spec/1.2/spec.html#Block). They are basically the projects to depend on. - - `group/`: (optional) The github group where the project is, otherwise it will be taken from same group. - - `projectName`: (mandatory) The project name. - - `@branchSource:branchTarget`: (optional) It is possible to map branches for projects. `projectx@master:7.x` would map whatever pull request is performed for `master` branch to `projectX:7.x`. - - `|flowfile.yaml`: (optional) in case the dependency has a different flow file name. - - `|:jobId`: (optional) in case the dependency has a different jobId. - -> Example: -> -> ``` -> parent-dependencies: 'projectA' -> parent-dependencies: | -> projectA -> groupX/projectB -> projectC@master:7.x -> groupy/projectD@8.0.0:9.0.1 -> groupy/projectD|flow.yml:jobIdX -> groupy/projectD|:jobIdX -> groupy/projectD|flow.yml -> groupy/projectD@8.0.0:9.0.1|flow.yml:jobIdX -> groupy/projectD@8.0.0:9.0.1|:jobIdX -> groupy/projectD@8.0.0:9.0.1|flow.yml -> ``` - -- **child-dependencies** (optional): `[group/]projectName[@branchSource:branchTarget][|[flowfile.yaml][:jobId]]]` The child projects dependencies that depends on this project. You can defined several depencies thanks to the [yaml block scalar functionality](https://yaml.org/spec/1.2/spec.html#Block). - - `group/`: (optional) The github group where the project is, otherwise it will be taken from the same group. - - `projectName`: (mandatory) The project name. - - `@branchSource:branchTarget`: (optional) It is possible to map branches for projects. `projectx@master:7.x` would map whatever pull request is performed for `master` branch to `projectX:7.x`. - - `|flowfile.yaml`: (optional) in case the dependency has a different flow file name. - - `|:jobId`: (optional) in case the dependency has a different jobId. - -> Examples: -> -> ``` -> child-dependencies: 'projectA' -> child-dependencies: | -> projectA -> groupX/projectB -> projectC@master:7.x -> groupy/projectD@8.0.0:9.0.1 -> groupy/projectD|flow.yml:jobIdX -> groupy/projectD|:jobIdX -> groupy/projectD|flow.yml -> groupy/projectD@8.0.0:9.0.1|flow.yml:jobIdX -> groupy/projectD@8.0.0:9.0.1|:jobIdX -> groupy/projectD@8.0.0:9.0.1|flow.yml -> ``` - -- **build-command** (required): `command1[\ncommand2\ncommand3]` The command(s) to build. You can defined several commands thanks to the [yaml block scalar functionality](https://yaml.org/spec/1.2/spec.html#Block). - - > Example: - > - > ``` - > build-command: 'mvn clean install' - > build-command: | - > mvn clean install - > mvn -e -nsu -Dfull -Pwildfly clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dcontainer=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g" - > build-command: | - > sh scripts/prepare_environment_build_images.sh - > mkdir -p ${{ matrix.images }} - > rsync -av --progress . ${{ matrix.images }} --exclude workspaces - > make ${{ matrix.images }} ignore_test=true cekit_option="--work-dir . - > make ${{ matrix.images }} ignore_build=true cekit_option="--work-dir . - > ``` - -- **build-command-upstream** (optional): `command1[\ncommand2\ncommand3]` The command(s) to build in case the project is built by a child project. If it's not defined `build-command` will be taken. You can defined several commands thanks to the [yaml block scalar functionality](https://yaml.org/spec/1.2/spec.html#Block). - - > Example: - > - > ``` - > build-command-upstream: 'mvn clean install' - > build-command-upstream: | - > mvn clean install - > mvn -e -nsu -Dfull -Pwildfly clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dcontainer=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g" - > ``` - -- **workflow-file-name** (required): `file_name.yml` it defines which workflow file name will be taken from the rest of the projects to get metainfo. _This is the most embarrassing field we have here :pensive:. It's due to github does not provide filename in case the `name` is defined for the flow. The information is stored in `GITHUB_WORKFLOW` environment variable but it's overridden in case you define a name for it (which is the most common thing). It is better explained in [workflow-file-name section](#workflow-file-name)_. - - > **_Warning:_** The flow files should be placed in `.github/workflows` folder for every project from the chain. Don't specify `.github/workflows/whateverflowfilename.yaml`, just `whateverflowfilename.yaml`. +- **definition-file** (mandatory): `path to the file in filesystem | URL to the file` > Example: > > ``` - > workflow-file-name: "pull_request.yml" - > workflow-file-name: "whateverflowfilename.yml" - > ``` - -- **matrix-variables** (optional): `key:${{ flowvariable1 }}[\nkey2:${{ flowvariable2 }}\nmatrix.variable:${{ matrix.variable }}]` define it in case you use matrix variables in your with parameters. - - > Examples: - > - > ``` - > build-command: mkdir -p ${{ matrix.images }} - > matrix-variables: matrix.images:${{ matrix.images }} - > ``` - + > definition-file: './folder/whatever_definition_file.yaml' + > definition-file: 'http://yourdomain.com/definition-file.yaml' + > definition-file: 'https://raw.githubusercontent.com/kiegroup/droolsjbpm-build-bootstrap/master/.ci/pull-request-config.yaml' + > definition-file: 'https://raw.githubusercontent.com/kiegroup/droolsjbpm-build-bootstrap/${BRANCH}/.ci/pull-request-config.yaml' + > definition-file: 'https://raw.githubusercontent.com/${GROUP}/droolsjbpm-build-bootstrap/${BRANCH}/.ci/pull-request-config.yaml' + > definition-file: 'https://raw.githubusercontent.com/${GROUP}/${PROJECT_NAME}/${BRANCH}/.ci/pull-request-config.yaml' > ``` - > build-command-upstream: | - > mkdir -p ${{ matrix.images }} - > rsync -av --progress . ${{ matrix.os }} - > matrix-variables: | - > matrix.images:${{ matrix.images }} - > matrix.os:${{ matrix.os }} - > ``` - -- **archive-artifacts-path** (optional): `file path[@success|failure|always (success by default)]` (see: [@actions/glob](https://github.com/actions/toolkit/tree/main/packages/glob) and [Archiving Artifacts](#archiving-artifacts)). define it in case you want to archive artifacts after building the project chain. - - > Example: see [Archiving Artifacts](#archiving-artifacts) - > - > Example about `[@success|failure|always]`: [Upload for different execution results](https://github.com/actions/upload-artifact#upload-for-different-execution-results) - -* **archive-artifacts-name** (optional, default: `the project name`): `a string` (see: [Archiving Artifacts](#archiving-artifacts) and [Uploading without an artifact name](#uploading-without-an-artifact-name)). define it in case you want to archive artifacts after building the project chain. - - > **_Warning:_** `archive-artifacts-path` input is mandatory in case you want to use this field (it does not make sense to specify an artifact name without defining what you want to upload) - - > Example: see [Archiving Artifacts](#archiving-artifacts) - -* **archive-artifacts-if-no-files-found** (optional, default: `warn`): `warn|ignore|error` (see: [Archiving Artifacts](#archiving-artifacts) and [Customization if no files are found](#customization-if-no-files-are-found)). Allows you to customize the behavior of the action if no files are found. - - > **_Warning:_** `archive-artifacts-path` input is mandatory in case you want to use this field (it does not make sense to specify the failure behaviour without defining what you want to upload) - - > Example: see [Archiving Artifacts](#archiving-artifacts) - -* **archive-artifacts-dependencies** (optional, default: `none`): `all|none|list of projects` (see: [Archiving Artifacts](#archiving-artifacts) and [archive-artifacts-dependencies usage](#archive-artifacts-dependencies-usage)). Allows you to decide which projects you want treat to upload artifacts from the project triggering the job. - - > **_Note:_** `archive-artifacts-path` input is **NOT** mandatory in case you want to use this field - - > Example: see [Archiving Artifacts](#archiving-artifacts) ## Archiving Artifacts @@ -198,52 +78,32 @@ The `archive-artifacts-path` input brings you the chance to specify if the path ### Upload an Individual File ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: path/to/artifact/world.txt +archive-artifacts: + path: **/dashbuilder-runtime.war ``` ### Upload an Entire Directory ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: path/to/artifact/ # or path/to/artifact +archive-artifacts: + path: path/to/artifact-folder/ ``` ### Upload using a Wildcard Pattern ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: path/**/[abc]rtifac?/* +archive-artifacts: + path: path/**/[abc]rtifac?/* ``` ### Upload using Multiple Paths and Exclusions ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: | - path/output/bin/ - path/output/test-results - !path/**/*.tmp +archive-artifacts: + path: | + path/output/bin/ + path/output/test-results + !path/**/*.tmp ``` ### Upload for different execution results @@ -251,17 +111,12 @@ steps: This is something additional to [@actions/glob](https://github.com/actions/toolkit/tree/main/packages/glob) ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: | - path/output/bin/ - path2/output2/bin2/@sucess - path/output/test-results@failure - !path/**/*.tmp@always +archive-artifacts: + path: | + path/output/bin/ + path2/output2/bin2/@sucess + path/output/test-results@failure + !path/**/*.tmp@always ``` - will upload `path/output/bin/` just in case of `success` @@ -298,30 +153,23 @@ The [@actions/artifact](https://github.com/actions/toolkit/tree/main/packages/ar If a path (or paths), result in no files being found for the artifact, the action will succeed but print out a warning. In certain scenarios it may be desirable to fail the action or suppress the warning. The `if-no-files-found` option allows you to customize the behavior of the action if no files are found. ```yaml -steps: -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: path/to/artifact/ - archive-artifacts-if-no-files-found: error # 'warn' or 'ignore' are also available, defaults to `warn` +archive-artifacts: + path: path/to/artifact/ + if-no-files-found: error # 'warn' or 'ignore' are also available, defaults to `warn` ``` ### Conditional Artifact Upload not supported (yet) -### Uploading without an artifact name +### Uploading without artifact name -You can upload an artifact without specifying a name +You can upload an artifact with or without specifying a name ```yaml -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: path/to/artifact/world.txt +archive-artifacts: + name: my-artifacts + path: **/dashbuilder-runtime.war ``` If not provided, `artifact` will be used as the default name which will manifest itself in the UI after upload. @@ -332,113 +180,59 @@ Each artifact behaves as a file share. Uploading to the same artifact multiple t ```yaml # Project A -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: world.txt +archive-artifacts: + path: world.txt ``` ```yaml # Project B -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: extra-file.txt +archive-artifacts: + path: extra-file.txt ``` ```yaml # Project C -- uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: world.txt +archive-artifacts: + path: world.txt ``` With the following example, the available artifact (named `artifact` which is the default if no name is provided) would contain both `world.txt` and `extra-file.txt`. -> **_Warning:_** Be careful when uploading to the same artifact via multiple jobs as artifacts may become corrupted - -```yaml - strategy: - matrix: - java-version: [8, 9, 11, 13] - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: ${{ matrix.java-version }} - - name: 'Accidently upload to the same artifact via multiple jobs' - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact - archive-artifacts-path: world.txt -``` - -In the above example, four jobs will upload four different files to the same artifact but there will only be one file available when `my-artifact` is downloaded. Each job overwrites what was previously uploaded. To ensure that jobs don't overwrite existing artifacts, use a different name per job. - -```yaml - - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: my-artifact ${{ matrix.java-version }} - archive-artifacts-path: world.txt - matrix-variables: "matrix.java-version:${{ matrix.java-version }} -``` - ### Environment Variables and Tilde Expansion You can use `~` in the path input as a substitute for `$HOME`. Basic tilde expansion is supported. ```yaml - - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-name: 'Artifacts-V2' - archive-artifacts-path: '~/new/**/*' +archive-artifacts: + path: "~/new/**/*" ``` -### archive-artifacts-dependencies usage +### archive-artifacts dependencies usage -The idea of the field `archive-artifacts-dependencies` is to allow to define from the project triggering the job which artifacts you want to archive from the whole chain. Possible values: +The idea of the property `dependencies` is to allow to define from the project triggering the job which artifacts you want to archive from the whole chain. Possible values: - `none` no artifact from its dependencies will be uploaded, no matter what the dependencies projects define. - `all` all artifacts from its dependencies will be uploaded, dependending on what the dependencies define. - `list of projects` define which of the projects in the chain will be treated to upload artifacts, dependending on what the dependencies define. ```yaml - - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: '~/new/**/*' - archive-artifacts-dependencies: 'none' +archive-artifacts: + path: "~/new/**/*" + dependencies: "none" ``` ```yaml - - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: '~/new/**/*' - archive-artifacts-dependencies: 'all' +archive-artifacts: + path: "~/new/**/*" + dependencies: "all" ``` ```yaml - - uses: kiegroup/github-action-build-chain - with: - ... - ... - archive-artifacts-path: '~/new/**/*' - archive-artifacts-dependencies: | - projectX - projectY +archive-artifacts: + path: "~/new/**/*" + dependencies: | + projectX + projectY ``` ## Where does the upload go? @@ -481,140 +275,7 @@ Considering the projects hierarchy: ![Project hierarchy](/docs/project-hierarchy.png) -**Project A** - -``` -name: Build Chain - -on: [pull_request] - -jobs: - build-chain-openjdk8: - runs-on: ubuntu-latest - name: Pull Request openjdk8 - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - child-dependencies: | - projectC - projectD - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" -``` - -**Project B** - -``` -name: Build Chain - -on: [pull_request] - -jobs: - build-chain-openjdk8: - runs-on: ubuntu-latest - name: Pull Request openjdk8 - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - child-dependencies: 'projectD' - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" -``` - -**Project C** - -``` -name: Build Chain - -on: [pull_request] - -jobs: - build-chain-openjdk8: - runs-on: ubuntu-latest - name: Pull Request openjdk8 - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - parent-dependencies: 'projectD' - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" -``` - -**Project D** - -``` -name: Build Chain - -on: [pull_request] - -jobs: - build-chain-openjdk8: - runs-on: ubuntu-latest - name: Pull Request openjdk8 - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - parent-dependencies: | - projectA - projectB - child-dependencies: 'projectE' - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" -``` - -**Project E** - -``` -name: Build Chain - -on: [pull_request] - -jobs: - build-chain-openjdk8: - runs-on: ubuntu-latest - name: Pull Request openjdk8 - steps: - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build Chain - id: build-chain - uses: kiegroup/github-action-build-chain - with: - parent-dependencies: 'projectD' - build-command: 'mvn whatever goals' - build-command-upstream: 'mvn whatever goals' - workflow-file-name: "whatever_flow.yml" -``` +// TO BE DOCUMENTED ## Docker build @@ -630,30 +291,29 @@ In case you want to build it for a different openjdk version you just specify a docker build --build-arg OPENJDK_VERSION=11 . ``` -## Testing - -### Unit testing - -- **TEST_GITHUB_TOKEN** env variable is needed. +## Execution -### Integration testing - -In order to execute integration testing you just run `env GITHUB_TOKEN=%TOKEN% URL=%GITHUB_EVENT_URL% workflow-file-name=%WORKFLOW_FILE_NAME% GITHUB_JOB='%GITHUB_JOB%' yarn it` where: +It is possible to execute build-chain flow anywhere you want (just remember your machine would need to meet requirements to execute commands). In order to execute it locally (wherever) you just run `env GITHUB_TOKEN=%TOKEN% URL=%GITHUB_EVENT_URL% definition-file=%DEFINITION_FILE% yarn it` where: - %TOKEN%: is your personal token, like `1e2ca1ac1252121d83fbe69ab3c4dd92bcb1ae32`. - %GITHUB_EVENT_URL%: the url to your event to test, like `https://github.com/kiegroup/kogito-images/pull/220`. -- %WORKFLOW_FILE_NAME%: the workflow file name located in `.github/workflows` folder, like `build_images.yml`. -- %GITHUB_JOB%: the job id from the `%WORKFLOW_FILE_NAME%` to execute. +- %DEFINITION_FILE%: The workflow definition file path, it can be a path in the filesystem or a URL to the file. So the final command would look like -`env GITHUB_TOKEN=3e6ce1ac1772121d83fbe69ab3c4dd92dad1ae40 URL=https://github.com/kiegroup/lienzo-core/pull/3 workflow-file-name=pull_request.yml GITHUB_JOB='build-chain-openjdk8' yarn it`. +`env GITHUB_TOKEN=3e6ce1ac1772121d83fbe69ab3c4dd92dad1ae40 URL=https://github.com/kiegroup/lienzo-core/pull/3 definition-file=https://raw.githubusercontent.com/kiegroup/droolsjbpm-build-bootstrap/master/.ci/pull-request-config.yaml yarn it` or `npm run it` in case you prefer to use npm. -## Github limitations +## Development + +### build-chain-configuration-reader dependency -### workflow-file-name +The definition files are read thanks to [build-chain-configuration-reader](https://github.com/kiegroup/build-chain-configuration-reader) library so in case you want to modify something from there it's easier if you just [npm link](https://docs.npmjs.com/cli/link) it: -You are probably wondering why the input field `workflow-file-name` even exists. Why don't we take the filename directly from the job and keep the same name for all the flow files in the chain?. Well, we can in case the `name` is not defined in the flow, then the file name information can be taken from `GITHUB_WORKFLOW` environment variable but in case the name is set, `GITHUB_WORKFLOW` becomes the name and there's no other way to get filename from the tool. -This is a github action limitation already reported as a suggestion to provide file name from the flow triggering the job. +- clone repo and browse to the folder +- `npm/yarn install` it +- (`sudo`) `npm link` +- and then from this project folder execute `npm link @kie/build-chain-configuration-reader` + +## Github limitations ### inputs usage in runs.image from action.yml diff --git a/action.yml b/action.yml index 47394ad8..195f63e8 100644 --- a/action.yml +++ b/action.yml @@ -3,51 +3,9 @@ author: "Enrique Mingorance Cano " description: | Github action build chain is a tool to build multiple projects from different repositories in a single action. inputs: - parent-dependencies: - description: "the list of parent project dependencies separated by comma. Something like lienzo-core,lienzo-tests" - required: false - child-dependencies: - description: "the list of child project dependencies separated by comma. Something like appformer,kiegroup/droolsjbpm-build-bootstrap,drools" - required: false - build-command: - description: "the list of commands as string split by | to run" + definition-file: + description: "the file where the build chain is defined. It can a file in the same repository (relative path) or a URL" required: true - build-command-upstream: - description: "the list of commands as string split by | to run in case the project is upstream built" - required: false - workflow-file-name: - description: "the file flow file name, normally the same one where the flow is stored. Like `pull_request.yml`" - required: true - matrix-variables: - description: "the map of matrix-variable-key:matrix-variable-value in case you want to use them from build-command/build-command-upstream.." - required: false - archive-artifacts-path: - description: "A file, directory or wildcard pattern that describes what to upload" - required: false - archive-artifacts-name: - description: "Artifact name" - default: "artifact" - required: false - archive-artifacts-if-no-files-found: - description: > - The desired behavior if no files are found using the provided path. - - Available Options: - warn: Output a warning but do not fail the action. - error: Fail the action with an error message. - ignore: Do not output any warnings or errors, the action does not fail. - default: "warn" - required: false - archive-artifacts-dependencies: - description: > - whether the artifacts from the dependencies has to be uploaded or not. - - Available Options: - none: no artifact from any dependency/dependant project will be uploaded. - all: all the artifacts defined by the dependencies will be uploaded. - a list of projects: only the projects defined here will be uploaded. - default: "none" - required: false runs: using: "node12" main: "dist/index.js" diff --git a/dist/index.js b/dist/index.js index 7abc0f87..3787cd1e 100755 --- a/dist/index.js +++ b/dist/index.js @@ -611,7 +611,26 @@ module.exports._enoent = enoent; /***/ }), /* 21 */, -/* 22 */, +/* 22 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const http = __webpack_require__(605); +const https = __webpack_require__(34); + +function checkUrlExist(url) { + return new Promise(resolve => { + (url.startsWith("https://") ? https : http).get(url, response => { + resolve(200 === response.statusCode); + }); + }); +} + +module.exports = { + checkUrlExist +}; + + +/***/ }), /* 23 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -638,7 +657,7 @@ module.exports = new Schema({ __webpack_require__(809), __webpack_require__(228), __webpack_require__(44), - __webpack_require__(312) + __webpack_require__(417) ] }); @@ -931,3199 +950,2636 @@ module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'; /***/ }), /* 46 */, /* 47 */, -/* 48 */ -/***/ (function(module, exports) { +/* 48 */, +/* 49 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports = module.exports = SemVer +"use strict"; -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} +const os = __webpack_require__(87); +const execa = __webpack_require__(955); -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' +// Reference: https://www.gaijin.at/en/lstwinver.php +const names = new Map([ + ['10.0', '10'], + ['6.3', '8.1'], + ['6.2', '8'], + ['6.1', '7'], + ['6.0', 'Vista'], + ['5.2', 'Server 2003'], + ['5.1', 'XP'], + ['5.0', '2000'], + ['4.9', 'ME'], + ['4.1', '98'], + ['4.0', '95'] +]); -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +const windowsRelease = release => { + const version = /\d+\.\d/.exec(release || os.release()); -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 + if (release && !version) { + throw new Error('`release` argument doesn\'t match `n.n`'); + } -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 + const ver = (version || [])[0]; -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime. + // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version + // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx + // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead. + // If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name. + if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { + let stdout; + try { + stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; + } catch (_) { + stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || ''; + } -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + const year = (stdout.match(/2008|2012|2016|2019/) || [])[0]; -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + if (year) { + return `Server ${year}`; + } + } -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + return names.get(ver); +}; -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' +module.exports = windowsRelease; -// ## Main Version -// Three dot-separated numeric identifiers. -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' +/***/ }), +/* 50 */, +/* 51 */, +/* 52 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' +const noTreatment = __webpack_require__(981); +const mavenTreatment = __webpack_require__(121); -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. +function treatCommand(command) { + let libraryToExecute = noTreatment; + if (command.match(/.*mvn .*/)) { + libraryToExecute = mavenTreatment; + } + return libraryToExecute.treat(command); +} -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +module.exports = { + treatCommand +}; -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +/***/ }), +/* 53 */, +/* 54 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' +"use strict"; +// Adapted from https://github.com/sindresorhus/make-dir +// Copyright (c) Sindre Sorhus (sindresorhus.com) +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' +const fs = __webpack_require__(869) +const path = __webpack_require__(622) +const atLeastNode = __webpack_require__(159) -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +const useNativeRecursiveOption = atLeastNode('10.12.0') -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`) + error.code = 'EINVAL' + throw error + } + } +} -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' +const processOptions = options => { + const defaults = { mode: 0o777 } + if (typeof options === 'number') options = { mode: options } + return { ...defaults, ...options } +} -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`) + error.code = 'EPERM' + error.errno = -4048 + error.path = pth + error.syscall = 'mkdir' + return error +} -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +module.exports.makeDir = async (input, options) => { + checkPath(input) + options = processOptions(options) -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' + if (useNativeRecursiveOption) { + const pth = path.resolve(input) -src[FULL] = '^' + FULLPLAIN + '$' + return fs.mkdir(pth, { + mode: options.mode, + recursive: true + }) + } -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' + const make = async pth => { + try { + await fs.mkdir(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' + if (error.message.includes('null bytes')) { + throw error + } -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + await make(path.dirname(pth)) + return make(pth) + } -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + try { + const stats = await fs.stat(pth) + if (!stats.isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } } } - if (version instanceof SemVer) { - return version - } + return make(path.resolve(input)) +} - if (typeof version !== 'string') { - return null - } +module.exports.makeDirSync = (input, options) => { + checkPath(input) + options = processOptions(options) - if (version.length > MAX_LENGTH) { - return null - } + if (useNativeRecursiveOption) { + const pth = path.resolve(input) - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null + return fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }) } - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} + const make = pth => { + try { + fs.mkdirSync(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} + if (error.message.includes('null bytes')) { + throw error + } -exports.SemVer = SemVer + make(path.dirname(pth)) + return make(pth) + } -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + try { + if (!fs.statSync(pth).isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } + return make(path.resolve(input)) +} - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) +/***/ }), +/* 55 */, +/* 56 */, +/* 57 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (!m) { - throw new TypeError('Invalid Version: ' + version) +const { + clone, + doesBranchExist, + merge: gitMerge, + hasPullRequest, + getForkedProject +} = __webpack_require__(484); +const { logger } = __webpack_require__(79); +const { + parentChainFromNode, + treatUrl +} = __webpack_require__(702); +const { checkUrlExist } = __webpack_require__(22); + +async function checkoutDefinitionTree(context, treeNode) { + const nodeChain = await parentChainFromNode(treeNode); + let currentTargetBranch = context.config.github.targetBranch; + for (const node of [...nodeChain].reverse()) { + try { + node.checkoutInfo = await checkoutProject( + context, + node, + currentTargetBranch + ); + currentTargetBranch = node.checkoutInfo.targetBranch; + } catch (err) { + logger.error(`Error checking out project ${node.project}`); + throw err; + } } - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + return nodeChain; +} - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') +async function checkoutProject(context, node, currentTargetBranch) { + logger.info(`[${node.project}] Checking out project`); + const dir = getDir(context.config.rootFolder, node.project); + const checkoutInfo = await getCheckoutInfo( + context, + node.repo.group, + node.repo.name, + currentTargetBranch, + node.mapping + ); + if (checkoutInfo == undefined) { + const msg = `Trying to checking out ${node.project} into '${dir}'. It does not exist.`; + logger.error(msg); + throw new Error(msg); } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + if (checkoutInfo.merge) { + logger.info( + `[${node.project}] Merging ${context.config.github.serverUrl}/${node.project}:${checkoutInfo.targetBranch} into ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}` + ); + try { + await clone( + `${context.config.github.serverUrl}/${node.project}`, + dir, + checkoutInfo.targetBranch + ); + } catch (err) { + logger.error( + `Error checking out (before merging) ${context.config.github.serverUrl}/${node.repo.group}/${node.project}:${context.config.github.targetBranch}` + ); + throw err; + } + try { + await gitMerge( + dir, + checkoutInfo.group, + checkoutInfo.project, + checkoutInfo.branch + ); + } catch (err) { + logger.error( + `Error merging ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}. Please manually merge it and relaunch.` + ); + throw err; + } + } else { + try { + logger.info( + `Checking out '${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}' into '${dir}'` + ); + await clone( + `${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}`, + dir, + checkoutInfo.branch + ); + } catch (err) { + logger.error( + `Error checking out ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}.` + ); + throw err; + } } + return checkoutInfo; +} - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } +async function getCheckoutInfo( + context, + targetGroup, + targetProject, + currentTargetBranch, + mapping +) { + const sourceGroup = context.config.github.sourceGroup; + const sourceBranch = context.config.github.sourceBranch; + const targetBranch = + mapping && mapping.source === currentTargetBranch + ? mapping.target + : currentTargetBranch; + const forkedProjectName = await getForkedProjectName( + context.octokit, + targetGroup, + targetProject, + sourceGroup + ); + logger.info( + `[${targetGroup}/${targetProject}] Getting checkout Info. sourceProject: ${forkedProjectName} sourceGroup: ${sourceGroup}. sourceBranch: ${sourceBranch}. targetGroup: ${targetGroup}. targetBranch: ${targetBranch}. Mapping: ${ + mapping + ? "source:" + mapping.source + " target:" + mapping.target + : "not defined" + }` + ); + return (await doesBranchExist( + context.octokit, + sourceGroup, + forkedProjectName, + sourceBranch + )) + ? { + project: forkedProjectName, + group: sourceGroup, + branch: sourceBranch, + targetGroup, + targetBranch, + merge: await hasPullRequest( + context.octokit, + targetGroup, + targetProject, + sourceBranch, + context.config.github.author + ) } - return id - }) - } + : (await doesBranchExist( + context.octokit, + targetGroup, + targetProject, + sourceBranch + )) + ? { + project: targetProject, + group: targetGroup, + branch: sourceBranch, + targetGroup, + targetBranch, + merge: await hasPullRequest( + context.octokit, + targetGroup, + targetProject, + sourceBranch, + context.config.github.author + ) + } + : (await doesBranchExist( + context.octokit, + targetGroup, + targetProject, + targetBranch + )) + ? { + project: targetProject, + group: targetGroup, + branch: targetBranch, + targetGroup, + targetBranch, + merge: false + } + : undefined; +} - this.build = m[5] ? m[5].split('.') : [] - this.format() +function getDir(rootFolder, project) { + const folder = + rootFolder !== undefined && rootFolder !== "" ? rootFolder : "."; + return `${folder}/${project.replace(/ |-/g, "_")}`; } -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') +async function getForkedProjectName(octokit, owner, project, wantedOwner) { + if (owner !== wantedOwner) { + const forkedProject = await getForkedProject( + octokit, + owner, + project, + wantedOwner + ); + return !forkedProject || !forkedProject.name ? project : forkedProject.name; + } else { + return project; } - return this.version } -SemVer.prototype.toString = function () { - return this.version +/** + * it checks what's the proper URL to retrieve definition from in case a URL with ${} expression is defined. It will try sourceGroup/sourceBranch then targetGroup/sourceBranch and then targetGroup/targetBranch in this order. + * @param {Object} context the context information + * @param {Object} definitionFile the definition file path or URL + */ +async function getFinalDefinitionFilePath(context, definitionFile) { + if (definitionFile.startsWith("http") && definitionFile.includes("${")) { + const sourceGroupAndBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.sourceGroup, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.sourceBranch + }); + if (!(await checkUrlExist(sourceGroupAndBranchOption))) { + const targetGroupSourceBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.group, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.sourceBranch + }); + if (!(await checkUrlExist(targetGroupSourceBranchOption))) { + const targetGroupAndBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.group, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.targetBranch + }); + if (!(await checkUrlExist(targetGroupAndBranchOption))) { + throw new Error( + `Definition file ${definitionFile} does not exist for any of these cases: ${sourceGroupAndBranchOption}, ${targetGroupSourceBranchOption} or ${targetGroupAndBranchOption}` + ); + } else { + return targetGroupAndBranchOption; + } + } else { + return targetGroupSourceBranchOption; + } + } else { + return sourceGroupAndBranchOption; + } + } + return definitionFile; } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +module.exports = { + checkoutDefinitionTree, + getCheckoutInfo, + getDir, + getFinalDefinitionFilePath +}; - return this.compareMain(other) || this.comparePre(other) -} -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +/***/ }), +/* 58 */, +/* 59 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} +"use strict"; -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } +var util = __webpack_require__(669); - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) +// Constants +var c = __webpack_require__(45); + +var $$ = __webpack_require__(255); +var HelpFormatter = __webpack_require__(532); + +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +function ArgumentDefaultsHelpFormatter(options) { + HelpFormatter.call(this, options); } -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break +util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } +ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { + var help = action.help; + if (action.help.indexOf('%(defaultValue)s') === -1) { + if (action.defaultValue !== c.SUPPRESS) { + var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ]; + if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { + help += ' (default: %(defaultValue)s)'; } - break - - default: - throw new Error('invalid increment argument: ' + release) + } } - this.format() - this.raw = this.version - return this -} + return help; +}; -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } +module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } +function RawDescriptionHelpFormatter(options) { + HelpFormatter.call(this, options); } -exports.compareIdentifiers = compareIdentifiers +util.inherits(RawDescriptionHelpFormatter, HelpFormatter); -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) +RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = text.split('\n'); + lines = lines.map(function (line) { + return $$.trimEnd(indent + line); + }); + return lines.join('\n'); +}; +module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; - if (anum && bnum) { - a = +a - b = +b - } +/** + * new RawTextHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) + * + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 +function RawTextHelpFormatter(options) { + RawDescriptionHelpFormatter.call(this, options); } -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} +util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} +RawTextHelpFormatter.prototype._splitLines = function (text) { + return text.split('\n'); +}; -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} +module.exports.RawTextHelpFormatter = RawTextHelpFormatter; -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} +/***/ }), +/* 60 */, +/* 61 */, +/* 62 */, +/* 63 */, +/* 64 */, +/* 65 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} +"use strict"; +/** internal + * class ArgumentGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} +var util = __webpack_require__(669); -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} +var ActionContainer = __webpack_require__(614); -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} +/** + * new ArgumentGroup(container, options) + * - container (object): main container + * - options (object): hash of group options + * + * #### options + * - **prefixChars** group name prefix + * - **argumentDefault** default argument value + * - **title** group title + * - **description** group description + * + **/ +var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} + options = options || {}; -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + // add any missing keyword arguments by checking the container + options.conflictHandler = (options.conflictHandler || container.conflictHandler); + options.prefixChars = (options.prefixChars || container.prefixChars); + options.argumentDefault = (options.argumentDefault || container.argumentDefault); -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + ActionContainer.call(this, options); -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} + // group attributes + this.title = options.title; + this._groupActions = []; -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b + // share most attributes with the container + this._container = container; + this._registries = container._registries; + this._actions = container._actions; + this._optionStringActions = container._optionStringActions; + this._defaults = container._defaults; + this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; + this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; +}; +util.inherits(ArgumentGroup, ActionContainer); - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - case '': - case '=': - case '==': - return eq(a, b, loose) +ArgumentGroup.prototype._addAction = function (action) { + // Parent add action + action = ActionContainer.prototype._addAction.call(this, action); + this._groupActions.push(action); + return action; +}; - case '!=': - return neq(a, b, loose) - case '>': - return gt(a, b, loose) +ArgumentGroup.prototype._removeAction = function (action) { + // Parent remove action + ActionContainer.prototype._removeAction.call(this, action); + var actionIndex = this._groupActions.indexOf(action); + if (actionIndex >= 0) { + this._groupActions.splice(actionIndex, 1); + } +}; - case '>=': - return gte(a, b, loose) - case '<': - return lt(a, b, loose) - case '<=': - return lte(a, b, loose) +/***/ }), +/* 66 */, +/* 67 */, +/* 68 */, +/* 69 */, +/* 70 */, +/* 71 */, +/* 72 */, +/* 73 */, +/* 74 */, +/* 75 */, +/* 76 */, +/* 77 */, +/* 78 */, +/* 79 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - default: - throw new TypeError('Invalid operator: ' + op) - } -} +const util = __webpack_require__(669); +const process = __webpack_require__(765); -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +class ClientError extends Error {} - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp +class TimeoutError extends Error {} + +function log(prefix, obj) { + if (process.env.NODE_ENV !== "test") { + const str = obj.map(o => (typeof o === "object" ? inspect(o) : o)); + if (prefix) { + console.log.apply(console, [prefix, ...str]); } else { - comp = comp.value + console.log.apply(console, str); } } +} - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } +const logger = { + level: "info", - debug('comp', this) -} + trace: (...str) => { + if (logger.level === "trace") { + log("[TRACE]", str); + } + }, -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) + debug: (...str) => { + if (logger.level === "trace" || logger.level === "debug") { + log("DEBUG", str); + } + }, - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } + info: (...str) => log("[INFO] ", str), + warn: (...str) => log("[WARN] ", str), - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' + error: (...str) => { + if (str.length === 1) { + if (str[0] instanceof Error) { + if (logger.level === "trace" || logger.level === "debug") { + log(null, [str[0].stack || str[0]]); + } else { + log("[ERROR] ", [str[0].message || str[0]]); + } + } + } else { + log("[ERROR] ", str); + } } +}; - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } +function inspect(obj) { + return util.inspect(obj, false, null, true); } -Comparator.prototype.toString = function () { - return this.value -} +module.exports = { + ClientError, + TimeoutError, + logger +}; -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - if (this.semver === ANY) { - return true - } +/***/ }), +/* 80 */, +/* 81 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (typeof version === 'string') { - version = new SemVer(version, this.options) +const { logger } = __webpack_require__(79); +const exec = __webpack_require__(986); + +class ExitError extends Error { + constructor(message, code) { + super(message); + this.code = code; } +} - return cmp(version, this.operator, this.semver, this.options) +async function execute(cwd, command) { + logger.info(`Execute command '${command}' in dir '${cwd}'`); + const options = {}; + options.cwd = cwd; + await exec.exec(command, [], options); } -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } +module.exports = { + ExitError, + execute +}; - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - var rangeTmp +/***/ }), +/* 82 */ +/***/ (function(__unusedmodule, exports) { - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } +"use strict"; - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * 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; +//# sourceMappingURL=utils.js.map - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +/***/ }), +/* 83 */, +/* 84 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const glob = __webpack_require__(281); +const path = __webpack_require__(622); +const { stat } = __webpack_require__(747); +const { dirname } = __webpack_require__(622); +const { promisify } = __webpack_require__(669); +const stats = promisify(stat); +const { logger } = __webpack_require__(79); + +async function findFilesToUpload(searchPath, globOptions) { + const globber = await glob.create( + searchPath, + globOptions || getDefaultGlobOptions() + ); + const filesToUpload = await getSearchResults(globber); + + return { + filesToUpload, + rootDirectory: getRootDirectory(globber, filesToUpload) + }; } -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } +/** + * If multiple paths are specific, the least common ancestor (LCA) of the search paths is used as + * the delimiter to control the directory structure for the artifact. This function returns the LCA + * when given an array of search paths + * + * Example 1: The patterns `/foo/` and `/bar/` returns `/` + * + * Example 2: The patterns `~/foo/bar/*` and `~/foo/voo/two/*` and `~/foo/mo/` returns `~/foo` + */ +function getMultiPathLCA(searchPaths) { + if (searchPaths.length < 2) { + throw new Error("At least two search paths must be provided"); } - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } + const commonPaths = []; + let smallestPathLength = Number.MAX_SAFE_INTEGER; - if (range instanceof Comparator) { - return new Range(range.value, options) + const splitPaths = searchPaths + .map(searchPath => path.normalize(searchPath).split(path.sep)) + .reduce((acc, splitSearchPath) => { + smallestPathLength = Math.min(smallestPathLength, splitSearchPath.length); + acc.push(splitSearchPath); + return acc; + }, []); + + if (searchPaths[0].startsWith(path.sep)) { + commonPaths.push(path.sep); } - if (!(this instanceof Range)) { - return new Range(range, options) + let splitIndex = 0; + function isPathTheSame() { + const compare = splitPaths[0][splitIndex]; + for (let i = 1; i < splitPaths.length; i++) { + if (compare !== splitPaths[i][splitIndex]) { + return false; + } + } + return true; } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + while (splitIndex < smallestPathLength) { + if (!isPathTheSame()) { + break; + } + commonPaths.push(splitPaths[0][splitIndex]); + splitIndex++; + } + return path.join(...commonPaths); +} - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) +async function getSearchResults(globber) { + const rawSearchResults = await globber.glob(); - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) + const searchResults = []; + for (const searchResult of rawSearchResults) { + const fileStats = await stats(searchResult); + if (!fileStats.isDirectory()) { + searchResults.push(searchResult); + if ( + searchResults + .map(item => item.toLowerCase()) + .find(item => item === searchResult.toLowerCase()) + ) { + logger.info( + `Uploads are case insensitive: ${searchResult} was detected that it will be overwritten by another file with the same path` + ); + } + } } - - this.format() + return searchResults; } -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range +function getRootDirectory(globber, searchResults) { + const searchPaths = globber.getSearchPaths(); + if (searchPaths.length > 1) { + logger.info( + `Multiple search paths detected. Calculating the least common ancestor of all paths` + ); + const lcaSearchPath = getMultiPathLCA(searchPaths); + logger.info( + `The least common ancestor is ${lcaSearchPath}. This will be the root directory of the artifact` + ); + return lcaSearchPath; + } + return searchResults.length === 1 && searchPaths[0] === searchResults[0] + ? dirname(searchResults[0]) + : searchPaths[0]; } -Range.prototype.toString = function () { - return this.range +function getDefaultGlobOptions() { + return { + followSymbolicLinks: true, + implicitDescendants: true, + omitBrokenSymbolicLinks: true + }; } -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) +module.exports = { + findFilesToUpload +}; - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) +/***/ }), +/* 85 */, +/* 86 */, +/* 87 */ +/***/ (function(module) { - // normalize spaces - range = range.split(/\s+/).join(' ') +module.exports = require("os"); - // At this point, the range is completely trimmed and - // ready to be split into comparators. +/***/ }), +/* 88 */, +/* 89 */, +/* 90 */, +/* 91 */, +/* 92 */, +/* 93 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) +var Stream = __webpack_require__(413).Stream - return set -} +module.exports = legacy -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} + Stream.call(this); -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} + var self = this; -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret + options = options || {}; - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret + if (this.encoding) this.setEncoding(this.encoding); - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' + + if (this.start > this.end) { + throw new Error('start must be <= end'); } + + this.pos = this.start; } - debug('caret return', ret) - return ret - }) -} + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - if (gtlt === '=' && anyX) { - gtlt = '' + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } + if (this.start < 0) { + throw new Error('start must be >= zero'); } - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + this.pos = this.start; } - debug('xRange return', ret) - - return ret - }) -} + this.busy = false; + this._queue = []; -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } } - - return (from + ' ' + to).trim() } -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} +/***/ }), +/* 94 */, +/* 95 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } +"use strict"; - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const copySync = __webpack_require__(43).copySync +const removeSync = __webpack_require__(723).removeSync +const mkdirpSync = __webpack_require__(727).mkdirpSync +const stat = __webpack_require__(127) - // Version has a -pre, but it's not one of the ones we like. - return false - } +function moveSync (src, dest, opts) { + opts = opts || {} + const overwrite = opts.overwrite || opts.clobber || false - return true + const { srcStat } = stat.checkPathsSync(src, dest, 'move') + stat.checkParentPathsSync(src, srcStat, dest, 'move') + mkdirpSync(path.dirname(dest)) + return doRename(src, dest, overwrite) } -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false +function doRename (src, dest, overwrite) { + if (overwrite) { + removeSync(dest) + return rename(src, dest, overwrite) } - return range.test(version) + if (fs.existsSync(dest)) throw new Error('dest already exists.') + return rename(src, dest, overwrite) } -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null +function rename (src, dest, overwrite) { try { - var rangeObj = new Range(range, options) - } catch (er) { - return null + fs.renameSync(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') throw err + return moveAcrossDevice(src, dest, overwrite) } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max } -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null +function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min + copySync(src, dest, opts) + return removeSync(src) } -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) +module.exports = moveSync - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } +/***/ }), +/* 96 */, +/* 97 */, +/* 98 */, +/* 99 */, +/* 100 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +"use strict"; - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - if (minver && range.test(minver)) { - return minver - } +var Type = __webpack_require__(945); - return null -} +var _hasOwnProperty = Object.prototype.hasOwnProperty; -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } } -} -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) + return true; } -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) +function constructYamlSet(data) { + return data !== null ? data : {}; } -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +/***/ }), +/* 101 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var high = null - var low = null +const { readDefinitionFile } = __webpack_require__(799); +const { treatProject } = __webpack_require__(443); +const { validateNode } = __webpack_require__(492); - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) +/** + * It will return back the definition tree plus dependencies as an object. + * + * @param {string} file - The definition file. It can be a URL or a in the filesystem. + * @param {Object} urlPlaceHolders the url place holders to replace url. This is needed in case either the definition file or the dependencies file are loaded from a URL + */ +async function getTree(file, urlPlaceHolders = {}) { + const definition = await readDefinitionFile(file, urlPlaceHolders); + return dependencyListToTree(definition.dependencies, definition); +} - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } +/** + * It will return back the definition tree plus dependencies as an object for a particular project. + * + * @param {string} file - The definition file. It can be a URL or a in the filesystem. + * @param {string} project - The project name to look for. + * @param {Object} urlPlaceHolders the url place holders to replace url. This is needed in case either the definition file or the dependencies file are loaded from a URL + */ +async function getTreeForProject(file, project, urlPlaceHolders = {}) { + return lookForProject( + await getTree(file, urlPlaceHolders), + project, + undefined + ); +} - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } +/** + * It returns the leaf from the tree corresponding to the project name + * @param {Object} tree + * @param {String} project the project name + */ +function lookForProject(tree, project) { + if (tree && tree.length > 0) { + const leaf = tree.find(leaf => project === leaf.project); + if (leaf) { + delete leaf.mapping; + } + return leaf + ? leaf + : tree + .map(leaf => lookForProject(leaf.children, project)) + .find(child => child); + } else { + return undefined; } - return true } -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} +/** + * it treats the dependenciy list together with the build configuration to compose the build tree + * @param {Object} dependencyList the dependency list + * @param {Object} buildConfiguration the build configuration directly read from the yaml file + */ +function dependencyListToTree(dependencyList, buildConfiguration) { + const map = dependencyList.reduce((map, dependency, i) => { + map[dependency.project] = { index: i, node: undefined }; + dependency.children = []; + dependency.parents = []; + return map; + }, {}); -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) + return dependencyList.reduce((roots, node) => { + validateNode(node); + map[node.project].node = { + ...node, + repo: { + group: node.project.split("/")[0], + name: node.project.split("/")[1] + }, + ...treatProject(node.project, buildConfiguration) + }; + if (node.dependencies && node.dependencies.length > 0) { + node.dependencies.forEach(dependency => { + dependencyList[map[dependency.project].index].children.push({ + ...map[node.project].node, + mapping: dependency.mapping + }); + node.parents.push({ + ...map[dependency.project].node, + mapping: dependency.mapping + }); + }); + } else { + roots.push(map[node.project].node); + } + return roots; + }, []); } -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } +module.exports = { getTree, getTreeForProject, dependencyListToTree }; - if (typeof version !== 'string') { - return null - } - var match = version.match(re[COERCE]) +/***/ }), +/* 102 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (match == null) { - return null - } +"use strict"; - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) +// For internal use, subject to change. +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__webpack_require__(747)); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +function issueCommand(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, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); } - +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map /***/ }), -/* 49 */ +/* 103 */, +/* 104 */, +/* 105 */, +/* 106 */, +/* 107 */, +/* 108 */, +/* 109 */, +/* 110 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -const os = __webpack_require__(87); -const execa = __webpack_require__(955); - -// Reference: https://www.gaijin.at/en/lstwinver.php -const names = new Map([ - ['10.0', '10'], - ['6.3', '8.1'], - ['6.2', '8'], - ['6.1', '7'], - ['6.0', 'Vista'], - ['5.2', 'Server 2003'], - ['5.1', 'XP'], - ['5.0', '2000'], - ['4.9', 'ME'], - ['4.1', '98'], - ['4.0', '95'] -]); - -const windowsRelease = release => { - const version = /\d+\.\d/.exec(release || os.release()); - if (release && !version) { - throw new Error('`release` argument doesn\'t match `n.n`'); - } +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const mkdirsSync = __webpack_require__(727).mkdirsSync +const utimesMillisSync = __webpack_require__(916).utimesMillisSync +const stat = __webpack_require__(127) - const ver = (version || [])[0]; +function copySync (src, dest, opts) { + if (typeof opts === 'function') { + opts = { filter: opts } + } - // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime. - // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version - // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx - // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead. - // If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name. - if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { - let stdout; - try { - stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; - } catch (_) { - stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || ''; - } + opts = opts || {} + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - const year = (stdout.match(/2008|2012|2016|2019/) || [])[0]; + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) + } - if (year) { - return `Server ${year}`; - } - } + const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy') + stat.checkParentPathsSync(src, srcStat, dest, 'copy') + return handleFilterAndCopy(destStat, src, dest, opts) +} - return names.get(ver); -}; +function handleFilterAndCopy (destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return + const destParent = path.dirname(dest) + if (!fs.existsSync(destParent)) mkdirsSync(destParent) + return startCopy(destStat, src, dest, opts) +} -module.exports = windowsRelease; +function startCopy (destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return + return getStats(destStat, src, dest, opts) +} +function getStats (destStat, src, dest, opts) { + const statSync = opts.dereference ? fs.statSync : fs.lstatSync + const srcStat = statSync(src) -/***/ }), -/* 50 */, -/* 51 */, -/* 52 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) +} -const noTreatment = __webpack_require__(981); -const mavenTreatment = __webpack_require__(121); +function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + return mayCopyFile(srcStat, src, dest, opts) +} -function treatCommand(command) { - let libraryToExecute = noTreatment; - if (command.match(/.*mvn .*/)) { - libraryToExecute = mavenTreatment; +function mayCopyFile (srcStat, src, dest, opts) { + if (opts.overwrite) { + fs.unlinkSync(dest) + return copyFile(srcStat, src, dest, opts) + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) } - return libraryToExecute.treat(command); } -module.exports = { - treatCommand -}; - +function copyFile (srcStat, src, dest, opts) { + fs.copyFileSync(src, dest) + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) + return setDestMode(dest, srcStat.mode) +} -/***/ }), -/* 53 */, -/* 54 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +function handleTimestamps (srcMode, src, dest) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) + return setDestTimestamps(src, dest) +} -"use strict"; -// Adapted from https://github.com/sindresorhus/make-dir -// Copyright (c) Sindre Sorhus (sindresorhus.com) -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} -const fs = __webpack_require__(869) -const path = __webpack_require__(622) -const atLeastNode = __webpack_require__(159) +function makeFileWritable (dest, srcMode) { + return setDestMode(dest, srcMode | 0o200) +} -const useNativeRecursiveOption = atLeastNode('10.12.0') +function setDestMode (dest, srcMode) { + return fs.chmodSync(dest, srcMode) +} -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -const checkPath = pth => { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) +function setDestTimestamps (src, dest) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = fs.statSync(src) + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) +} - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`) - error.code = 'EINVAL' - throw error - } +function onDir (srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) + if (destStat && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } + return copyDir(src, dest, opts) } -const processOptions = options => { - const defaults = { mode: 0o777 } - if (typeof options === 'number') options = { mode: options } - return { ...defaults, ...options } +function mkDirAndCopy (srcMode, src, dest, opts) { + fs.mkdirSync(dest) + copyDir(src, dest, opts) + return setDestMode(dest, srcMode) } -const permissionError = pth => { - // This replicates the exception of `fs.mkdir` with native the - // `recusive` option when run on an invalid drive under Windows. - const error = new Error(`operation not permitted, mkdir '${pth}'`) - error.code = 'EPERM' - error.errno = -4048 - error.path = pth - error.syscall = 'mkdir' - return error +function copyDir (src, dest, opts) { + fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) } -module.exports.makeDir = async (input, options) => { - checkPath(input) - options = processOptions(options) - - if (useNativeRecursiveOption) { - const pth = path.resolve(input) +function copyDirItem (item, src, dest, opts) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy') + return startCopy(destStat, srcItem, destItem, opts) +} - return fs.mkdir(pth, { - mode: options.mode, - recursive: true - }) +function onLink (destStat, src, dest, opts) { + let resolvedSrc = fs.readlinkSync(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } - const make = async pth => { + if (!destStat) { + return fs.symlinkSync(resolvedSrc, dest) + } else { + let resolvedDest try { - await fs.mkdir(pth, options.mode) - } catch (error) { - if (error.code === 'EPERM') { - throw error - } - - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth) - } - - if (error.message.includes('null bytes')) { - throw error - } - - await make(path.dirname(pth)) - return make(pth) - } + resolvedDest = fs.readlinkSync(dest) + } catch (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) + throw err + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } - try { - const stats = await fs.stat(pth) - if (!stats.isDirectory()) { - // This error is never exposed to the user - // it is caught below, and the original error is thrown - throw new Error('The path is not a directory') - } - } catch { - throw error - } + // prevent copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } + return copyLink(resolvedSrc, dest) } +} - return make(path.resolve(input)) +function copyLink (resolvedSrc, dest) { + fs.unlinkSync(dest) + return fs.symlinkSync(resolvedSrc, dest) } -module.exports.makeDirSync = (input, options) => { - checkPath(input) - options = processOptions(options) +module.exports = copySync - if (useNativeRecursiveOption) { - const pth = path.resolve(input) - return fs.mkdirSync(pth, { - mode: options.mode, - recursive: true - }) - } +/***/ }), +/* 111 */, +/* 112 */, +/* 113 */, +/* 114 */, +/* 115 */, +/* 116 */, +/* 117 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - const make = pth => { - try { - fs.mkdirSync(pth, options.mode) - } catch (error) { - if (error.code === 'EPERM') { - throw error - } +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth) - } +var pathModule = __webpack_require__(622); +var isWindows = process.platform === 'win32'; +var fs = __webpack_require__(747); - if (error.message.includes('null bytes')) { - throw error - } +// JavaScript implementation of realpath, ported from node pre-v6 - make(path.dirname(pth)) - return make(pth) - } +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - try { - if (!fs.statSync(pth).isDirectory()) { - // This error is never exposed to the user - // it is caught below, and the original error is thrown - throw new Error('The path is not a directory') - } - } catch { - throw error +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); } } } +} - return make(path.resolve(input)) +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); } +var normalize = pathModule.normalize; -/***/ }), -/* 55 */, -/* 56 */, -/* 57 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -const { - clone, - doesBranchExist, - merge: gitMerge, - hasPullRequest, - getForkedProject -} = __webpack_require__(484); -const { logger } = __webpack_require__(79); -const { saveCheckoutInfo } = __webpack_require__(195); - -async function checkoutDependencies( - context, - dependencies, - currentTargetBranch -) { - const result = {}; - for (const dependencyKey of Object.keys(dependencies)) { - result[dependencyKey] = await checkoutProject( - context, - dependencyKey, - dependencies[dependencyKey], - currentTargetBranch - ); - } - return result; -} - -async function checkoutProject( - context, - project, - dependencyInformation, - currentTargetBranch -) { - const dir = getDir(context.config.rootFolder, project); - const checkoutInfo = await getCheckoutInfo( - context, - dependencyInformation.group, - project, - currentTargetBranch, - dependencyInformation.mapping - ); - if (checkoutInfo == undefined) { - const msg = `Trying to checking out ${project} into '${dir}'. It does not exist.`; - logger.error(msg); - throw new Error(msg); - } - - if (checkoutInfo.merge) { - logger.info( - `Merging ${context.config.github.serverUrl}/${dependencyInformation.group}/${project}:${checkoutInfo.targetBranch} into ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}` - ); - try { - await clone( - `${context.config.github.serverUrl}/${dependencyInformation.group}/${project}`, - dir, - checkoutInfo.targetBranch - ); - } catch (err) { - logger.error( - `Error checking out (before merging) ${context.config.github.serverUrl}/${dependencyInformation.group}/${project}:${context.config.github.targetBranch}` - ); - throw err; - } - try { - await gitMerge( - dir, - checkoutInfo.group, - checkoutInfo.project, - checkoutInfo.branch - ); - } catch (err) { - logger.error( - `Error merging ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}. Please manually merge it and relaunch.` - ); - throw err; - } - } else { - try { - logger.info( - `Checking out '${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}' into '${dir}'` - ); - await clone( - `${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}`, - dir, - checkoutInfo.branch - ); - } catch (err) { - logger.error( - `Error checking out ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}.` - ); - throw err; - } - } - saveCheckoutInfo(context, project, checkoutInfo); - return checkoutInfo; +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; } -async function getCheckoutInfo( - context, - targetGroup, - targetProject, - currentTargetBranch, - mapping -) { - const sourceGroup = context.config.github.sourceGroup; - const sourceBranch = context.config.github.sourceBranch; - const targetBranch = - mapping && mapping.source === currentTargetBranch - ? mapping.target - : currentTargetBranch; - const forkedProjectName = await getForkedProjectName( - context.octokit, - targetGroup, - targetProject, - sourceGroup - ); - logger.info( - `Getting checkout Info for ${targetProject}. sourceProject: ${forkedProjectName} sourceGroup: ${sourceGroup}. sourceBranch: ${sourceBranch}. targetGroup: ${targetGroup}. targetBranch: ${targetBranch}. Mapping: ${ - mapping - ? "source:" + mapping.source + " target:" + mapping.target - : "not defined" - }` - ); - return (await doesBranchExist( - context.octokit, - sourceGroup, - forkedProjectName, - sourceBranch - )) - ? { - project: forkedProjectName, - group: sourceGroup, - branch: sourceBranch, - targetGroup, - targetBranch, - merge: await hasPullRequest( - context.octokit, - targetGroup, - targetProject, - sourceBranch, - context.config.github.author - ) - } - : (await doesBranchExist( - context.octokit, - targetGroup, - targetProject, - sourceBranch - )) - ? { - project: targetProject, - group: targetGroup, - branch: sourceBranch, - targetGroup, - targetBranch, - merge: await hasPullRequest( - context.octokit, - targetGroup, - targetProject, - sourceBranch, - context.config.github.author - ) - } - : (await doesBranchExist( - context.octokit, - targetGroup, - targetProject, - targetBranch - )) - ? { - project: targetProject, - group: targetGroup, - branch: targetBranch, - targetGroup, - targetBranch, - merge: false - } - : undefined; +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; } -function getDir(rootFolder, project) { - const folder = - rootFolder !== undefined && rootFolder !== "" ? rootFolder : "."; - return `${folder}/${project.replace(/ |-/g, "_")}`; -} +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); -async function getForkedProjectName(octokit, owner, project, wantedOwner) { - if (owner !== wantedOwner) { - const forkedProject = await getForkedProject( - octokit, - owner, - project, - wantedOwner - ); - return !forkedProject || !forkedProject.name ? project : forkedProject.name; - } else { - return project; + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; } -} -module.exports = { - checkoutDependencies, - checkoutProject, - getCheckoutInfo, - getDir -}; + var original = p, + seenLinks = {}, + knownHard = {}; + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -/***/ }), -/* 58 */, -/* 59 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + start(); -"use strict"; + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } -var util = __webpack_require__(669); + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; -// Constants -var c = __webpack_require__(45); + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } -var $$ = __webpack_require__(255); -var HelpFormatter = __webpack_require__(532); + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } -/** - * new RawDescriptionHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) - * - * Help message formatter which adds default values to argument help. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ - -function ArgumentDefaultsHelpFormatter(options) { - HelpFormatter.call(this, options); -} - -util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); - -ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { - var help = action.help; - if (action.help.indexOf('%(defaultValue)s') === -1) { - if (action.defaultValue !== c.SUPPRESS) { - var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ]; - if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { - help += ' (default: %(defaultValue)s)'; + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; } - } - return help; -}; - -module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; - -/** - * new RawDescriptionHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) - * - * Help message formatter which retains any formatting in descriptions. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ -function RawDescriptionHelpFormatter(options) { - HelpFormatter.call(this, options); -} + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } -util.inherits(RawDescriptionHelpFormatter, HelpFormatter); + if (cache) cache[original] = p; -RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { - var lines = text.split('\n'); - lines = lines.map(function (line) { - return $$.trimEnd(indent + line); - }); - return lines.join('\n'); + return p; }; -module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; - -/** - * new RawTextHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) - * - * Help message formatter which retains formatting of all help text. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ -function RawTextHelpFormatter(options) { - RawDescriptionHelpFormatter.call(this, options); -} -util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } -RawTextHelpFormatter.prototype._splitLines = function (text) { - return text.split('\n'); -}; + // make p is absolute + p = pathModule.resolve(p); -module.exports.RawTextHelpFormatter = RawTextHelpFormatter; + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + var original = p, + seenLinks = {}, + knownHard = {}; -/***/ }), -/* 60 */, -/* 61 */, -/* 62 */, -/* 63 */, -/* 64 */, -/* 65 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -"use strict"; -/** internal - * class ArgumentGroup - * - * Group arguments. - * By default, ArgumentParser groups command-line arguments - * into “positional arguments” and “optional arguments” - * when displaying help messages. When there is a better - * conceptual grouping of arguments than this default one, - * appropriate groups can be created using the addArgumentGroup() method - * - * This class inherited from [[ArgumentContainer]] - **/ + start(); + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -var util = __webpack_require__(669); + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } -var ActionContainer = __webpack_require__(614); + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; -/** - * new ArgumentGroup(container, options) - * - container (object): main container - * - options (object): hash of group options - * - * #### options - * - **prefixChars** group name prefix - * - **argumentDefault** default argument value - * - **title** group title - * - **description** group description - * - **/ -var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } - options = options || {}; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } - // add any missing keyword arguments by checking the container - options.conflictHandler = (options.conflictHandler || container.conflictHandler); - options.prefixChars = (options.prefixChars || container.prefixChars); - options.argumentDefault = (options.argumentDefault || container.argumentDefault); + return fs.lstat(base, gotStat); + } - ActionContainer.call(this, options); + function gotStat(err, stat) { + if (err) return cb(err); - // group attributes - this.title = options.title; - this._groupActions = []; + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } - // share most attributes with the container - this._container = container; - this._registries = container._registries; - this._actions = container._actions; - this._optionStringActions = container._optionStringActions; - this._defaults = container._defaults; - this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; - this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; -}; -util.inherits(ArgumentGroup, ActionContainer); + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } -ArgumentGroup.prototype._addAction = function (action) { - // Parent add action - action = ActionContainer.prototype._addAction.call(this, action); - this._groupActions.push(action); - return action; -}; + function gotTarget(err, target, base) { + if (err) return cb(err); + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } -ArgumentGroup.prototype._removeAction = function (action) { - // Parent remove action - ActionContainer.prototype._removeAction.call(this, action); - var actionIndex = this._groupActions.indexOf(action); - if (actionIndex >= 0) { - this._groupActions.splice(actionIndex, 1); + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); } }; - /***/ }), -/* 66 */, -/* 67 */, -/* 68 */, -/* 69 */, -/* 70 */, -/* 71 */, -/* 72 */, -/* 73 */, -/* 74 */, -/* 75 */, -/* 76 */, -/* 77 */, -/* 78 */, -/* 79 */ +/* 118 */ /***/ (function(module, __unusedexports, __webpack_require__) { -const util = __webpack_require__(669); -const process = __webpack_require__(765); - -class ClientError extends Error {} - -class TimeoutError extends Error {} - -function log(prefix, obj) { - if (process.env.NODE_ENV !== "test") { - const str = obj.map(o => (typeof o === "object" ? inspect(o) : o)); - if (prefix) { - console.log.apply(console, [prefix, ...str]); - } else { - console.log.apply(console, str); - } - } -} +"use strict"; -const logger = { - level: "info", +const os = __webpack_require__(87); - trace: (...str) => { - if (logger.level === "trace") { - log("[TRACE]", str); - } - }, +const nameMap = new Map([ + [20, ['Big Sur', '11']], + [19, ['Catalina', '10.15']], + [18, ['Mojave', '10.14']], + [17, ['High Sierra', '10.13']], + [16, ['Sierra', '10.12']], + [15, ['El Capitan', '10.11']], + [14, ['Yosemite', '10.10']], + [13, ['Mavericks', '10.9']], + [12, ['Mountain Lion', '10.8']], + [11, ['Lion', '10.7']], + [10, ['Snow Leopard', '10.6']], + [9, ['Leopard', '10.5']], + [8, ['Tiger', '10.4']], + [7, ['Panther', '10.3']], + [6, ['Jaguar', '10.2']], + [5, ['Puma', '10.1']] +]); - debug: (...str) => { - if (logger.level === "trace" || logger.level === "debug") { - log("DEBUG", str); - } - }, +const macosRelease = release => { + release = Number((release || os.release()).split('.')[0]); - info: (...str) => log("[INFO] ", str), - warn: (...str) => log("[WARN] ", str), + const [name, version] = nameMap.get(release); - error: (...str) => { - if (str.length === 1) { - if (str[0] instanceof Error) { - if (logger.level === "trace" || logger.level === "debug") { - log(null, [str[0].stack || str[0]]); - } else { - log("[ERROR] ", [str[0].message || str[0]]); - } - } - } else { - log("[ERROR] ", str); - } - } + return { + name, + version + }; }; -function inspect(obj) { - return util.inspect(obj, false, null, true); -} - -module.exports = { - ClientError, - TimeoutError, - logger -}; +module.exports = macosRelease; +// TODO: remove this in the next major version +module.exports.default = macosRelease; /***/ }), -/* 80 */, -/* 81 */, -/* 82 */ +/* 119 */, +/* 120 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - - -var Type = __webpack_require__(945); +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day +module.exports = glob -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute +var fs = __webpack_require__(747) +var rp = __webpack_require__(302) +var minimatch = __webpack_require__(571) +var Minimatch = minimatch.Minimatch +var inherits = __webpack_require__(689) +var EE = __webpack_require__(759).EventEmitter +var path = __webpack_require__(622) +var assert = __webpack_require__(357) +var isAbsolute = __webpack_require__(681) +var globSync = __webpack_require__(245) +var common = __webpack_require__(644) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __webpack_require__(634) +var util = __webpack_require__(669) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} +var once = __webpack_require__(969) -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } - if (match === null) throw new Error('Date resolve error'); + return new Glob(pattern, options, cb) +} - // match: [1] year [2] month [3] day +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); +// old api surface +glob.glob = glob - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin } - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] } + return origin +} - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } + var g = new Glob(pattern, options) + var set = g.minimatch.set - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + if (!pattern) + return false - if (delta) date.setTime(date.getTime() - delta); + if (set.length > 1) + return true - return date; -} + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); + return false } -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } -/***/ }), -/* 83 */, -/* 84 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) -const glob = __webpack_require__(281); -const path = __webpack_require__(622); -const { stat } = __webpack_require__(747); -const { dirname } = __webpack_require__(622); -const { promisify } = __webpack_require__(669); -const stats = promisify(stat); -const { logger } = __webpack_require__(79); + setopts(this, pattern, options) + this._didRealPath = false -async function findFilesToUpload(searchPath, globOptions) { - const globber = await glob.create( - searchPath, - globOptions || getDefaultGlobOptions() - ); - const filesToUpload = await getSearchResults(globber); + // process each pattern in the minimatch set + var n = this.minimatch.set.length - return { - filesToUpload, - rootDirectory: getRootDirectory(globber, filesToUpload) - }; -} + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) -/** - * If multiple paths are specific, the least common ancestor (LCA) of the search paths is used as - * the delimiter to control the directory structure for the artifact. This function returns the LCA - * when given an array of search paths - * - * Example 1: The patterns `/foo/` and `/bar/` returns `/` - * - * Example 2: The patterns `~/foo/bar/*` and `~/foo/voo/two/*` and `~/foo/mo/` returns `~/foo` - */ -function getMultiPathLCA(searchPaths) { - if (searchPaths.length < 2) { - throw new Error("At least two search paths must be provided"); + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) } - const commonPaths = []; - let smallestPathLength = Number.MAX_SAFE_INTEGER; + var self = this + this._processing = 0 - const splitPaths = searchPaths - .map(searchPath => path.normalize(searchPath).split(path.sep)) - .reduce((acc, splitSearchPath) => { - smallestPathLength = Math.min(smallestPathLength, splitSearchPath.length); - acc.push(splitSearchPath); - return acc; - }, []); + this._emitQueue = [] + this._processQueue = [] + this.paused = false - if (searchPaths[0].startsWith(path.sep)) { - commonPaths.push(path.sep); - } + if (this.noprocess) + return this - let splitIndex = 0; - function isPathTheSame() { - const compare = splitPaths[0][splitIndex]; - for (let i = 1; i < splitPaths.length; i++) { - if (compare !== splitPaths[i][splitIndex]) { - return false; - } - } - return true; - } + if (n === 0) + return done() - while (splitIndex < smallestPathLength) { - if (!isPathTheSame()) { - break; - } - commonPaths.push(splitPaths[0][splitIndex]); - splitIndex++; + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) } - return path.join(...commonPaths); -} - -async function getSearchResults(globber) { - const rawSearchResults = await globber.glob(); + sync = false - const searchResults = []; - for (const searchResult of rawSearchResults) { - const fileStats = await stats(searchResult); - if (!fileStats.isDirectory()) { - searchResults.push(searchResult); - if ( - searchResults - .map(item => item.toLowerCase()) - .find(item => item === searchResult.toLowerCase()) - ) { - logger.info( - `Uploads are case insensitive: ${searchResult} was detected that it will be overwritten by another file with the same path` - ); + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() } } } - return searchResults; -} - -function getRootDirectory(globber, searchResults) { - const searchPaths = globber.getSearchPaths(); - if (searchPaths.length > 1) { - logger.info( - `Multiple search paths detected. Calculating the least common ancestor of all paths` - ); - const lcaSearchPath = getMultiPathLCA(searchPaths); - logger.info( - `The least common ancestor is ${lcaSearchPath}. This will be the root directory of the artifact` - ); - return lcaSearchPath; - } - return searchResults.length === 1 && searchPaths[0] === searchResults[0] - ? dirname(searchResults[0]) - : searchPaths[0]; -} - -function getDefaultGlobOptions() { - return { - followSymbolicLinks: true, - implicitDescendants: true, - omitBrokenSymbolicLinks: true - }; } -module.exports = { - findFilesToUpload -}; +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + if (this.realpath && !this._didRealpath) + return this._realpath() -/***/ }), -/* 85 */, -/* 86 */, -/* 87 */ -/***/ (function(module) { + common.finish(this) + this.emit('end', this.found) +} -module.exports = require("os"); +Glob.prototype._realpath = function () { + if (this._didRealpath) + return -/***/ }), -/* 88 */, -/* 89 */, -/* 90 */, -/* 91 */, -/* 92 */, -/* 93 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + this._didRealpath = true -var Stream = __webpack_require__(413).Stream + var n = this.matches.length + if (n === 0) + return this._finish() -module.exports = legacy + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream + function next () { + if (--n === 0) + self._finish() } +} - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() - Stream.call(this); + var found = Object.keys(matchset) + var self = this + var n = found.length - var self = this; + if (n === 0) + return cb() - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} - options = options || {}; +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} - if (this.encoding) this.setEncoding(this.encoding); +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} - if (this.start > this.end) { - throw new Error('start must be <= end'); +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) + } } +} - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + if (this.aborted) + return - this.pos = this.start; - } + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } - this.busy = false; - this._queue = []; + //console.error('PROCESS %d', this._processing, pattern) - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ } -} + // now n is the index of the first one that is *not* a string. + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return -/***/ }), -/* 94 */, -/* 95 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break -"use strict"; + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + var remain = pattern.slice(n) -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const copySync = __webpack_require__(43).copySync -const removeSync = __webpack_require__(723).removeSync -const mkdirpSync = __webpack_require__(727).mkdirpSync -const stat = __webpack_require__(127) + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix -function moveSync (src, dest, opts) { - opts = opts || {} - const overwrite = opts.overwrite || opts.clobber || false + var abs = this._makeAbs(read) - const { srcStat } = stat.checkPathsSync(src, dest, 'move') - stat.checkParentPathsSync(src, srcStat, dest, 'move') - mkdirpSync(path.dirname(dest)) - return doRename(src, dest, overwrite) -} + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() -function doRename (src, dest, overwrite) { - if (overwrite) { - removeSync(dest) - return rename(src, dest, overwrite) - } - if (fs.existsSync(dest)) throw new Error('dest already exists.') - return rename(src, dest, overwrite) + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } -function rename (src, dest, overwrite) { - try { - fs.renameSync(src, dest) - } catch (err) { - if (err.code !== 'EXDEV') throw err - return moveAcrossDevice(src, dest, overwrite) - } +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) } -function moveAcrossDevice (src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - } - copySync(src, dest, opts) - return removeSync(src) -} +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { -module.exports = moveSync + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' -/***/ }), -/* 96 */, -/* 97 */, -/* 98 */, -/* 99 */, -/* 100 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } -"use strict"; + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() -var Type = __webpack_require__(945); + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. -var _hasOwnProperty = Object.prototype.hasOwnProperty; + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) -function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) } + // This was the last one, and no stats were needed + return cb() } - return true; + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() } -function constructYamlSet(data) { - return data !== null ? data : {}; -} +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); + if (isIgnored(this, e)) + return + if (this.paused) { + this._emitQueue.push([index, e]) + return + } -/***/ }), -/* 101 */, -/* 102 */, -/* 103 */, -/* 104 */, -/* 105 */, -/* 106 */, -/* 107 */, -/* 108 */, -/* 109 */, -/* 110 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var abs = isAbsolute(e) ? e : this._makeAbs(e) -"use strict"; + if (this.mark) + e = this._mark(e) + if (this.absolute) + e = abs -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const mkdirsSync = __webpack_require__(727).mkdirsSync -const utimesMillisSync = __webpack_require__(916).utimesMillisSync -const stat = __webpack_require__(127) + if (this.matches[index][e]) + return -function copySync (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts } + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } - opts = opts || {} - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + this.matches[index][e] = true - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) - } + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) - const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy') - stat.checkParentPathsSync(src, srcStat, dest, 'copy') - return handleFilterAndCopy(destStat, src, dest, opts) + this.emit('match', e) } -function handleFilterAndCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path.dirname(dest) - if (!fs.existsSync(destParent)) mkdirsSync(destParent) - return startCopy(destStat, src, dest, opts) -} +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return -function startCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - return getStats(destStat, src, dest, opts) -} + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs.statSync : fs.lstatSync - const srcStat = statSync(src) + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) -} + if (lstatcb) + fs.lstat(abs, lstatcb) -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs.unlinkSync(dest) - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) } } -function copyFile (srcStat, src, dest, opts) { - fs.copyFileSync(src, dest) - if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) - return setDestMode(dest, srcStat.mode) -} +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return -function handleTimestamps (srcMode, src, dest) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) - return setDestTimestamps(src, dest) -} + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() -function setDestMode (dest, srcMode) { - return fs.chmodSync(dest, srcMode) -} + if (Array.isArray(c)) + return cb(null, c) + } -function setDestTimestamps (src, dest) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - const updatedSrcStat = fs.statSync(src) - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) } -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) - if (destStat && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) } - return copyDir(src, dest, opts) } -function mkDirAndCopy (srcMode, src, dest, opts) { - fs.mkdirSync(dest) - copyDir(src, dest, opts) - return setDestMode(dest, srcMode) -} +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return -function copyDir (src, dest, opts) { - fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) -} + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } -function copyDirItem (item, src, dest, opts) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy') - return startCopy(destStat, srcItem, destItem, opts) + this.cache[abs] = entries + return cb(null, entries) } -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs.readlinkSync(src) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return - if (!destStat) { - return fs.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest - try { - resolvedDest = fs.readlinkSync(dest) - } catch (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) - throw err - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break - // prevent copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - return copyLink(resolvedSrc, dest) + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break } + + return cb() } -function copyLink (resolvedSrc, dest) { - fs.unlinkSync(dest) - return fs.symlinkSync(resolvedSrc, dest) +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) } -module.exports = copySync +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) -/***/ }), -/* 111 */, -/* 112 */, -/* 113 */, -/* 114 */, -/* 115 */, -/* 116 */, -/* 117 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -var pathModule = __webpack_require__(622); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(747); + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) -// JavaScript implementation of realpath, ported from node pre-v6 + var isSym = this.symlinks[abs] + var len = entries.length -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue - return callback; + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) } - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } - } + cb() } -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) } +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -var normalize = pathModule.normalize; - -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} + //console.error('ps2', prefix, exists) -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} + if (!this.matches[index]) + this.matches[index] = Object.create(null) -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } } - var original = p, - seenLinks = {}, - knownHard = {}; + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} - start(); +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + if (f.length > this.maxLength) + return cb() - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; + if (Array.isArray(c)) + c = 'DIR' - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } - - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } - - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + if (needDir && c === 'FILE') + return cb() - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. } - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) } - - return fs.lstat(base, gotStat); } - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) } - fs.stat(base, function(err) { - if (err) return cb(err); - - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); } +} - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() } -}; - - -/***/ }), -/* 118 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const os = __webpack_require__(87); -const nameMap = new Map([ - [20, ['Big Sur', '11']], - [19, ['Catalina', '10.15']], - [18, ['Mojave', '10.14']], - [17, ['High Sierra', '10.13']], - [16, ['Sierra', '10.12']], - [15, ['El Capitan', '10.11']], - [14, ['Yosemite', '10.10']], - [13, ['Mavericks', '10.9']], - [12, ['Mountain Lion', '10.8']], - [11, ['Lion', '10.7']], - [10, ['Snow Leopard', '10.6']], - [9, ['Leopard', '10.5']], - [8, ['Tiger', '10.4']], - [7, ['Panther', '10.3']], - [6, ['Jaguar', '10.2']], - [5, ['Puma', '10.1']] -]); + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat -const macosRelease = release => { - release = Number((release || os.release()).split('.')[0]); + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) - const [name, version] = nameMap.get(release); + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c - return { - name, - version - }; -}; + if (needDir && c === 'FILE') + return cb() -module.exports = macosRelease; -// TODO: remove this in the next major version -module.exports.default = macosRelease; + return cb(null, c, stat) +} /***/ }), -/* 119 */, -/* 120 */, /* 121 */ /***/ (function(module) { @@ -4643,11 +4099,17 @@ module.exports.MaxBufferError = MaxBufferError; /***/ (function(module, __unusedexports, __webpack_require__) { const { ClientError, logger } = __webpack_require__(79); -const { getWorkflowfileName } = __webpack_require__(316); +const { getDefinitionFile } = __webpack_require__(933); const GITHUB_URL_REGEXP = /^https:\/\/github.com\/([^/]+)\/([^/]+)\/(pull|tree)\/([^ ]+)$/; const GIT_URL_REGEXP = /^(https?:\/\/.*\/)([^/]+)\/([^/]+)\/(pull|tree)\/([^ ]+)$/; +function getInputs() { + return { + definitionFile: getDefinitionFile() + }; +} + async function createConfig(eventData, rootFolder, env = {}) { async function parseGitHub(env) { return { @@ -4669,9 +4131,10 @@ async function createConfig(eventData, rootFolder, env = {}) { repository: env["GITHUB_REPOSITORY"], // Ginxo/lienzo-tests group: env["GITHUB_REPOSITORY"].split("/")[0], // Ginxo project: env["GITHUB_REPOSITORY"].split("/")[1], // lienzo-tests - flowFile: getWorkflowfileName(), // main.yml + groupProject: env["GITHUB_REPOSITORY"], workflowName: env["GITHUB_WORKFLOW"], // Build Chain - ref: env["GITHUB_REF"] // refs/pull/1/merge' + ref: env["GITHUB_REF"], // refs/pull/1/merge' + inputs: getInputs() }; } return { @@ -4818,6969 +4281,5560 @@ module.exports = { /***/ }), -/* 150 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 150 */, +/* 151 */, +/* 152 */, +/* 153 */, +/* 154 */, +/* 155 */, +/* 156 */, +/* 157 */, +/* 158 */, +/* 159 */ +/***/ (function(module) { -/*! - * Tmp - * - * Copyright (c) 2011-2017 KARASZI Istvan - * - * MIT Licensed - */ +module.exports = r => { + const n = process.versions.node.split('.').map(x => parseInt(x, 10)) + r = r.split('.').map(x => parseInt(x, 10)) + return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2]))) +} -/* - * Module dependencies. - */ -const fs = __webpack_require__(747); -const os = __webpack_require__(87); -const path = __webpack_require__(622); -const crypto = __webpack_require__(417); -const _c = { fs: fs.constants, os: os.constants }; -const rimraf = __webpack_require__(569); -/* - * The working inner variables. - */ -const - // the random characters to choose from - RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', +/***/ }), +/* 160 */, +/* 161 */, +/* 162 */, +/* 163 */, +/* 164 */, +/* 165 */, +/* 166 */, +/* 167 */, +/* 168 */ +/***/ (function(module) { - TEMPLATE_PATTERN = /XXXXXX/, +"use strict"; - DEFAULT_TRIES = 3, +const alias = ['stdin', 'stdout', 'stderr']; - CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), +const hasAlias = opts => alias.some(x => Boolean(opts[x])); - // constants are off on the windows platform and will not match the actual errno codes - IS_WIN32 = os.platform() === 'win32', - EBADF = _c.EBADF || _c.os.errno.EBADF, - ENOENT = _c.ENOENT || _c.os.errno.ENOENT, +module.exports = opts => { + if (!opts) { + return null; + } - DIR_MODE = 0o700 /* 448 */, - FILE_MODE = 0o600 /* 384 */, + if (opts.stdio && hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); + } - EXIT = 'exit', + if (typeof opts.stdio === 'string') { + return opts.stdio; + } - // this will hold the objects need to be removed on exit - _removeObjects = [], + const stdio = opts.stdio || []; - // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback - FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), - FN_RIMRAF_SYNC = rimraf.sync; + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } -let - _gracefulCleanup = false; + const result = []; + const len = Math.max(stdio.length, alias.length); -/** - * Gets a temporary file name. - * - * @param {(Options|tmpNameCallback)} options options or callback - * @param {?tmpNameCallback} callback the callback function - */ -function tmpName(options, callback) { - const - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1]; + for (let i = 0; i < len; i++) { + let value = null; - try { - _assertAndSanitizeOptions(opts); - } catch (err) { - return cb(err); - } + if (stdio[i] !== undefined) { + value = stdio[i]; + } else if (opts[alias[i]] !== undefined) { + value = opts[alias[i]]; + } - let tries = opts.tries; - (function _getUniqueName() { - try { - const name = _generateTmpName(opts); + result[i] = value; + } - // check whether the path exists then retry if needed - fs.stat(name, function (err) { - /* istanbul ignore else */ - if (!err) { - /* istanbul ignore else */ - if (tries-- > 0) return _getUniqueName(); + return result; +}; - return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); - } - cb(null, name); - }); - } catch (err) { - cb(err); - } - }()); -} +/***/ }), +/* 169 */, +/* 170 */, +/* 171 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Synchronous version of tmpName. - * - * @param {Object} options - * @returns {string} the generated random name - * @throws {Error} if the options are invalid or could not generate a filename - */ -function tmpNameSync(options) { - const - args = _parseArguments(options), - opts = args[0]; +"use strict"; - _assertAndSanitizeOptions(opts); - let tries = opts.tries; - do { - const name = _generateTmpName(opts); - try { - fs.statSync(name); - } catch (e) { - return name; - } - } while (tries-- > 0); +const u = __webpack_require__(676).fromPromise +const jsonFile = __webpack_require__(469) - throw new Error('Could not get a unique tmp filename, max tries reached'); -} +jsonFile.outputJson = u(__webpack_require__(695)) +jsonFile.outputJsonSync = __webpack_require__(628) +// aliases +jsonFile.outputJSON = jsonFile.outputJson +jsonFile.outputJSONSync = jsonFile.outputJsonSync +jsonFile.writeJSON = jsonFile.writeJson +jsonFile.writeJSONSync = jsonFile.writeJsonSync +jsonFile.readJSON = jsonFile.readJson +jsonFile.readJSONSync = jsonFile.readJsonSync -/** - * Creates and opens a temporary file. - * - * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined - * @param {?fileCallback} callback - */ -function file(options, callback) { - const - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1]; +module.exports = jsonFile - // gets a temporary filename - tmpName(opts, function _tmpNameCreated(err, name) { - /* istanbul ignore else */ - if (err) return cb(err); - // create and open the file - fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { - /* istanbu ignore else */ - if (err) return cb(err); +/***/ }), +/* 172 */, +/* 173 */, +/* 174 */, +/* 175 */, +/* 176 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (opts.discardDescriptor) { - return fs.close(fd, function _discardCallback(possibleErr) { - // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only - return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); - }); - } else { - // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care - // about the descriptor - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); - } - }); - }); -} +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = __webpack_require__(393); +/** + * Status Reporter that displays information about the progress/status of an artifact that is being uploaded or downloaded + * + * Variable display time that can be adjusted using the displayFrequencyInMilliseconds variable + * The total status of the upload/download gets displayed according to this value + * If there is a large file that is being uploaded, extra information about the individual status can also be displayed using the updateLargeFileStatus function + */ +class StatusReporter { + constructor(displayFrequencyInMilliseconds) { + this.totalNumberOfFilesToProcess = 0; + this.processedCount = 0; + this.largeFiles = new Map(); + this.totalFileStatus = undefined; + this.largeFileStatus = undefined; + this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds; + } + setTotalNumberOfFilesToProcess(fileTotal) { + this.totalNumberOfFilesToProcess = fileTotal; + } + start() { + // displays information about the total upload/download status + this.totalFileStatus = setInterval(() => { + // display 1 decimal place without any rounding + const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess); + core_1.info(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`); + }, this.displayFrequencyInMilliseconds); + // displays extra information about any large files that take a significant amount of time to upload or download every 1 second + this.largeFileStatus = setInterval(() => { + for (const value of Array.from(this.largeFiles.values())) { + core_1.info(value); + } + // delete all entries in the map after displaying the information so it will not be displayed again unless explicitly added + this.largeFiles.clear(); + }, 1000); + } + // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload + updateLargeFileStatus(fileName, numerator, denominator) { + // display 1 decimal place without any rounding + const percentage = this.formatPercentage(numerator, denominator); + const displayInformation = `Uploading ${fileName} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`; + // any previously added display information should be overwritten for the specific large file because a map is being used + this.largeFiles.set(fileName, displayInformation); + } + stop() { + if (this.totalFileStatus) { + clearInterval(this.totalFileStatus); + } + if (this.largeFileStatus) { + clearInterval(this.largeFileStatus); + } + } + incrementProcessedCount() { + this.processedCount++; + } + formatPercentage(numerator, denominator) { + // toFixed() rounds, so use extra precision to display accurate information even though 4 decimal places are not displayed + return ((numerator / denominator) * 100).toFixed(4).toString(); + } +} +exports.StatusReporter = StatusReporter; +//# sourceMappingURL=status-reporter.js.map -/** - * Synchronous version of file. - * - * @param {Options} options - * @returns {FileSyncObject} object consists of name, fd and removeCallback - * @throws {Error} if cannot create a file - */ -function fileSync(options) { - const - args = _parseArguments(options), - opts = args[0]; +/***/ }), +/* 177 */, +/* 178 */, +/* 179 */, +/* 180 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - const name = tmpNameSync(opts); - var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); - /* istanbul ignore else */ - if (opts.discardDescriptor) { - fs.closeSync(fd); - fd = undefined; - } +"use strict"; - return { - name: name, - fd: fd, - removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) - }; -} -/** - * Creates a temporary directory. - * - * @param {(Options|dirCallback)} options the options or the callback function - * @param {?dirCallback} callback - */ -function dir(options, callback) { - const - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1]; - // gets a temporary filename - tmpName(opts, function _tmpNameCreated(err, name) { - /* istanbul ignore else */ - if (err) return cb(err); +var common = __webpack_require__(740); - // create the directory - fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { - /* istanbul ignore else */ - if (err) return cb(err); - cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); - }); - }); +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; } -/** - * Synchronous version of dir. - * - * @param {Options} options - * @returns {DirSyncObject} object consists of name and removeCallback - * @throws {Error} if it cannot create a directory - */ -function dirSync(options) { - const - args = _parseArguments(options), - opts = args[0]; - const name = tmpNameSync(opts); - fs.mkdirSync(name, opts.mode || DIR_MODE); +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; - return { - name: name, - removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) - }; -} + if (!this.buffer) return null; -/** - * Removes files asynchronously. - * - * @param {Object} fdPath - * @param {Function} next - * @private - */ -function _removeFileAsync(fdPath, next) { - const _handler = function (err) { - if (err && !_isENOENT(err)) { - // reraise any unanticipated error - return next(err); - } - next(); - }; + indent = indent || 4; + maxLength = maxLength || 75; - if (0 <= fdPath[0]) - fs.close(fdPath[0], function () { - fs.unlink(fdPath[1], _handler); - }); - else fs.unlink(fdPath[1], _handler); -} + head = ''; + start = this.position; -/** - * Removes files synchronously. - * - * @param {Object} fdPath - * @private - */ -function _removeFileSync(fdPath) { - let rethrownException = null; - try { - if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); - } catch (e) { - // reraise any unanticipated error - if (!_isEBADF(e) && !_isENOENT(e)) throw e; - } finally { - try { - fs.unlinkSync(fdPath[1]); - } - catch (e) { - // reraise any unanticipated error - if (!_isENOENT(e)) rethrownException = e; + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; } } - if (rethrownException !== null) { - throw rethrownException; - } -} - -/** - * Prepares the callback for removal of the temporary file. - * - * Returns either a sync callback or a async callback depending on whether - * fileSync or file was called, which is expressed by the sync parameter. - * - * @param {string} name the path of the file - * @param {number} fd file descriptor - * @param {Object} opts - * @param {boolean} sync - * @returns {fileCallback | fileCallbackSync} - * @private - */ -function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { - const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); - const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + tail = ''; + end = this.position; - return sync ? removeCallbackSync : removeCallback; -} + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } -/** - * Prepares the callback for removal of the temporary directory. - * - * Returns either a sync callback or a async callback depending on whether - * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. - * - * @param {string} name - * @param {Object} opts - * @param {boolean} sync - * @returns {Function} the callback - * @private - */ -function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); - const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; - const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); - const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + snippet = this.buffer.slice(start, end); - return sync ? removeCallbackSync : removeCallback; -} + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; -/** - * Creates a guarded function wrapping the removeFunction call. - * - * The cleanup callback is save to be called multiple times. - * Subsequent invocations will be ignored. - * - * @param {Function} removeFunction - * @param {string} fileOrDirName - * @param {boolean} sync - * @param {cleanupCallbackSync?} cleanupCallbackSync - * @returns {cleanupCallback | cleanupCallbackSync} - * @private - */ -function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { - let called = false; - // if sync is true, the next parameter will be ignored - return function _cleanupCallback(next) { +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; - /* istanbul ignore else */ - if (!called) { - // remove cleanupCallback from cache - const toRemove = cleanupCallbackSync || _cleanupCallback; - const index = _removeObjects.indexOf(toRemove); - /* istanbul ignore else */ - if (index >= 0) _removeObjects.splice(index, 1); + if (this.name) { + where += 'in "' + this.name + '" '; + } - called = true; - if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { - return removeFunction(fileOrDirName); - } else { - return removeFunction(fileOrDirName, next || function() {}); - } - } - }; -} + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); -/** - * The garbage collector. - * - * @private - */ -function _garbageCollector() { - /* istanbul ignore else */ - if (!_gracefulCleanup) return; + if (!compact) { + snippet = this.getSnippet(); - // the function being called removes itself from _removeObjects, - // loop until _removeObjects is empty - while (_removeObjects.length) { - try { - _removeObjects[0](); - } catch (e) { - // already removed? + if (snippet) { + where += ':\n' + snippet; } } -} - -/** - * Random name generator based on crypto. - * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript - * - * @param {number} howMany - * @returns {string} the generated random name - * @private - */ -function _randomChars(howMany) { - let - value = [], - rnd = null; - // make sure that we do not fail because we ran out of entropy - try { - rnd = crypto.randomBytes(howMany); - } catch (e) { - rnd = crypto.pseudoRandomBytes(howMany); - } + return where; +}; - for (var i = 0; i < howMany; i++) { - value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); - } - return value.join(''); -} +module.exports = Mark; -/** - * Helper which determines whether a string s is blank, that is undefined, or empty or null. - * - * @private - * @param {string} s - * @returns {Boolean} true whether the string s is blank, false otherwise - */ -function _isBlank(s) { - return s === null || _isUndefined(s) || !s.trim(); -} -/** - * Checks whether the `obj` parameter is defined or not. - * - * @param {Object} obj - * @returns {boolean} true if the object is undefined - * @private - */ -function _isUndefined(obj) { - return typeof obj === 'undefined'; -} +/***/ }), +/* 181 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Parses the function arguments. - * - * This function helps to have optional arguments. - * - * @param {(Options|null|undefined|Function)} options - * @param {?Function} callback - * @returns {Array} parsed arguments - * @private - */ -function _parseArguments(options, callback) { - /* istanbul ignore else */ - if (typeof options === 'function') { - return [{}, options]; - } +"use strict"; - /* istanbul ignore else */ - if (_isUndefined(options)) { - return [{}, callback]; - } - // copy options so we do not leak the changes we make internally - const actualOptions = {}; - for (const key of Object.getOwnPropertyNames(options)) { - actualOptions[key] = options[key]; - } +var Type = __webpack_require__(945); - return [actualOptions, callback]; -} +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; -/** - * Generates a new temporary name. - * - * @param {Object} opts - * @returns {string} the new random name according to opts - * @private - */ -function _generateTmpName(opts) { +function resolveYamlOmap(data) { + if (data === null) return true; - const tmpDir = opts.tmpdir; + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; - /* istanbul ignore else */ - if (!_isUndefined(opts.name)) - return path.join(tmpDir, opts.dir, opts.name); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - /* istanbul ignore else */ - if (!_isUndefined(opts.template)) - return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + if (_toString.call(pair) !== '[object Object]') return false; - // prefix and postfix - const name = [ - opts.prefix ? opts.prefix : 'tmp', - '-', - process.pid, - '-', - _randomChars(12), - opts.postfix ? '-' + opts.postfix : '' - ].join(''); + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } - return path.join(tmpDir, opts.dir, name); + return true; } -/** - * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing - * options. - * - * @param {Options} options - * @private - */ -function _assertAndSanitizeOptions(options) { +function constructYamlOmap(data) { + return data !== null ? data : []; +} - options.tmpdir = _getTmpDir(options); +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); - const tmpDir = options.tmpdir; - /* istanbul ignore else */ - if (!_isUndefined(options.name)) - _assertIsRelative(options.name, 'name', tmpDir); - /* istanbul ignore else */ - if (!_isUndefined(options.dir)) - _assertIsRelative(options.dir, 'dir', tmpDir); - /* istanbul ignore else */ - if (!_isUndefined(options.template)) { - _assertIsRelative(options.template, 'template', tmpDir); - if (!options.template.match(TEMPLATE_PATTERN)) - throw new Error(`Invalid template, found "${options.template}".`); - } - /* istanbul ignore else */ - if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) - throw new Error(`Invalid tries, found "${options.tries}".`); +/***/ }), +/* 182 */, +/* 183 */, +/* 184 */, +/* 185 */, +/* 186 */, +/* 187 */, +/* 188 */, +/* 189 */, +/* 190 */, +/* 191 */, +/* 192 */, +/* 193 */, +/* 194 */, +/* 195 */, +/* 196 */, +/* 197 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // if a name was specified we will try once - options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; - options.keep = !!options.keep; - options.detachDescriptor = !!options.detachDescriptor; - options.discardDescriptor = !!options.discardDescriptor; - options.unsafeCleanup = !!options.unsafeCleanup; +module.exports = isexe +isexe.sync = sync - // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to - options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); - options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); - // sanitize further if template is relative to options.dir - options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); +var fs = __webpack_require__(747) - // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to - options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); - options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; - options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) } -/** - * Resolve the specified path name in respect to tmpDir. - * - * The specified name might include relative path components, e.g. ../ - * so we need to resolve in order to be sure that is is located inside tmpDir - * - * @param name - * @param tmpDir - * @returns {string} - * @private - */ -function _resolvePath(name, tmpDir) { - const sanitizedName = _sanitizeName(name); - if (sanitizedName.startsWith(tmpDir)) { - return path.resolve(sanitizedName); - } else { - return path.resolve(path.join(tmpDir, sanitizedName)); - } +function sync (path, options) { + return checkStat(fs.statSync(path), options) } -/** - * Sanitize the specified path name by removing all quote characters. - * - * @param name - * @returns {string} - * @private - */ -function _sanitizeName(name) { - if (_isBlank(name)) { - return name; - } - return name.replace(/["']/g, ''); +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) } -/** - * Asserts whether specified name is relative to the specified tmpDir. - * - * @param {string} name - * @param {string} option - * @param {string} tmpDir - * @throws {Error} - * @private - */ -function _assertIsRelative(name, option, tmpDir) { - if (option === 'name') { - // assert that name is not absolute and does not contain a path - if (path.isAbsolute(name)) - throw new Error(`${option} option must not contain an absolute path, found "${name}".`); - // must not fail on valid . or .. or similar such constructs - let basename = path.basename(name); - if (basename === '..' || basename === '.' || basename !== name) - throw new Error(`${option} option must not contain a path, found "${name}".`); - } - else { // if (option === 'dir' || option === 'template') { - // assert that dir or template are relative to tmpDir - if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { - throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); - } - let resolvedPath = _resolvePath(name, tmpDir); - if (!resolvedPath.startsWith(tmpDir)) - throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); - } -} +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid -/** - * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. - * - * @private - */ -function _isEBADF(error) { - return _isExpectedError(error, -EBADF, 'EBADF'); -} + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() -/** - * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. - * - * @private - */ -function _isENOENT(error) { - return _isExpectedError(error, -ENOENT, 'ENOENT'); -} + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g -/** - * Helper to determine whether the expected error code matches the actual code and errno, - * which will differ between the supported node versions. - * - * - Node >= 7.0: - * error.code {string} - * error.errno {number} any numerical value will be negated - * - * CAVEAT - * - * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT - * is no different here. - * - * @param {SystemError} error - * @param {number} errno - * @param {string} code - * @private - */ -function _isExpectedError(error, errno, code) { - return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; -} + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 -/** - * Sets the graceful cleanup. - * - * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the - * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary - * object removals. - */ -function setGracefulCleanup() { - _gracefulCleanup = true; + return ret } -/** - * Returns the currently configured tmp dir from os.tmpdir(). - * - * @private - * @param {?Options} options - * @returns {string} the currently configured tmp dir - */ -function _getTmpDir(options) { - return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); -} -// Install process exit listener -process.addListener(EXIT, _garbageCollector); +/***/ }), +/* 198 */, +/* 199 */, +/* 200 */, +/* 201 */, +/* 202 */, +/* 203 */, +/* 204 */, +/* 205 */, +/* 206 */, +/* 207 */, +/* 208 */, +/* 209 */, +/* 210 */, +/* 211 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Configuration options. +"use strict"; +/*:nodoc:* + * class ActionStoreTrue * - * @typedef {Object} Options - * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected - * @property {?number} tries the number of tries before give up the name generation - * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files - * @property {?string} template the "mkstemp" like filename template - * @property {?string} name fixed name relative to tmpdir or the specified dir option - * @property {?string} dir tmp directory relative to the root tmp directory in use - * @property {?string} prefix prefix for the generated name - * @property {?string} postfix postfix for the generated name - * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir - * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty - * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection - * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection - */ + * This action store the values True respectively. + * This isspecial cases of 'storeConst' + * + * This class inherited from [[Action]] + **/ -/** - * @typedef {Object} FileSyncObject - * @property {string} name the name of the file - * @property {string} fd the file descriptor or -1 if the fd has been discarded - * @property {fileCallback} removeCallback the callback function to remove the file - */ -/** - * @typedef {Object} DirSyncObject - * @property {string} name the name of the directory - * @property {fileCallback} removeCallback the callback function to remove the directory - */ +var util = __webpack_require__(669); -/** - * @callback tmpNameCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - */ +var ActionStoreConstant = __webpack_require__(267); -/** - * @callback fileCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {number} fd the file descriptor or -1 if the fd had been discarded - * @param {cleanupCallback} fn the cleanup callback function - */ +/*:nodoc:* + * new ActionStoreTrue(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { + options = options || {}; + options.constant = true; + options.defaultValue = options.defaultValue !== null ? options.defaultValue : false; + ActionStoreConstant.call(this, options); +}; +util.inherits(ActionStoreTrue, ActionStoreConstant); -/** - * @callback fileCallbackSync - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {number} fd the file descriptor or -1 if the fd had been discarded - * @param {cleanupCallbackSync} fn the cleanup callback function - */ -/** - * @callback dirCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {cleanupCallback} fn the cleanup callback function - */ +/***/ }), +/* 212 */, +/* 213 */, +/* 214 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/** - * @callback dirCallbackSync - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {cleanupCallbackSync} fn the cleanup callback function - */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const artifact_client_1 = __webpack_require__(359); +/** + * Constructs an ArtifactClient + */ +function create() { + return artifact_client_1.DefaultArtifactClient.create(); +} +exports.create = create; +//# sourceMappingURL=artifact-client.js.map -/** - * Removes the temporary created file or directory. - * - * @callback cleanupCallback - * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed - */ - -/** - * Removes the temporary created file or directory. - * - * @callback cleanupCallbackSync - */ - -/** - * Callback function for function composition. - * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} - * - * @callback simpleCallback - */ - -// exporting all the needed methods - -// evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will -// allow users to reconfigure the temporary directory -Object.defineProperty(module.exports, 'tmpdir', { - enumerable: true, - configurable: false, - get: function () { - return _getTmpDir(); - } -}); - -module.exports.dir = dir; -module.exports.dirSync = dirSync; - -module.exports.file = file; -module.exports.fileSync = fileSync; - -module.exports.tmpName = tmpName; -module.exports.tmpNameSync = tmpNameSync; +/***/ }), +/* 215 */, +/* 216 */, +/* 217 */, +/* 218 */, +/* 219 */, +/* 220 */, +/* 221 */, +/* 222 */, +/* 223 */, +/* 224 */, +/* 225 */, +/* 226 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -module.exports.setGracefulCleanup = setGracefulCleanup; +"use strict"; -/***/ }), -/* 151 */, -/* 152 */, -/* 153 */, -/* 154 */, -/* 155 */, -/* 156 */, -/* 157 */, -/* 158 */, -/* 159 */ -/***/ (function(module) { +module.exports = { + // Export promiseified graceful-fs: + ...__webpack_require__(869), + // Export extra methods: + ...__webpack_require__(43), + ...__webpack_require__(774), + ...__webpack_require__(615), + ...__webpack_require__(472), + ...__webpack_require__(171), + ...__webpack_require__(727), + ...__webpack_require__(959), + ...__webpack_require__(353), + ...__webpack_require__(517), + ...__webpack_require__(322), + ...__webpack_require__(723) +} -module.exports = r => { - const n = process.versions.node.split('.').map(x => parseInt(x, 10)) - r = r.split('.').map(x => parseInt(x, 10)) - return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2]))) +// Export fs.promises as a getter property so that we don't trigger +// ExperimentalWarning before fs.promises is actually accessed. +const fs = __webpack_require__(747) +if (Object.getOwnPropertyDescriptor(fs, 'promises')) { + Object.defineProperty(module.exports, 'promises', { + get () { return fs.promises } + }) } /***/ }), -/* 160 */, -/* 161 */, -/* 162 */, -/* 163 */, -/* 164 */, -/* 165 */ +/* 227 */, +/* 228 */ /***/ (function(module, __unusedexports, __webpack_require__) { -const fs = __webpack_require__(747); -const path = __webpack_require__(622); -const { logger } = __webpack_require__(79); -const { getYamlFileContent } = __webpack_require__(360); -var assert = __webpack_require__(357); -const core = __webpack_require__(393); -const { checkoutDependencies, getDir } = __webpack_require__(57); - -async function checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - currentTargetBranch, - workflowInformation -) { - if (!projectList[project]) { - projectList.push(project); - if ( - workflowInformation.parentDependencies && - Object.keys(workflowInformation.parentDependencies).length > 0 - ) { - core.startGroup( - `Checking out dependencies [${Object.keys( - workflowInformation.parentDependencies - ).join(", ")}] for project ${project}` - ); - const checkoutInfos = await checkoutDependencies( - context, - workflowInformation.parentDependencies, - currentTargetBranch - ); - core.endGroup(); - for (const [parentProject, parentDependency] of Object.entries( - workflowInformation.parentDependencies - ).filter( - ([parentDependencyKey]) => - parentDependencyKey !== null && parentDependencyKey !== "" - )) { - const dir = getDir(context.config.rootFolder, parentProject); - const parentWorkflowInformation = readWorkflowInformation( - parentProject, - parentDependency.jobId - ? parentDependency.jobId - : workflowInformation.jobId, - `.github/workflows/${ - parentDependency.flowFile - ? parentDependency.flowFile - : workflowInformation.flowFile - }`, - context.config.github.group, - context.config.matrixVariables, - dir - ); +"use strict"; - if (parentWorkflowInformation) { - return [parentWorkflowInformation].concat( - await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - parentProject, - checkoutInfos[parentProject].targetBranch, - parentWorkflowInformation - ) - ); - } else { - logger.warn( - `workflow information ${ - parentDependency.flowFile - ? parentDependency.flowFile - : context.config.github.flowFile - } not present for ${parentProject}.` - ); - return []; - } - } - } - } - return []; -} -function readWorkflowInformation( - project, - jobId, - workflowFilePath, - defaultGroup, - matrixVariables, - dir = "." -) { - const filePath = path.join(dir, workflowFilePath); - if (!fs.existsSync(filePath)) { - logger.warn(`file ${filePath} does not exist`); - return undefined; - } - return parseWorkflowInformation( - project, - jobId, - getYamlFileContent(filePath), - defaultGroup, - matrixVariables - ); -} +var Type = __webpack_require__(945); -function parseWorkflowInformation( - project, - jobId, - workflowData, - defaultGroup, - matrixVariables -) { - assert(workflowData.jobs[jobId], `The job id '${jobId}' does not exist`); - const buildChainStep = workflowData.jobs[jobId].steps.find( - step => step.uses && step.uses.includes("github-action-build-chain") - ); - assert( - buildChainStep.with["workflow-file-name"], - `The workflow file name does not exist for '${project}' and it's mandatory` - ); - buildChainStep.with = Object.entries(buildChainStep.with) - .filter(([key]) => key !== "matrix-variables") - .reduce((acc, [key, value]) => { - acc[key] = treatMatrixVariables(value, matrixVariables); - return acc; - }, {}); - return { - id: buildChainStep.id, - project, - name: buildChainStep.name, - buildCommands: splitCommands(buildChainStep.with["build-command"]), - buildCommandsUpstream: splitCommands( - buildChainStep.with["build-command-upstream"] - ), - buildCommandsDownstream: splitCommands( - buildChainStep.with["build-command-downstream"] - ), - childDependencies: dependenciesToObject( - buildChainStep.with["child-dependencies"], - defaultGroup - ), - parentDependencies: dependenciesToObject( - buildChainStep.with["parent-dependencies"], - defaultGroup - ), - archiveArtifacts: getArchiveArtifacts(buildChainStep, project), - jobId, - flowFile: buildChainStep.with["workflow-file-name"] - }; -} +function resolveYamlBoolean(data) { + if (data === null) return false; -function splitCommands(commands) { - return commands - ? commands - .split("\n") - .filter(line => line) - .map(item => item.trim()) - : undefined; -} + var max = data.length; -function treatMatrixVariables(withExpression, matrixVariables) { - let result = withExpression; - const exp = /((\${{ )([a-zA-Z0-9\\.\\-]*)( }}))/g; - let match = undefined; - while ((match = exp.exec(withExpression))) { - if (!matrixVariables || !matrixVariables[match[3]]) { - throw new Error( - `The variable '${match[3]}' is not defined in "with" 'matrix-variables' so it can't be replaced. Please define it in the flow triggering the job.` - ); - } - result = result.replace(`${match[1]}`, matrixVariables[match[3]]); - } - return result; + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -function getArchiveArtifacts(step, defaultName = "artifact") { - return { - name: step.with["archive-artifacts-name"] - ? step.with["archive-artifacts-name"] - : step.with["archive-artifacts-path"] - ? defaultName - : undefined, - - paths: treatArchiveArtifactsPath(step.with["archive-artifacts-path"]), - ifNoFilesFound: step.with["archive-artifacts-if-no-files-found"] - ? step.with["archive-artifacts-if-no-files-found"] - : step.with["archive-artifacts-path"] - ? "warn" - : undefined, - dependencies: treatArchiveArtifactsDependencies( - step.with["archive-artifacts-dependencies"] - ) - }; +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; } -function treatArchiveArtifactsPath(archiveArtifacts) { - return archiveArtifacts - ? archiveArtifacts - .split("\n") - .filter(line => line) - .reduce((acc, pathExpression) => { - acc.push(convertPathExpressionToPath(pathExpression)); - return acc; - }, []) - : undefined; +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; } -function convertPathExpressionToPath(pathExpression) { - const match = pathExpression.match(/([^@]*)@?(always|success|failure)?/); - return match - ? { - path: match[1], - on: match[2] ? match[2] : "success" - } - : pathExpression; -} +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); -function treatArchiveArtifactsDependencies(archiveArtifactsDependencies) { - if (archiveArtifactsDependencies) { - if ( - archiveArtifactsDependencies === "all" || - archiveArtifactsDependencies === "none" - ) { - return archiveArtifactsDependencies; - } else { - return archiveArtifactsDependencies - .split("\n") - .filter(line => line) - .map(item => item.trim()); - } - } else { - return "none"; - } -} - -function dependenciesToObject(dependencies, defaultGroup) { - const dependenciesObject = {}; - dependencies - ? dependencies - .split("\n") - .filter(line => line) - .forEach(dependency => { - const projectName = getProjectName(dependency.trim()); - dependenciesObject[projectName] = { - group: getGroupFromDependency(dependency, defaultGroup), - mapping: getMappingFromDependency(dependency), - flowFile: getFlowFileFromDependency(dependency), - jobId: getJobIdFromDependency(dependency) - }; - }) - : {}; - return dependenciesObject; -} -function getProjectName(dependency) { - const match = dependency.match(/(.*\/)?([\w\-.]*).*/); - return match[2]; -} +/***/ }), +/* 229 */, +/* 230 */, +/* 231 */, +/* 232 */, +/* 233 */, +/* 234 */, +/* 235 */, +/* 236 */, +/* 237 */, +/* 238 */, +/* 239 */, +/* 240 */, +/* 241 */, +/* 242 */, +/* 243 */, +/* 244 */, +/* 245 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -function getGroupFromDependency(dependency, defaultGroup) { - const match = dependency.match(/([\w\-.]*)\//); - return match ? match[1] : defaultGroup; -} +module.exports = globSync +globSync.GlobSync = GlobSync -function getMappingFromDependency(dependency) { - const match = dependency.match(/@([\w\-.]*):([\w\-.]*)/); - return match - ? { - source: match[1], - target: match[2] - } - : undefined; -} +var fs = __webpack_require__(747) +var rp = __webpack_require__(302) +var minimatch = __webpack_require__(571) +var Minimatch = minimatch.Minimatch +var Glob = __webpack_require__(120).Glob +var util = __webpack_require__(669) +var path = __webpack_require__(622) +var assert = __webpack_require__(357) +var isAbsolute = __webpack_require__(681) +var common = __webpack_require__(644) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored -function getFlowFileFromDependency(dependency) { - const match = dependency.match(/\|([\w\-.]*):?/); - return match && match[1] ? match[1] : undefined; -} +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') -function getJobIdFromDependency(dependency) { - const match = dependency.match(/\|.*:([\w\-.]*)/); - return match && match[1] ? match[1] : undefined; + return new GlobSync(pattern, options).found } -module.exports = { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation, - dependenciesToObject -}; +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') -/***/ }), -/* 166 */, -/* 167 */, -/* 168 */ -/***/ (function(module) { + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) -"use strict"; + setopts(this, pattern, options) -const alias = ['stdin', 'stdout', 'stderr']; + if (this.noprocess) + return this -const hasAlias = opts => alias.some(x => Boolean(opts[x])); - -module.exports = opts => { - if (!opts) { - return null; - } - - if (opts.stdio && hasAlias(opts)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); - } + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} - if (typeof opts.stdio === 'string') { - return opts.stdio; - } +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} - const stdio = opts.stdio || []; - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) - const result = []; - const len = Math.max(stdio.length, alias.length); + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. - for (let i = 0; i < len; i++) { - let value = null; + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return - if (stdio[i] !== undefined) { - value = stdio[i]; - } else if (opts[alias[i]] !== undefined) { - value = opts[alias[i]]; - } + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - result[i] = value; - } + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } - return result; -}; + var remain = pattern.slice(n) + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix -/***/ }), -/* 169 */, -/* 170 */, -/* 171 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var abs = this._makeAbs(read) -"use strict"; + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} -const u = __webpack_require__(676).fromPromise -const jsonFile = __webpack_require__(469) -jsonFile.outputJson = u(__webpack_require__(695)) -jsonFile.outputJsonSync = __webpack_require__(628) -// aliases -jsonFile.outputJSON = jsonFile.outputJson -jsonFile.outputJSONSync = jsonFile.outputJsonSync -jsonFile.writeJSON = jsonFile.writeJson -jsonFile.writeJSONSync = jsonFile.writeJsonSync -jsonFile.readJSON = jsonFile.readJson -jsonFile.readJSONSync = jsonFile.readJsonSync +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) -module.exports = jsonFile + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' -/***/ }), -/* 172 */, -/* 173 */, -/* 174 */, -/* 175 */, -/* 176 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const core_1 = __webpack_require__(393); -/** - * Status Reporter that displays information about the progress/status of an artifact that is being uploaded or downloaded - * - * Variable display time that can be adjusted using the displayFrequencyInMilliseconds variable - * The total status of the upload/download gets displayed according to this value - * If there is a large file that is being uploaded, extra information about the individual status can also be displayed using the updateLargeFileStatus function - */ -class StatusReporter { - constructor(displayFrequencyInMilliseconds) { - this.totalNumberOfFilesToProcess = 0; - this.processedCount = 0; - this.largeFiles = new Map(); - this.totalFileStatus = undefined; - this.largeFileStatus = undefined; - this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds; - } - setTotalNumberOfFilesToProcess(fileTotal) { - this.totalNumberOfFilesToProcess = fileTotal; - } - start() { - // displays information about the total upload/download status - this.totalFileStatus = setInterval(() => { - // display 1 decimal place without any rounding - const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess); - core_1.info(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`); - }, this.displayFrequencyInMilliseconds); - // displays extra information about any large files that take a significant amount of time to upload or download every 1 second - this.largeFileStatus = setInterval(() => { - for (const value of Array.from(this.largeFiles.values())) { - core_1.info(value); - } - // delete all entries in the map after displaying the information so it will not be displayed again unless explicitly added - this.largeFiles.clear(); - }, 1000); - } - // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload - updateLargeFileStatus(fileName, numerator, denominator) { - // display 1 decimal place without any rounding - const percentage = this.formatPercentage(numerator, denominator); - const displayInformation = `Uploading ${fileName} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`; - // any previously added display information should be overwritten for the specific large file because a map is being used - this.largeFiles.set(fileName, displayInformation); - } - stop() { - if (this.totalFileStatus) { - clearInterval(this.totalFileStatus); - } - if (this.largeFileStatus) { - clearInterval(this.largeFileStatus); - } - } - incrementProcessedCount() { - this.processedCount++; - } - formatPercentage(numerator, denominator) { - // toFixed() rounds, so use extra precision to display accurate information even though 4 decimal places are not displayed - return ((numerator / denominator) * 100).toFixed(4).toString(); - } -} -exports.StatusReporter = StatusReporter; -//# sourceMappingURL=status-reporter.js.map + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return -/***/ }), -/* 177 */, -/* 178 */, -/* 179 */, -/* 180 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. -"use strict"; + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } -var common = __webpack_require__(740); - - -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } } -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; - - if (!this.buffer) return null; +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return - indent = indent || 4; - maxLength = maxLength || 75; + var abs = this._makeAbs(e) - head = ''; - start = this.position; + if (this.mark) + e = this._mark(e) - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } + if (this.absolute) { + e = abs } - tail = ''; - end = this.position; + if (this.matches[index][e]) + return - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } - snippet = this.buffer.slice(start, end); - - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; + this.matches[index][e] = true - if (this.name) { - where += 'in "' + this.name + '" '; - } + if (this.stat) + this._stat(e) +} - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - if (!compact) { - snippet = this.getSnippet(); +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) - if (snippet) { - where += ':\n' + snippet; + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null } } - return where; -}; - - -module.exports = Mark; - - -/***/ }), -/* 181 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) -var Type = __webpack_require__(945); + return entries +} -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries -function resolveYamlOmap(data) { - if (data === null) return true; + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; + if (Array.isArray(c)) + return c + } - if (_toString.call(pair) !== '[object Object]') return false; + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; } - return true; -} + this.cache[abs] = entries -function constructYamlOmap(data) { - return data !== null ? data : []; + // mark and cache dir-ness + return entries } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break -/***/ }), -/* 182 */, -/* 183 */, -/* 184 */, -/* 185 */, -/* 186 */, -/* 187 */, -/* 188 */, -/* 189 */, -/* 190 */, -/* 191 */, -/* 192 */, -/* 193 */, -/* 194 */, -/* 195 */ -/***/ (function(module) { + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break -function getCheckoutInfo(context) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break } - return context.checkoutInfo; } -function getCheckoutInfoProject(context, project) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; - } - return context.checkoutInfo[project]; -} +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { -function saveCheckoutInfo(context, project, checkoutInfo) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; - } - return (context.checkoutInfo[project] = checkoutInfo); -} + var entries = this._readdir(abs, inGlobStar) -module.exports = { - getCheckoutInfo, - getCheckoutInfoProject, - saveCheckoutInfo -}; + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -/***/ }), -/* 196 */, -/* 197 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) -module.exports = isexe -isexe.sync = sync + var len = entries.length + var isSym = this.symlinks[abs] -var fs = __webpack_require__(747) + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue -function sync (path, options) { - return checkStat(fs.statSync(path), options) -} + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } } -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() + if (!this.matches[index]) + this.matches[index] = Object.create(null) - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g + // If it doesn't exist, then just mark the lack of results + if (!exists) + return - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } - return ret + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) } +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' -/***/ }), -/* 198 */, -/* 199 */, -/* 200 */, -/* 201 */, -/* 202 */, -/* 203 */, -/* 204 */, -/* 205 */, -/* 206 */, -/* 207 */, -/* 208 */, -/* 209 */, -/* 210 */, -/* 211 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (f.length > this.maxLength) + return false -"use strict"; -/*:nodoc:* - * class ActionStoreTrue - * - * This action store the values True respectively. - * This isspecial cases of 'storeConst' - * - * This class inherited from [[Action]] - **/ + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (Array.isArray(c)) + c = 'DIR' -var util = __webpack_require__(669); + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c -var ActionStoreConstant = __webpack_require__(267); + if (needDir && c === 'FILE') + return false -/*:nodoc:* - * new ActionStoreTrue(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { - options = options || {}; - options.constant = true; - options.defaultValue = options.defaultValue !== null ? options.defaultValue : false; - ActionStoreConstant.call(this, options); -}; -util.inherits(ActionStoreTrue, ActionStoreConstant); + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } -/***/ }), -/* 212 */, -/* 213 */, -/* 214 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const artifact_client_1 = __webpack_require__(359); -/** - * Constructs an ArtifactClient - */ -function create() { - return artifact_client_1.DefaultArtifactClient.create(); -} -exports.create = create; -//# sourceMappingURL=artifact-client.js.map + this.statCache[abs] = stat -/***/ }), -/* 215 */, -/* 216 */, -/* 217 */, -/* 218 */, -/* 219 */, -/* 220 */, -/* 221 */, -/* 222 */, -/* 223 */, -/* 224 */, -/* 225 */, -/* 226 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' -"use strict"; + this.cache[abs] = this.cache[abs] || c + if (needDir && c === 'FILE') + return false -module.exports = { - // Export promiseified graceful-fs: - ...__webpack_require__(869), - // Export extra methods: - ...__webpack_require__(43), - ...__webpack_require__(774), - ...__webpack_require__(615), - ...__webpack_require__(472), - ...__webpack_require__(171), - ...__webpack_require__(727), - ...__webpack_require__(959), - ...__webpack_require__(353), - ...__webpack_require__(517), - ...__webpack_require__(322), - ...__webpack_require__(723) + return c } -// Export fs.promises as a getter property so that we don't trigger -// ExperimentalWarning before fs.promises is actually accessed. -const fs = __webpack_require__(747) -if (Object.getOwnPropertyDescriptor(fs, 'promises')) { - Object.defineProperty(module.exports, 'promises', { - get () { return fs.promises } - }) +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) } /***/ }), -/* 227 */, -/* 228 */ +/* 246 */, +/* 247 */, +/* 248 */, +/* 249 */, +/* 250 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - - -var Type = __webpack_require__(945); +var constants = __webpack_require__(619) -function resolveYamlBoolean(data) { - if (data === null) return false; +var origCwd = process.cwd +var cwd = null - var max = data.length; +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) } -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} +module.exports = patch -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); +function patch (fs) { + // (re-)implement some things that are known busted or missing. + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -/***/ }), -/* 229 */, -/* 230 */, -/* 231 */, -/* 232 */, -/* 233 */, -/* 234 */, -/* 235 */, -/* 236 */, -/* 237 */, -/* 238 */, -/* 239 */, -/* 240 */, -/* 241 */, -/* 242 */, -/* 243 */, -/* 244 */, -/* 245 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } -module.exports = globSync -globSync.GlobSync = GlobSync + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. -var fs = __webpack_require__(747) -var rp = __webpack_require__(302) -var minimatch = __webpack_require__(571) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(402).Glob -var util = __webpack_require__(669) -var path = __webpack_require__(622) -var assert = __webpack_require__(357) -var isAbsolute = __webpack_require__(681) -var common = __webpack_require__(856) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - return new GlobSync(pattern, options).found -} + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - setopts(this, pattern, options) + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - if (this.noprocess) - return this + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) } - this._finish() -} -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) } } - }) - } - common.finish(this) -} - + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } } - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} - + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } - // if the abs isn't a dir, then nothing can match! - if (!entries) - return + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er } - if (m) - matchedEntries.push(e) } } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er } + } + } - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null } - this._emitMatch(index, e) + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) } - // This was the last one, and no stats were needed - return } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } } -} + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return - - var abs = this._makeAbs(e) + if (er.code === "ENOSYS") + return true - if (this.mark) - e = this._mark(e) + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } - if (this.absolute) { - e = abs + return false } +} - if (this.matches[index][e]) - return - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +/***/ }), +/* 251 */, +/* 252 */, +/* 253 */, +/* 254 */, +/* 255 */ +/***/ (function(__unusedmodule, exports) { - this.matches[index][e] = true +"use strict"; - if (this.stat) - this._stat(e) -} +exports.repeat = function (str, num) { + var result = ''; + for (var i = 0; i < num; i++) { result += str; } + return result; +}; -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) +exports.arrayEqual = function (a, b) { + if (a.length !== b.length) { return false; } + for (var i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { return false; } + } + return true; +}; - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null +exports.trimChars = function (str, chars) { + var start = 0; + var end = str.length - 1; + while (chars.indexOf(str.charAt(start)) >= 0) { start++; } + while (chars.indexOf(str.charAt(end)) >= 0) { end--; } + return str.slice(start, end + 1); +}; + +exports.capitalize = function (str) { + return str.charAt(0).toUpperCase() + str.slice(1); +}; + +exports.arrayUnion = function () { + var result = []; + for (var i = 0, values = {}; i < arguments.length; i++) { + var arr = arguments[i]; + for (var j = 0; j < arr.length; j++) { + if (!values[arr[j]]) { + values[arr[j]] = true; + result.push(arr[j]); + } } } + return result; +}; - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) +exports.has = has; - return entries +exports.extend = function (dest, src) { + for (var i in src) { + if (has(src, i)) { dest[i] = src[i]; } + } +}; + +exports.trimEnd = function (str) { + return str.replace(/\s+$/g, ''); +}; + + +/***/ }), +/* 256 */, +/* 257 */, +/* 258 */, +/* 259 */, +/* 260 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = __webpack_require__(357) +var signals = __webpack_require__(654) +var isWin = /^win/i.test(process.platform) + +var EE = __webpack_require__(759) +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter } -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +var emitter +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ +} else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} +} - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true +} - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +module.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') - if (Array.isArray(c)) - return c + if (loaded === false) { + load() } - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' } -} -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() } } + emitter.on(ev, cb) - this.cache[abs] = entries - - // mark and cache dir-ness - return entries + return remove } -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break +module.exports.unload = unload +function unload () { + if (!loaded) { + return + } + loaded = false - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 +} - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return } + emitter.emitted[event] = true + emitter.emit(event, code, signal) } -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return +// { : , ... } +var sigListeners = {} +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT' + } + process.kill(process.pid, sig) + } + } +}) - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +module.exports.signals = function () { + return signals +} - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) +module.exports.load = load - var len = entries.length - var isSym = this.symlinks[abs] +var loaded = false - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) +function load () { + if (loaded) { return + } + loaded = true - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } + process.emit = processEmit + process.reallyExit = processReallyExit } -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +var originalProcessReallyExit = process.reallyExit +function processReallyExit (code) { + process.exitCode = code || 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) +} - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' +var originalProcessEmit = process.emit +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg } + var ret = originalProcessEmit.apply(this, arguments) + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + return ret + } else { + return originalProcessEmit.apply(this, arguments) } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) } -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (Array.isArray(c)) - c = 'DIR' +/***/ }), +/* 261 */, +/* 262 */, +/* 263 */, +/* 264 */, +/* 265 */, +/* 266 */, +/* 267 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c +"use strict"; +/*:nodoc:* + * class ActionStoreConstant + * + * This action stores the value specified by the const keyword argument. + * (Note that the const keyword argument defaults to the rather unhelpful null.) + * The 'store_const' action is most commonly used with optional + * arguments that specify some sort of flag. + * + * This class inherited from [[Action]] + **/ - if (needDir && c === 'FILE') - return false - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } +var util = __webpack_require__(669); - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } +var Action = __webpack_require__(380); - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } +/*:nodoc:* + * new ActionStoreConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { + options = options || {}; + options.nargs = 0; + if (typeof options.constant === 'undefined') { + throw new Error('constant option is required for storeAction'); } + Action.call(this, options); +}; +util.inherits(ActionStoreConstant, Action); - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' +/*:nodoc:* + * ActionStoreConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStoreConstant.prototype.call = function (parser, namespace) { + namespace.set(this.dest, this.constant); +}; - this.cache[abs] = this.cache[abs] || c - if (needDir && c === 'FILE') - return false +/***/ }), +/* 268 */, +/* 269 */, +/* 270 */, +/* 271 */, +/* 272 */, +/* 273 */, +/* 274 */, +/* 275 */, +/* 276 */, +/* 277 */, +/* 278 */, +/* 279 */, +/* 280 */ +/***/ (function(module, exports) { - return c -} +exports = module.exports = SemVer -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} } -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 -/***/ }), -/* 246 */, -/* 247 */, -/* 248 */, -/* 249 */, -/* 250 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 -var constants = __webpack_require__(619) +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 -var origCwd = process.cwd -var cwd = null +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. -module.exports = patch +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' -function patch (fs) { - // (re-)implement some things that are known busted or missing. +// ## Main Version +// Three dot-separated numeric identifiers. - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. - // This ensures `util.promisify` works as it does for native `fs.read`. - read.__proto__ = fs$read - return read - })(fs.read) +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } +src[FULL] = '^' + FULLPLAIN + '$' - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } - } +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' - if (er.code === "ENOSYS") - return true +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - return false - } -} +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' -/***/ }), -/* 251 */, -/* 252 */, -/* 253 */, -/* 254 */, -/* 255 */ -/***/ (function(__unusedmodule, exports) { +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' -"use strict"; +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' -exports.repeat = function (str, num) { - var result = ''; - for (var i = 0; i < num; i++) { result += str; } - return result; -}; +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' -exports.arrayEqual = function (a, b) { - if (a.length !== b.length) { return false; } - for (var i = 0; i < a.length; i++) { - if (a[i] !== b[i]) { return false; } +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) } - return true; -}; - -exports.trimChars = function (str, chars) { - var start = 0; - var end = str.length - 1; - while (chars.indexOf(str.charAt(start)) >= 0) { start++; } - while (chars.indexOf(str.charAt(end)) >= 0) { end--; } - return str.slice(start, end + 1); -}; - -exports.capitalize = function (str) { - return str.charAt(0).toUpperCase() + str.slice(1); -}; +} -exports.arrayUnion = function () { - var result = []; - for (var i = 0, values = {}; i < arguments.length; i++) { - var arr = arguments[i]; - for (var j = 0; j < arr.length; j++) { - if (!values[arr[j]]) { - values[arr[j]] = true; - result.push(arr[j]); - } +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } } - return result; -}; - -function has(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -exports.has = has; - -exports.extend = function (dest, src) { - for (var i in src) { - if (has(src, i)) { dest[i] = src[i]; } + if (version instanceof SemVer) { + return version } -}; -exports.trimEnd = function (str) { - return str.replace(/\s+$/g, ''); -}; + if (typeof version !== 'string') { + return null + } + if (version.length > MAX_LENGTH) { + return null + } -/***/ }), -/* 256 */, -/* 257 */, -/* 258 */, -/* 259 */, -/* 260 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. -var assert = __webpack_require__(357) -var signals = __webpack_require__(654) -var isWin = /^win/i.test(process.platform) + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} -var EE = __webpack_require__(759) -/* istanbul ignore if */ -if (typeof EE !== 'function') { - EE = EE.EventEmitter +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null } -var emitter -if (process.__signal_exit_emitter__) { - emitter = process.__signal_exit_emitter__ -} else { - emitter = process.__signal_exit_emitter__ = new EE() - emitter.count = 0 - emitter.emitted = {} -} - -// Because this emitter is a global, we have to check to see if a -// previous version of this library failed to enable infinite listeners. -// I know what you're about to say. But literally everything about -// signal-exit is a compromise with evil. Get used to it. -if (!emitter.infinite) { - emitter.setMaxListeners(Infinity) - emitter.infinite = true +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null } -module.exports = function (cb, opts) { - assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') - - if (loaded === false) { - load() - } +exports.SemVer = SemVer - var ev = 'exit' - if (opts && opts.alwaysLast) { - ev = 'afterexit' +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - - var remove = function () { - emitter.removeListener(ev, cb) - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload() + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) } - emitter.on(ev, cb) - return remove -} + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } -module.exports.unload = unload -function unload () { - if (!loaded) { - return + if (!(this instanceof SemVer)) { + return new SemVer(version, options) } - loaded = false - signals.forEach(function (sig) { - try { - process.removeListener(sig, sigListeners[sig]) - } catch (er) {} - }) - process.emit = originalProcessEmit - process.reallyExit = originalProcessReallyExit - emitter.count -= 1 -} + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose -function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true - emitter.emit(event, code, signal) -} + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) -// { : , ... } -var sigListeners = {} -signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process.listeners(sig) - if (listeners.length === emitter.count) { - unload() - emit('exit', null, sig) - /* istanbul ignore next */ - emit('afterexit', null, sig) - /* istanbul ignore next */ - if (isWin && sig === 'SIGHUP') { - // "SIGHUP" throws an `ENOSYS` error on Windows, - // so use a supported signal instead - sig = 'SIGINT' - } - process.kill(process.pid, sig) - } + if (!m) { + throw new TypeError('Invalid Version: ' + version) } -}) - -module.exports.signals = function () { - return signals -} -module.exports.load = load + this.raw = version -var loaded = false + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -function load () { - if (loaded) { - return + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - loaded = true - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1 + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } - signals = signals.filter(function (sig) { - try { - process.on(sig, sigListeners[sig]) - return true - } catch (er) { - return false - } - }) + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } - process.emit = processEmit - process.reallyExit = processReallyExit -} + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } -var originalProcessReallyExit = process.reallyExit -function processReallyExit (code) { - process.exitCode = code || 0 - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - /* istanbul ignore next */ - originalProcessReallyExit.call(process, process.exitCode) + this.build = m[5] ? m[5].split('.') : [] + this.format() } -var originalProcessEmit = process.emit -function processEmit (ev, arg) { - if (ev === 'exit') { - if (arg !== undefined) { - process.exitCode = arg - } - var ret = originalProcessEmit.apply(this, arguments) - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - return ret - } else { - return originalProcessEmit.apply(this, arguments) +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') } + return this.version } +SemVer.prototype.toString = function () { + return this.version +} -/***/ }), -/* 261 */, -/* 262 */, -/* 263 */, -/* 264 */, -/* 265 */, -/* 266 */, -/* 267 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -"use strict"; -/*:nodoc:* - * class ActionStoreConstant - * - * This action stores the value specified by the const keyword argument. - * (Note that the const keyword argument defaults to the rather unhelpful null.) - * The 'store_const' action is most commonly used with optional - * arguments that specify some sort of flag. - * - * This class inherited from [[Action]] - **/ + return this.compareMain(other) || this.comparePre(other) +} +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -var util = __webpack_require__(669); + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} -var Action = __webpack_require__(380); +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -/*:nodoc:* - * new ActionStoreConstant(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { - options = options || {}; - options.nargs = 0; - if (typeof options.constant === 'undefined') { - throw new Error('constant option is required for storeAction'); + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } - Action.call(this, options); -}; -util.inherits(ActionStoreConstant, Action); - -/*:nodoc:* - * ActionStoreConstant#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionStoreConstant.prototype.call = function (parser, namespace) { - namespace.set(this.dest, this.constant); -}; + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} -/***/ }), -/* 268 */, -/* 269 */, -/* 270 */, -/* 271 */, -/* 272 */, -/* 273 */, -/* 274 */, -/* 275 */, -/* 276 */, -/* 277 */, -/* 278 */, -/* 279 */, -/* 280 */ -/***/ (function(module) { +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break -module.exports = register + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break -function register (state, name, method, options) { - if (typeof method !== 'function') { - throw new Error('method for before hook must be a function') + default: + throw new Error('invalid increment argument: ' + release) } + this.format() + this.raw = this.version + return this +} - if (!options) { - options = {} +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined } - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options) - }, method)() + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null } +} - return Promise.resolve() - .then(function () { - if (!state.registry[name]) { - return method(options) +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } } - - return (state.registry[name]).reduce(function (method, registered) { - return registered.hook.bind(null, method, options) - }, method)() - }) + } + return defaultResult // may be undefined + } } +exports.compareIdentifiers = compareIdentifiers -/***/ }), -/* 281 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) -"use strict"; + if (anum && bnum) { + a = +a + b = +b + } -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 }); -const internal_globber_1 = __webpack_require__(297); -/** - * Constructs a globber - * - * @param patterns Patterns separated by newlines - * @param options Glob options - */ -function create(patterns, options) { - return __awaiter(this, void 0, void 0, function* () { - return yield internal_globber_1.DefaultGlobber.create(patterns, options); - }); + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -exports.create = create; -//# sourceMappingURL=glob.js.map -/***/ }), -/* 282 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} -"use strict"; -/** internal - * class MutuallyExclusiveGroup - * - * Group arguments. - * By default, ArgumentParser groups command-line arguments - * into “positional arguments” and “optional arguments” - * when displaying help messages. When there is a better - * conceptual grouping of arguments than this default one, - * appropriate groups can be created using the addArgumentGroup() method - * - * This class inherited from [[ArgumentContainer]] - **/ +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} -var util = __webpack_require__(669); +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} -var ArgumentGroup = __webpack_require__(65); +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} -/** - * new MutuallyExclusiveGroup(container, options) - * - container (object): main container - * - options (object): options.required -> true/false - * - * `required` could be an argument itself, but making it a property of - * the options argument is more consistent with the JS adaptation of the Python) - **/ -var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { - var required; - options = options || {}; - required = options.required || false; - ArgumentGroup.call(this, container); - this.required = required; +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} -}; -util.inherits(MutuallyExclusiveGroup, ArgumentGroup); +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} -MutuallyExclusiveGroup.prototype._addAction = function (action) { - var msg; - if (action.required) { - msg = 'mutually exclusive arguments must be optional'; - throw new Error(msg); - } - action = this._container._addAction(action); - this._groupActions.push(action); - return action; -}; +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} -MutuallyExclusiveGroup.prototype._removeAction = function (action) { - this._container._removeAction(action); - this._groupActions.remove(action); -}; +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} -/***/ }), -/* 283 */, -/* 284 */ -/***/ (function(module) { +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} -"use strict"; +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b - var r = range(a, b, str); + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} + case '': + case '=': + case '==': + return eq(a, b, loose) -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + case '!=': + return neq(a, b, loose) -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; + case '>': + return gt(a, b, loose) - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; + case '>=': + return gte(a, b, loose) - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } + case '<': + return lt(a, b, loose) - bi = str.indexOf(b, i + 1); - } + case '<=': + return lte(a, b, loose) - i = ai < bi && ai >= 0 ? ai : bi; + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } + } - if (begs.length) { - result = [ left, right ]; + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value } } - return result; + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) } +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) -/***/ }), -/* 285 */, -/* 286 */, -/* 287 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } -"use strict"; + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} +Comparator.prototype.toString = function () { + return this.value +} -var format = __webpack_require__(669).format; +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + if (this.semver === ANY) { + return true + } -var ERR_CODE = 'ARGError'; + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } -/*:nodoc:* - * argumentError(argument, message) -> TypeError - * - argument (Object): action with broken argument - * - message (String): error message - * - * Error format helper. An error from creating or using an argument - * (optional or positional). The string value of this exception - * is the message, augmented with information - * about the argument that caused it. - * - * #####Example - * - * var argumentErrorHelper = require('./argument/error'); - * if (conflictOptionals.length > 0) { - * throw argumentErrorHelper( - * action, - * format('Conflicting option string(s): %s', conflictOptionals.join(', ')) - * ); - * } - * - **/ -module.exports = function (argument, message) { - var argumentName = null; - var errMessage; - var err; + return cmp(version, this.operator, this.semver, this.options) +} - if (argument.getName) { - argumentName = argument.getName(); - } else { - argumentName = '' + argument; +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') } - if (!argumentName) { - errMessage = message; - } else { - errMessage = format('argument "%s": %s', argumentName, message); + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - err = new TypeError(errMessage); - err.code = ERR_CODE; - return err; -}; + var rangeTmp + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } -/***/ }), -/* 288 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) -"use strict"; -/*:nodoc:* - * class ActionAppendConstant - * - * This stores a list, and appends the value specified by - * the const keyword argument to the list. - * (Note that the const keyword argument defaults to null.) - * The 'appendConst' action is typically useful when multiple - * arguments need to store constants to the same list. - * - * This class inherited from [[Action]] - **/ + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } -var util = __webpack_require__(669); + if (range instanceof Comparator) { + return new Range(range.value, options) + } -var Action = __webpack_require__(380); + if (!(this instanceof Range)) { + return new Range(range, options) + } -/*:nodoc:* - * new ActionAppendConstant(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { - options = options || {}; - options.nargs = 0; - if (typeof options.constant === 'undefined') { - throw new Error('constant option is required for appendAction'); + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) } - Action.call(this, options); -}; -util.inherits(ActionAppendConstant, Action); -/*:nodoc:* - * ActionAppendConstant#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionAppendConstant.prototype.call = function (parser, namespace) { - var items = [].concat(namespace[this.dest] || []); - items.push(this.constant); - namespace.set(this.dest, items); -}; + this.format() +} +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} -/***/ }), -/* 289 */, -/* 290 */, -/* 291 */, -/* 292 */, -/* 293 */, -/* 294 */, -/* 295 */, -/* 296 */, -/* 297 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +Range.prototype.toString = function () { + return this.range +} -"use strict"; +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) -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 __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } -var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __webpack_require__(393); -const fs = __webpack_require__(747); -const globOptionsHelper = __webpack_require__(601); -const path = __webpack_require__(622); -const patternHelper = __webpack_require__(597); -const internal_match_kind_1 = __webpack_require__(36); -const internal_pattern_1 = __webpack_require__(923); -const internal_search_state_1 = __webpack_require__(728); -const IS_WINDOWS = process.platform === 'win32'; -class DefaultGlobber { - constructor(options) { - this.patterns = []; - this.searchPaths = []; - this.options = globOptionsHelper.getOptions(options); - } - getSearchPaths() { - // Return a copy - return this.searchPaths.slice(); - } - glob() { - var e_1, _a; - return __awaiter(this, void 0, void 0, function* () { - const result = []; - try { - for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { - const itemPath = _c.value; - result.push(itemPath); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - return result; - }); - } - globGenerator() { - return __asyncGenerator(this, arguments, function* globGenerator_1() { - // Fill in defaults options - const options = globOptionsHelper.getOptions(this.options); - // Implicit descendants? - const patterns = []; - for (const pattern of this.patterns) { - patterns.push(pattern); - if (options.implicitDescendants && - (pattern.trailingSeparator || - pattern.segments[pattern.segments.length - 1] !== '**')) { - patterns.push(new internal_pattern_1.Pattern(pattern.negate, pattern.segments.concat('**'))); - } - } - // Push the search paths - const stack = []; - for (const searchPath of patternHelper.getSearchPaths(patterns)) { - core.debug(`Search path '${searchPath}'`); - // Exists? - try { - // Intentionally using lstat. Detection for broken symlink - // will be performed later (if following symlinks). - yield __await(fs.promises.lstat(searchPath)); - } - catch (err) { - if (err.code === 'ENOENT') { - continue; - } - throw err; - } - stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); - } - // Search - const traversalChain = []; // used to detect cycles - while (stack.length) { - // Pop - const item = stack.pop(); - // Match? - const match = patternHelper.match(patterns, item.path); - const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); - if (!match && !partialMatch) { - continue; - } - // Stat - const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) - // Broken symlink, or symlink cycle detected, or no longer exists - ); - // Broken symlink, or symlink cycle detected, or no longer exists - if (!stats) { - continue; - } - // Directory - if (stats.isDirectory()) { - // Matched - if (match & internal_match_kind_1.MatchKind.Directory) { - yield yield __await(item.path); - } - // Descend? - else if (!partialMatch) { - continue; - } - // Push the child items in reverse - const childLevel = item.level + 1; - const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); - stack.push(...childItems.reverse()); - } - // File - else if (match & internal_match_kind_1.MatchKind.File) { - yield yield __await(item.path); - } - } - }); - } - /** - * Constructs a DefaultGlobber - */ - static create(patterns, options) { - return __awaiter(this, void 0, void 0, function* () { - const result = new DefaultGlobber(options); - if (IS_WINDOWS) { - patterns = patterns.replace(/\r\n/g, '\n'); - patterns = patterns.replace(/\r/g, '\n'); - } - const lines = patterns.split('\n').map(x => x.trim()); - for (const line of lines) { - // Empty or comment - if (!line || line.startsWith('#')) { - continue; - } - // Pattern - else { - result.patterns.push(new internal_pattern_1.Pattern(line)); - } - } - result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); - return result; - }); - } - static stat(item, options, traversalChain) { - return __awaiter(this, void 0, void 0, function* () { - // Note: - // `stat` returns info about the target of a symlink (or symlink chain) - // `lstat` returns info about a symlink itself - let stats; - if (options.followSymbolicLinks) { - try { - // Use `stat` (following symlinks) - stats = yield fs.promises.stat(item.path); - } - catch (err) { - if (err.code === 'ENOENT') { - if (options.omitBrokenSymbolicLinks) { - core.debug(`Broken symlink '${item.path}'`); - return undefined; - } - throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); - } - throw err; - } - } - else { - // Use `lstat` (not following symlinks) - stats = yield fs.promises.lstat(item.path); - } - // Note, isDirectory() returns false for the lstat of a symlink - if (stats.isDirectory() && options.followSymbolicLinks) { - // Get the realpath - const realPath = yield fs.promises.realpath(item.path); - // Fixup the traversal chain to match the item level - while (traversalChain.length >= item.level) { - traversalChain.pop(); - } - // Test for a cycle - if (traversalChain.some((x) => x === realPath)) { - core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); - return undefined; - } - // Update the traversal chain - traversalChain.push(realPath); - } - return stats; - }); - } -} -exports.DefaultGlobber = DefaultGlobber; -//# sourceMappingURL=internal-globber.js.map - -/***/ }), -/* 298 */, -/* 299 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -const VERSION = "2.2.3"; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ -function normalizePaginatedListResponse(response) { - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) - 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; + // normalize spaces + range = range.split(/\s+/).join(' ') - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } + // At this point, the range is completely trimmed and + // ready to be split into comparators. - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) - response.data.total_count = totalCount; - return response; -} - -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]: () => ({ - next() { - if (!url) { - return Promise.resolve({ - done: true - }); - } - - return requestMethod({ - method, - url, - headers - }).then(normalizePaginatedListResponse).then(response => { - // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: response - }; - }); - } - - }) - }; + return set } -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') } - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) } -function gather(octokit, results, iterator, mapFn) { - return iterator.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, iterator, mapFn); - }); +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) } -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp } -paginateRest.VERSION = VERSION; - -exports.paginateRest = paginateRest; -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 300 */, -/* 301 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = rimraf -rimraf.sync = rimrafSync -var assert = __webpack_require__(357) -var path = __webpack_require__(622) -var fs = __webpack_require__(747) -var glob = undefined -try { - glob = __webpack_require__(402) -} catch (_err) { - // treat glob as optional. +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' } -var _0666 = parseInt('666', 8) -var defaultGlobOpts = { - nosort: true, - silent: true +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') } -// for EMFILE handling -var timeout = 0 +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret -var isWindows = (process.platform === "win32") + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] + debug('tilde return', ret) + return ret }) - - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts } -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - var busyTries = 0 - var errState = null - var n = 0 +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret - options.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } - glob(p, options.glob, afterGlob) + debug('caret return', ret) + return ret }) +} - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} - function afterGlob (er, results) { - if (er) - return cb(er) +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp - n = results.length - if (n === 0) - return cb() + if (gtlt === '=' && anyX) { + gtlt = '' + } - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } - - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 - // already gone - if (er.code === "ENOENT") er = null + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 } + } - timeout = 0 - next(er) - }) - }) + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to } + + return (from + ' ' + to).trim() } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue } - return cb(er) - }) - }) -} -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } - options.chmod(p, _0666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} + // Version has a -pre, but it's not one of the ones we like. + return false + } -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) + return true +} +exports.satisfies = satisfies +function satisfies (version, range, options) { try { - options.chmodSync(p, _0666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er + range = new Range(range, options) + } catch (er) { + return false } + return range.test(version) +} +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er + var rangeObj = new Range(range, options) + } catch (er) { + return null } - - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max } -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} - -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } }) + return min } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - var results +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver } - if (!results.length) - return - - for (var i = 0; i < results.length; i++) { - var p = results[i] - - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } - rmdirSync(p, options, er) - } + if (minver && range.test(minver)) { + return minver } -} -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) + return null +} +exports.validRange = validRange +function validRange (range, options) { try { - options.rmdirSync(p) + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) + return null } } -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - var retries = isWindows ? 100 : 1 - var i = 0 - do { - var threw = true - try { - var ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) } +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) -/***/ }), -/* 302 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } -var fs = __webpack_require__(747) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(117) + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} + var high = null + var low = null -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - }) -} - -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } } + return true } -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) } +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } -/***/ }), -/* 303 */, -/* 304 */, -/* 305 */, -/* 306 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var concatMap = __webpack_require__(896); -var balanced = __webpack_require__(284); + if (typeof version !== 'string') { + return null + } -module.exports = expandTop; + var match = version.match(re[COERCE]) -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; + if (match == null) { + return null + } -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} +/***/ }), +/* 281 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { +"use strict"; -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +var __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 }); +const internal_globber_1 = __webpack_require__(297); +/** + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); +} +exports.create = create; +//# sourceMappingURL=glob.js.map - var parts = []; - var m = balanced('{', '}', str); +/***/ }), +/* 282 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (!m) - return str.split(','); +"use strict"; +/** internal + * class MutuallyExclusiveGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } +var util = __webpack_require__(669); - parts.push.apply(parts, p); +var ArgumentGroup = __webpack_require__(65); - return parts; -} +/** + * new MutuallyExclusiveGroup(container, options) + * - container (object): main container + * - options (object): options.required -> true/false + * + * `required` could be an argument itself, but making it a property of + * the options argument is more consistent with the JS adaptation of the Python) + **/ +var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { + var required; + options = options || {}; + required = options.required || false; + ArgumentGroup.call(this, container); + this.required = required; -function expandTop(str) { - if (!str) - return []; +}; +util.inherits(MutuallyExclusiveGroup, ArgumentGroup); - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); + +MutuallyExclusiveGroup.prototype._addAction = function (action) { + var msg; + if (action.required) { + msg = 'mutually exclusive arguments must be optional'; + throw new Error(msg); } + action = this._container._addAction(action); + this._groupActions.push(action); + return action; +}; - return expand(escapeBraces(str), true).map(unescapeBraces); -} -function identity(e) { - return e; -} +MutuallyExclusiveGroup.prototype._removeAction = function (action) { + this._container._removeAction(action); + this._groupActions.remove(action); +}; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} -function expand(str, isTop) { - var expansions = []; +/***/ }), +/* 283 */, +/* 284 */ +/***/ (function(module) { - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } +"use strict"; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + var r = range(a, b, str); - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - var N; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - N = []; + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } + + bi = str.indexOf(b, i + 1); } - N.push(c); + + i = ai < bi && ai >= 0 ? ai : bi; } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + if (begs.length) { + result = [ left, right ]; } } - return expansions; + return result; } - /***/ }), -/* 307 */, -/* 308 */, -/* 309 */, -/* 310 */, -/* 311 */, -/* 312 */ +/* 285 */, +/* 286 */, +/* 287 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -var common = __webpack_require__(740); -var Type = __webpack_require__(945); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); -function resolveYamlFloat(data) { - if (data === null) return false; +var format = __webpack_require__(669).format; - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - return true; -} +var ERR_CODE = 'ARGError'; -function constructYamlFloat(data) { - var value, sign, base, digits; +/*:nodoc:* + * argumentError(argument, message) -> TypeError + * - argument (Object): action with broken argument + * - message (String): error message + * + * Error format helper. An error from creating or using an argument + * (optional or positional). The string value of this exception + * is the message, augmented with information + * about the argument that caused it. + * + * #####Example + * + * var argumentErrorHelper = require('./argument/error'); + * if (conflictOptionals.length > 0) { + * throw argumentErrorHelper( + * action, + * format('Conflicting option string(s): %s', conflictOptionals.join(', ')) + * ); + * } + * + **/ +module.exports = function (argument, message) { + var argumentName = null; + var errMessage; + var err; - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; + if (argument.getName) { + argumentName = argument.getName(); + } else { + argumentName = '' + argument; + } - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); + if (!argumentName) { + errMessage = message; + } else { + errMessage = format('argument "%s": %s', argumentName, message); } - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + err = new TypeError(errMessage); + err.code = ERR_CODE; + return err; +}; - } else if (value === '.nan') { - return NaN; - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); +/***/ }), +/* 288 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - value = 0.0; - base = 1; +"use strict"; +/*:nodoc:* + * class ActionAppendConstant + * + * This stores a list, and appends the value specified by + * the const keyword argument to the list. + * (Note that the const keyword argument defaults to null.) + * The 'appendConst' action is typically useful when multiple + * arguments need to store constants to the same list. + * + * This class inherited from [[Action]] + **/ - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); - return sign * value; - } - return sign * parseFloat(value, 10); -} +var util = __webpack_require__(669); +var Action = __webpack_require__(380); -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; +/*:nodoc:* + * new ActionAppendConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { + options = options || {}; + options.nargs = 0; + if (typeof options.constant === 'undefined') { + throw new Error('constant option is required for appendAction'); + } + Action.call(this, options); +}; +util.inherits(ActionAppendConstant, Action); -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); - - -/***/ }), -/* 313 */, -/* 314 */, -/* 315 */ -/***/ (function(module) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - - -/***/ }), -/* 316 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -const core = __webpack_require__(393); - -function getWorkflowfileName() { - return core.getInput("workflow-file-name"); -} - -module.exports = { - getWorkflowfileName +/*:nodoc:* + * ActionAppendConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppendConstant.prototype.call = function (parser, namespace) { + var items = [].concat(namespace[this.dest] || []); + items.push(this.constant); + namespace.set(this.dest, items); }; /***/ }), -/* 317 */, -/* 318 */, -/* 319 */, -/* 320 */, -/* 321 */, -/* 322 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const u = __webpack_require__(676).fromPromise -const fs = __webpack_require__(869) - -function pathExists (path) { - return fs.access(path).then(() => true).catch(() => false) -} - -module.exports = { - pathExists: u(pathExists), - pathExistsSync: fs.existsSync -} - - -/***/ }), -/* 323 */ -/***/ (function(module) { +/* 289 */, +/* 290 */, +/* 291 */, +/* 292 */, +/* 293 */, +/* 294 */, +/* 295 */, +/* 296 */, +/* 297 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var isStream = module.exports = function (stream) { - return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; -}; - -isStream.writable = function (stream) { - return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; -}; - -isStream.readable = function (stream) { - return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; +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()); + }); }; - -isStream.duplex = function (stream) { - return isStream.writable(stream) && isStream.readable(stream); +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; - -isStream.transform = function (stream) { - return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; - - -/***/ }), -/* 324 */, -/* 325 */, -/* 326 */, -/* 327 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -const VERSION = "1.0.0"; - -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - -function requestLog(octokit) { - octokit.hook.wrap("request", (request, options) => { - octokit.log.debug("request", options); - const start = Date.now(); - const requestOptions = octokit.request.endpoint.parse(options); - const path = requestOptions.url.replace(options.baseUrl, ""); - return request(options).then(response => { - octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`); - return response; - }).catch(error => { - octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`); - throw error; - }); - }); -} -requestLog.VERSION = VERSION; - -exports.requestLog = requestLog; -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 328 */, -/* 329 */, -/* 330 */, -/* 331 */, -/* 332 */, -/* 333 */, -/* 334 */, -/* 335 */, -/* 336 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; +const core = __webpack_require__(393); +const fs = __webpack_require__(747); +const globOptionsHelper = __webpack_require__(601); +const path = __webpack_require__(622); +const patternHelper = __webpack_require__(597); +const internal_match_kind_1 = __webpack_require__(36); +const internal_pattern_1 = __webpack_require__(923); +const internal_search_state_1 = __webpack_require__(728); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -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) { - options.headers['Authorization'] = 'Bearer ' + this.token; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -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) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + glob() { + var e_1, _a; + return __awaiter(this, void 0, void 0, function* () { + const result = []; + try { + for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { + const itemPath = _c.value; + result.push(itemPath); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return result; + }); } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - - -/***/ }), -/* 337 */, -/* 338 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const assert = __webpack_require__(357); -const path = __webpack_require__(622); -const pathHelper = __webpack_require__(972); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Helper class for parsing paths into segments - */ -class Path { - /** - * Constructs a Path - * @param itemPath Path or array of segments - */ - constructor(itemPath) { - this.segments = []; - // String - if (typeof itemPath === 'string') { - assert(itemPath, `Parameter 'itemPath' must not be empty`); - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // Not rooted - if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path.sep); + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, pattern.segments.concat('**'))); + } } - // Rooted - else { - // Add all segments, while not at the root - let remaining = itemPath; - let dir = pathHelper.dirname(remaining); - while (dir !== remaining) { - // Add the segment - const basename = path.basename(remaining); - this.segments.unshift(basename); - // Truncate the last segment - remaining = dir; - dir = pathHelper.dirname(remaining); + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); } - // Remainder is the root - this.segments.unshift(remaining); + catch (err) { + if (err.code === 'ENOENT') { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); } - } - // Array - else { - // Must not be empty - assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); - // Each segment - for (let i = 0; i < itemPath.length; i++) { - let segment = itemPath[i]; - // Must not be empty - assert(segment, `Parameter 'itemPath' must not contain any empty segments`); - // Normalize slashes - segment = pathHelper.normalizeSeparators(itemPath[i]); - // Root segment - if (i === 0 && pathHelper.hasRoot(segment)) { - segment = pathHelper.safeTrimTrailingSeparator(segment); - assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); - this.segments.push(segment); + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; } - // All other segments - else { - // Must not contain slash - assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); - this.segments.push(segment); + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); } } - } + }); } /** - * Converts the path to it's string representation + * Constructs a DefaultGlobber */ - toString() { - // First segment - let result = this.segments[0]; - // All others - let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); - for (let i = 1; i < this.segments.length; i++) { - if (skipSlash) { - skipSlash = false; + static create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); } - else { - result += path.sep; + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } } - result += this.segments[i]; - } - return result; + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; + }); } -} -exports.Path = Path; -//# sourceMappingURL=internal-path.js.map - -/***/ }), -/* 339 */, -/* 340 */, -/* 341 */, -/* 342 */, -/* 343 */, -/* 344 */, -/* 345 */, -/* 346 */, -/* 347 */, -/* 348 */, -/* 349 */, -/* 350 */, -/* 351 */, -/* 352 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/*:nodoc:* - * class ActionStore - * - * This action just stores the argument’s value. This is the default action. - * - * This class inherited from [[Action]] - * - **/ + static stat(item, options, traversalChain) { + return __awaiter(this, void 0, void 0, function* () { + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); + } + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; + }); + } +} +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map +/***/ }), +/* 298 */, +/* 299 */ +/***/ (function(__unusedmodule, exports) { -var util = __webpack_require__(669); +"use strict"; -var Action = __webpack_require__(380); -// Constants -var c = __webpack_require__(45); +Object.defineProperty(exports, '__esModule', { value: true }); +const VERSION = "2.4.0"; -/*:nodoc:* - * new ActionStore(options) - * - options (object): options hash see [[Action.new]] +/** + * Some “list” response that can be paginated have a different response structure * - **/ -var ActionStore = module.exports = function ActionStore(options) { - options = options || {}; - if (this.nargs <= 0) { - throw new Error('nargs for store actions must be > 0; if you ' + - 'have nothing to store, actions such as store ' + - 'true or store const may be more appropriate'); + * They have a `total_count` key in the response (search also has `incomplete_results`, + * /installation/repositories also has `repository_selection`), as well as a key with + * the list of the items which name varies from endpoint to endpoint. + * + * Octokit normalizes these responses so that paginated results are always returned following + * the same structure. One challenge is that if the list response has only one page, no Link + * header is provided, so this header alone is not sufficient to check wether a response is + * paginated or not. + * + * We check if a "total_count" key is present in the response data, but also make sure that + * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would + * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref + */ +function normalizePaginatedListResponse(response) { + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way + // to retrieve the same information. + + 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 this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) { - throw new Error('nargs must be OPTIONAL to supply const'); + + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; } - Action.call(this, options); -}; -util.inherits(ActionStore, Action); -/*:nodoc:* - * ActionStore#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionStore.prototype.call = function (parser, namespace, values) { - namespace.set(this.dest, values); -}; + response.data.total_count = totalCount; + return response; +} +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]: () => ({ + next() { + if (!url) { + return Promise.resolve({ + done: true + }); + } -/***/ }), -/* 353 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + return requestMethod({ + method, + url, + headers + }).then(normalizePaginatedListResponse).then(response => { + // `response.headers.link` format: + // '; rel="next", ; rel="last"' + // sets `url` to undefined if "next" URL is not present or `link` header is not set + url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: response + }; + }); + } -"use strict"; + }) + }; +} +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } -const u = __webpack_require__(676).fromCallback -module.exports = { - move: u(__webpack_require__(500)) + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); } +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; + } -/***/ }), -/* 354 */, -/* 355 */, -/* 356 */ -/***/ (function(module) { + let earlyExit = false; -function stringify (obj, options = {}) { - const EOL = options.EOL || '\n' + function done() { + earlyExit = true; + } - const str = JSON.stringify(obj, options ? options.replacer : null, options.spaces) + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - return str.replace(/\n/g, EOL) + EOL + if (earlyExit) { + return results; + } + + return gather(octokit, results, iterator, mapFn); + }); } -function stripBom (content) { - // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified - if (Buffer.isBuffer(content)) content = content.toString('utf8') - return content.replace(/^\uFEFF/, '') +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } +paginateRest.VERSION = VERSION; -module.exports = { stringify, stripBom } +exports.paginateRest = paginateRest; +//# sourceMappingURL=index.js.map /***/ }), -/* 357 */ -/***/ (function(module) { +/* 300 */, +/* 301 */, +/* 302 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = require("assert"); +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch -/***/ }), -/* 358 */, -/* 359 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +var fs = __webpack_require__(747) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(393)); -const upload_specification_1 = __webpack_require__(590); -const upload_http_client_1 = __webpack_require__(888); -const utils_1 = __webpack_require__(870); -const download_http_client_1 = __webpack_require__(855); -const download_specification_1 = __webpack_require__(828); -const config_variables_1 = __webpack_require__(401); -const path_1 = __webpack_require__(622); -class DefaultArtifactClient { - /** - * Constructs a DefaultArtifactClient - */ - static create() { - return new DefaultArtifactClient(); - } - /** - * Uploads an artifact - */ - uploadArtifact(name, files, rootDirectory, options) { - return __awaiter(this, void 0, void 0, function* () { - utils_1.checkArtifactName(name); - // Get specification for the files being uploaded - const uploadSpecification = upload_specification_1.getUploadSpecification(name, rootDirectory, files); - const uploadResponse = { - artifactName: name, - artifactItems: [], - size: 0, - failedItems: [] - }; - const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); - if (uploadSpecification.length === 0) { - core.warning(`No files found that can be uploaded`); - } - else { - // Create an entry for the artifact in the file container - const response = yield uploadHttpClient.createArtifactInFileContainer(name); - if (!response.fileContainerResourceUrl) { - core.debug(response.toString()); - throw new Error('No URL provided by the Artifact Service to upload an artifact to'); - } - core.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); - // Upload each of the files that were found concurrently - const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); - // Update the size of the artifact to indicate we are done uploading - // The uncompressed size is used for display when downloading a zip of the artifact from the UI - yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); - core.info(`Finished uploading artifact ${name}. Reported size is ${uploadResult.uploadSize} bytes. There were ${uploadResult.failedItems.length} items that failed to upload`); - uploadResponse.artifactItems = uploadSpecification.map(item => item.absoluteFilePath); - uploadResponse.size = uploadResult.uploadSize; - uploadResponse.failedItems = uploadResult.failedItems; - } - return uploadResponse; - }); - } - downloadArtifact(name, path, options) { - return __awaiter(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - throw new Error(`Unable to find any artifacts for the associated workflow`); - } - const artifactToDownload = artifacts.value.find(artifact => { - return artifact.name === name; - }); - if (!artifactToDownload) { - throw new Error(`Unable to find an artifact with the name: ${name}`); - } - const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); - if (!path) { - path = config_variables_1.getWorkSpaceDirectory(); - } - path = path_1.normalize(path); - path = path_1.resolve(path); - // During upload, empty directories are rejected by the remote server so there should be no artifacts that consist of only empty directories - const downloadSpecification = download_specification_1.getDownloadSpecification(name, items.value, path, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); - if (downloadSpecification.filesToDownload.length === 0) { - core.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); - } - else { - // Create all necessary directories recursively before starting any download - yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); - core.info('Directory structure has been setup for the artifact'); - yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); - } - return { - artifactName: name, - downloadPath: downloadSpecification.rootDownloadLocation - }; - }); - } - downloadAllArtifacts(path) { - return __awaiter(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const response = []; - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - core.info('Unable to find any artifacts for the associated workflow'); - return response; - } - if (!path) { - path = config_variables_1.getWorkSpaceDirectory(); - } - path = path_1.normalize(path); - path = path_1.resolve(path); - let downloadedArtifacts = 0; - while (downloadedArtifacts < artifacts.count) { - const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; - downloadedArtifacts += 1; - // Get container entries for the specific artifact - const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); - const downloadSpecification = download_specification_1.getDownloadSpecification(currentArtifactToDownload.name, items.value, path, true); - if (downloadSpecification.filesToDownload.length === 0) { - core.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); - } - else { - yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); - yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); - } - response.push({ - artifactName: currentArtifactToDownload.name, - downloadPath: downloadSpecification.rootDownloadLocation - }); - } - return response; - }); - } -} -exports.DefaultArtifactClient = DefaultArtifactClient; -//# sourceMappingURL=artifact-client.js.map - -/***/ }), -/* 360 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __webpack_require__(117) -const fse = __webpack_require__(226); -const fs = __webpack_require__(747); +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} -const tmp = __webpack_require__(150); -const yaml = __webpack_require__(414); -const { logger } = __webpack_require__(79); +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } -function tmpdir(callback) { - async function handle(path) { - try { - return await callback(path); - } finally { - await fse.remove(path); - } + if (typeof cache === 'function') { + cb = cache + cache = null } - return new Promise((resolve, reject) => { - tmp.dir((err, path) => { - if (err) { - reject(err); - } else { - handle(path).then(resolve, reject); - } - }); - }); + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) } -function getYamlFileContent(filePath) { +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + try { - let fileContents = fs.readFileSync(filePath, "utf8"); - return yaml.safeLoad(fileContents); - } catch (e) { - logger.error(`error reading yaml file ${filePath}`, e); - throw e; + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } } } -module.exports = { - tmpdir, - getYamlFileContent -}; +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} + +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} /***/ }), -/* 361 */, -/* 362 */, -/* 363 */, -/* 364 */, -/* 365 */, -/* 366 */, -/* 367 */, -/* 368 */, -/* 369 */, -/* 370 */, -/* 371 */, -/* 372 */, -/* 373 */, -/* 374 */, -/* 375 */, -/* 376 */, -/* 377 */, -/* 378 */ +/* 303 */, +/* 304 */, +/* 305 */, +/* 306 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; -/*:nodoc:* - * class ActionAppend - * - * This action stores a list, and appends each argument value to the list. - * This is useful to allow an option to be specified multiple times. - * This class inherided from [[Action]] - * - **/ - +var concatMap = __webpack_require__(896); +var balanced = __webpack_require__(284); +module.exports = expandTop; -var util = __webpack_require__(669); +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -var Action = __webpack_require__(380); +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} -// Constants -var c = __webpack_require__(45); - -/*:nodoc:* - * new ActionAppend(options) - * - options (object): options hash see [[Action.new]] - * - * Note: options.nargs should be optional for constants - * and more then zero for other - **/ -var ActionAppend = module.exports = function ActionAppend(options) { - options = options || {}; - if (this.nargs <= 0) { - throw new Error('nargs for append actions must be > 0; if arg ' + - 'strings are not supplying the value to append, ' + - 'the append const action may be more appropriate'); - } - if (!!this.constant && this.nargs !== c.OPTIONAL) { - throw new Error('nargs must be OPTIONAL to supply const'); - } - Action.call(this, options); -}; -util.inherits(ActionAppend, Action); - -/*:nodoc:* - * ActionAppend#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionAppend.prototype.call = function (parser, namespace, values) { - var items = (namespace[this.dest] || []).slice(); - items.push(values); - namespace.set(this.dest, items); -}; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} -/***/ }), -/* 379 */, -/* 380 */ -/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; -/** - * class Action - * - * Base class for all actions - * Do not call in your code, use this class only for inherits your own action - * - * Information about how to convert command line strings to Javascript objects. - * Action objects are used by an ArgumentParser to represent the information - * needed to parse a single argument from one or more strings from the command - * line. The keyword arguments to the Action constructor are also all attributes - * of Action instances. - * - * ##### Allowed keywords: - * - * - `store` - * - `storeConstant` - * - `storeTrue` - * - `storeFalse` - * - `append` - * - `appendConstant` - * - `count` - * - `help` - * - `version` - * - * Information about action options see [[Action.new]] - * - * See also [original guide](http://docs.python.org/dev/library/argparse.html#action) - * - **/ +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + var parts = []; + var m = balanced('{', '}', str); + if (!m) + return str.split(','); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -// Constants -var c = __webpack_require__(45); + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); -/** - * new Action(options) - * - * Base class for all actions. Used only for inherits - * - * - * ##### Options: - * - * - `optionStrings` A list of command-line option strings for the action. - * - `dest` Attribute to hold the created object(s) - * - `nargs` The number of command-line arguments that should be consumed. - * By default, one argument will be consumed and a single value will be - * produced. - * - `constant` Default value for an action with no value. - * - `defaultValue` The value to be produced if the option is not specified. - * - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If - * None, 'string'. - * - `choices` The choices available. - * - `required` True if the action must always be specified at the command - * line. - * - `help` The help describing the argument. - * - `metavar` The name to be used for the option's argument with the help - * string. If None, the 'dest' value will be used as the name. - * - * ##### nargs supported values: - * - * - `N` (an integer) consumes N arguments (and produces a list) - * - `?` consumes zero or one arguments - * - `*` consumes zero or more arguments (and produces a list) - * - `+` consumes one or more arguments (and produces a list) - * - * Note: that the difference between the default and nargs=1 is that with the - * default, a single value will be produced, while with nargs=1, a list - * containing a single value will be produced. - **/ -var Action = module.exports = function Action(options) { - options = options || {}; - this.optionStrings = options.optionStrings || []; - this.dest = options.dest; - this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null; - this.constant = typeof options.constant !== 'undefined' ? options.constant : null; - this.defaultValue = options.defaultValue; - this.type = typeof options.type !== 'undefined' ? options.type : null; - this.choices = typeof options.choices !== 'undefined' ? options.choices : null; - this.required = typeof options.required !== 'undefined' ? options.required : false; - this.help = typeof options.help !== 'undefined' ? options.help : null; - this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null; + return parts; +} - if (!(this.optionStrings instanceof Array)) { - throw new Error('optionStrings should be an array'); - } - if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') { - throw new Error('required should be a boolean'); - } -}; +function expandTop(str) { + if (!str) + return []; -/** - * Action#getName -> String - * - * Tells action name - **/ -Action.prototype.getName = function () { - if (this.optionStrings.length > 0) { - return this.optionStrings.join('/'); - } else if (this.metavar !== null && this.metavar !== c.SUPPRESS) { - return this.metavar; - } else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) { - return this.dest; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - return null; -}; -/** - * Action#isOptional -> Boolean - * - * Return true if optional - **/ -Action.prototype.isOptional = function () { - return !this.isPositional(); -}; + return expand(escapeBraces(str), true).map(unescapeBraces); +} -/** - * Action#isPositional -> Boolean - * - * Return true if positional - **/ -Action.prototype.isPositional = function () { - return (this.optionStrings.length === 0); -}; +function identity(e) { + return e; +} -/** - * Action#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Should be implemented in inherited classes - * - * ##### Example - * - * ActionCount.prototype.call = function (parser, namespace, values, optionString) { - * namespace.set(this.dest, (namespace[this.dest] || 0) + 1); - * }; - * - **/ -Action.prototype.call = function () { - throw new Error('.call() not defined');// Not Implemented error -}; +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} -/***/ }), -/* 381 */, -/* 382 */, -/* 383 */ -/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { +function expand(str, isTop) { + var expansions = []; + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; -const process = __webpack_require__(765); + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } -const fse = __webpack_require__(226); -const { ArgumentParser } = __webpack_require__(470); -const { Octokit } = __webpack_require__(889); - -const { ClientError, logger } = __webpack_require__(79); -const { createConfig, createConfigLocally } = __webpack_require__(148); -const { executeGitHubAction } = __webpack_require__(650); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } -const pkg = __webpack_require__(731); + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. -async function main() { - const parser = new ArgumentParser({ - prog: pkg.name, - version: pkg.version, - addHelp: true, - description: pkg.description - }); - parser.addArgument(["-t", "--trace"], { - action: "storeTrue", - help: "Show trace output" - }); - parser.addArgument(["-d", "--debug"], { - action: "storeTrue", - help: "Show debugging output" - }); - parser.addArgument(["url"], { - metavar: "", - nargs: "?", - help: "GitHub URL to process instead of environment variables" - }); + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - const args = parser.parseArgs(); + var N; - if (args.trace) { - logger.level = "trace"; - } else if (args.debug) { - logger.level = "debug"; - } + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - const token = env("GITHUB_TOKEN"); - const octokit = new Octokit({ - auth: `token ${token}`, - userAgent: "kiegroup/github-build-chain-action" - }); + N = []; - let config = undefined; - if (args.url) { - config = await createConfigLocally(octokit, args.url, process.env); + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } } else { - const eventPath = env("GITHUB_EVENT_PATH"); - const eventDataStr = await fse.readFile(eventPath, "utf8"); - const eventData = JSON.parse(eventDataStr); - config = await createConfig(eventData, undefined, process.env); + N = concatMap(n, function(el) { return expand(el, false) }); } - const context = { token, octokit, config }; - await executeGitHubAction(context); -} - -function env(name) { - const val = process.env[name]; - if (!val || !val.length) { - throw new ClientError(`environment variable ${name} not set!`); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } } - return val; -} -if (require.main === require.cache[eval('__filename')]) { - main().catch(e => { - if (e instanceof ClientError) { - process.exitCode = 2; - logger.error(e); - } else { - process.exitCode = 1; - logger.error(e); - } - }); + return expansions; } -/***/ }), -/* 384 */, -/* 385 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { -"use strict"; +/***/ }), +/* 307 */, +/* 308 */, +/* 309 */, +/* 310 */, +/* 311 */, +/* 312 */, +/* 313 */, +/* 314 */, +/* 315 */ +/***/ (function(module) { +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} -Object.defineProperty(exports, '__esModule', { value: true }); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +/***/ }), +/* 316 */, +/* 317 */, +/* 318 */, +/* 319 */, +/* 320 */, +/* 321 */, +/* 322 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var isPlainObject = _interopDefault(__webpack_require__(626)); -var universalUserAgent = __webpack_require__(796); +"use strict"; -function lowercaseKeys(object) { - if (!object) { - return {}; - } +const u = __webpack_require__(676).fromPromise +const fs = __webpack_require__(869) - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); +function pathExists (path) { + return fs.access(path).then(() => true).catch(() => false) } -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; +module.exports = { + pathExists: u(pathExists), + pathExistsSync: fs.existsSync } -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); - } // lowercase header names before merging with defaults to avoid duplicates +/***/ }), +/* 323 */ +/***/ (function(module) { - options.headers = lowercaseKeys(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten +"use strict"; - 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; -} +var isStream = module.exports = function (stream) { + return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; +}; -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); +isStream.writable = function (stream) { + return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; +}; - if (names.length === 0) { - return url; - } +isStream.readable = function (stream) { + return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; +}; - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -const urlVariableRegex = /\{[^}]+\}/g; +isStream.duplex = function (stream) { + return isStream.writable(stream) && isStream.readable(stream); +}; -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} +isStream.transform = function (stream) { + return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +}; -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - if (!matches) { - return []; - } +/***/ }), +/* 324 */, +/* 325 */, +/* 326 */, +/* 327 */ +/***/ (function(__unusedmodule, exports) { - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} +"use strict"; -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +Object.defineProperty(exports, '__esModule', { value: true }); -/* istanbul ignore file */ -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, "]"); - } +const VERSION = "1.0.0"; - return part; - }).join(""); -} +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +function requestLog(octokit) { + octokit.hook.wrap("request", (request, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path = requestOptions.url.replace(options.baseUrl, ""); + return request(options).then(response => { + octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`); + return response; + }).catch(error => { + octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`); + throw error; + }); }); } +requestLog.VERSION = VERSION; -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 !== undefined && 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(); +exports.requestLog = requestLog; +//# sourceMappingURL=index.js.map - 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 (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; +/***/ }), +/* 328 */, +/* 329 */, +/* 330 */, +/* 331 */, +/* 332 */, +/* 333 */, +/* 334 */, +/* 335 */, +/* 336 */ +/***/ (function(__unusedmodule, exports) { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } +"use strict"; - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } +Object.defineProperty(exports, "__esModule", { value: true }); +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + + Buffer.from(this.username + ':' + this.password).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; } - } - - return result; } - -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; +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) { + options.headers['Authorization'] = 'Bearer ' + this.token; + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +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) { + options.headers['Authorization'] = + 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } } +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return 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); - } +/***/ }), +/* 337 */, +/* 338 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - 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 = ","; +"use strict"; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); + } + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); + } + } + // Array + else { + // Must not be empty + assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + assert(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } + // All other segments + else { + // Must not contain slash + assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } } - - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); } - }); + /** + * Converts the path to it's string representation + */ + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; + } } +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible +/***/ }), +/* 339 */, +/* 340 */, +/* 341 */, +/* 342 */, +/* 343 */, +/* 344 */, +/* 345 */, +/* 346 */, +/* 347 */, +/* 348 */, +/* 349 */, +/* 350 */, +/* 351 */, +/* 352 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - 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"]); // extract variable names from URL to calculate remaining variables later +"use strict"; +/*:nodoc:* + * class ActionStore + * + * This action just stores the argument’s value. This is the default action. + * + * This class inherited from [[Action]] + * + **/ - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } +var util = __webpack_require__(669); - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequset = /application\/octet-stream/i.test(headers.accept); +var Action = __webpack_require__(380); - if (!isBinaryRequset) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); - } +// Constants +var c = __webpack_require__(45); - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters +/*:nodoc:* + * new ActionStore(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStore = module.exports = function ActionStore(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for store actions must be > 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate'); - 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; - } else { - headers["content-length"] = 0; - } - } - } // default content-type for JSON if body is set + } + if (typeof this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionStore, Action); +/*:nodoc:* + * ActionStore#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStore.prototype.call = function (parser, namespace, values) { + namespace.set(this.dest, values); +}; - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string +/***/ }), +/* 353 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present +"use strict"; - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); +const u = __webpack_require__(676).fromCallback +module.exports = { + move: u(__webpack_require__(500)) } -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); + +/***/ }), +/* 354 */, +/* 355 */, +/* 356 */ +/***/ (function(module) { + +function stringify (obj, options = {}) { + const EOL = options.EOL || '\n' + + const str = JSON.stringify(obj, options ? options.replacer : null, options.spaces) + + return str.replace(/\n/g, EOL) + EOL } -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); +function stripBom (content) { + // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified + if (Buffer.isBuffer(content)) content = content.toString('utf8') + return content.replace(/^\uFEFF/, '') } -const VERSION = "6.0.3"; +module.exports = { stringify, stripBom } -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; +/***/ }), +/* 357 */ +/***/ (function(module) { -const endpoint = withDefaults(null, DEFAULTS); +module.exports = require("assert"); -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map +/***/ }), +/* 358 */, +/* 359 */ +/***/ (function(__unusedmodule, exports, __webpack_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()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(393)); +const upload_specification_1 = __webpack_require__(590); +const upload_http_client_1 = __webpack_require__(888); +const utils_1 = __webpack_require__(870); +const download_http_client_1 = __webpack_require__(855); +const download_specification_1 = __webpack_require__(828); +const config_variables_1 = __webpack_require__(401); +const path_1 = __webpack_require__(622); +class DefaultArtifactClient { + /** + * Constructs a DefaultArtifactClient + */ + static create() { + return new DefaultArtifactClient(); + } + /** + * Uploads an artifact + */ + uploadArtifact(name, files, rootDirectory, options) { + return __awaiter(this, void 0, void 0, function* () { + utils_1.checkArtifactName(name); + // Get specification for the files being uploaded + const uploadSpecification = upload_specification_1.getUploadSpecification(name, rootDirectory, files); + const uploadResponse = { + artifactName: name, + artifactItems: [], + size: 0, + failedItems: [] + }; + const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); + if (uploadSpecification.length === 0) { + core.warning(`No files found that can be uploaded`); + } + else { + // Create an entry for the artifact in the file container + const response = yield uploadHttpClient.createArtifactInFileContainer(name); + if (!response.fileContainerResourceUrl) { + core.debug(response.toString()); + throw new Error('No URL provided by the Artifact Service to upload an artifact to'); + } + core.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); + // Upload each of the files that were found concurrently + const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); + // Update the size of the artifact to indicate we are done uploading + // The uncompressed size is used for display when downloading a zip of the artifact from the UI + yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); + core.info(`Finished uploading artifact ${name}. Reported size is ${uploadResult.uploadSize} bytes. There were ${uploadResult.failedItems.length} items that failed to upload`); + uploadResponse.artifactItems = uploadSpecification.map(item => item.absoluteFilePath); + uploadResponse.size = uploadResult.uploadSize; + uploadResponse.failedItems = uploadResult.failedItems; + } + return uploadResponse; + }); + } + downloadArtifact(name, path, options) { + return __awaiter(this, void 0, void 0, function* () { + const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); + const artifacts = yield downloadHttpClient.listArtifacts(); + if (artifacts.count === 0) { + throw new Error(`Unable to find any artifacts for the associated workflow`); + } + const artifactToDownload = artifacts.value.find(artifact => { + return artifact.name === name; + }); + if (!artifactToDownload) { + throw new Error(`Unable to find an artifact with the name: ${name}`); + } + const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); + if (!path) { + path = config_variables_1.getWorkSpaceDirectory(); + } + path = path_1.normalize(path); + path = path_1.resolve(path); + // During upload, empty directories are rejected by the remote server so there should be no artifacts that consist of only empty directories + const downloadSpecification = download_specification_1.getDownloadSpecification(name, items.value, path, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); + if (downloadSpecification.filesToDownload.length === 0) { + core.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); + } + else { + // Create all necessary directories recursively before starting any download + yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); + core.info('Directory structure has been setup for the artifact'); + yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); + yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); + } + return { + artifactName: name, + downloadPath: downloadSpecification.rootDownloadLocation + }; + }); + } + downloadAllArtifacts(path) { + return __awaiter(this, void 0, void 0, function* () { + const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); + const response = []; + const artifacts = yield downloadHttpClient.listArtifacts(); + if (artifacts.count === 0) { + core.info('Unable to find any artifacts for the associated workflow'); + return response; + } + if (!path) { + path = config_variables_1.getWorkSpaceDirectory(); + } + path = path_1.normalize(path); + path = path_1.resolve(path); + let downloadedArtifacts = 0; + while (downloadedArtifacts < artifacts.count) { + const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; + downloadedArtifacts += 1; + // Get container entries for the specific artifact + const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); + const downloadSpecification = download_specification_1.getDownloadSpecification(currentArtifactToDownload.name, items.value, path, true); + if (downloadSpecification.filesToDownload.length === 0) { + core.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); + } + else { + yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); + yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); + yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); + } + response.push({ + artifactName: currentArtifactToDownload.name, + downloadPath: downloadSpecification.rootDownloadLocation + }); + } + return response; + }); + } +} +exports.DefaultArtifactClient = DefaultArtifactClient; +//# sourceMappingURL=artifact-client.js.map /***/ }), -/* 386 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 360 */, +/* 361 */, +/* 362 */, +/* 363 */ +/***/ (function(module) { -"use strict"; +module.exports = register +function register (state, name, method, options) { + if (typeof method !== 'function') { + throw new Error('method for before hook must be a function') + } -var Type = __webpack_require__(945); + if (!options) { + options = {} + } -function resolveJavascriptUndefined() { - return true; -} + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options) + }, method)() + } -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} + return Promise.resolve() + .then(function () { + if (!state.registry[name]) { + return method(options) + } -function representJavascriptUndefined() { - return ''; + return (state.registry[name]).reduce(function (method, registered) { + return registered.hook.bind(null, method, options) + }, method)() + }) } -function isUndefined(object) { - return typeof object === 'undefined'; -} -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); +/***/ }), +/* 364 */, +/* 365 */, +/* 366 */, +/* 367 */, +/* 368 */, +/* 369 */, +/* 370 */, +/* 371 */, +/* 372 */, +/* 373 */ +/***/ (function(module) { +module.exports = require("crypto"); /***/ }), -/* 387 */, -/* 388 */, -/* 389 */ +/* 374 */, +/* 375 */, +/* 376 */, +/* 377 */, +/* 378 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/*:nodoc:* + * class ActionAppend + * + * This action stores a list, and appends each argument value to the list. + * This is useful to allow an option to be specified multiple times. + * This class inherided from [[Action]] + * + **/ -const fs = __webpack_require__(747); -const shebangCommand = __webpack_require__(866); -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - let buffer; +var util = __webpack_require__(669); - if (Buffer.alloc) { - // Node.js v4.5+ / v5.10+ - buffer = Buffer.alloc(size); - } else { - // Old Node.js API - buffer = new Buffer(size); - buffer.fill(0); // zero-fill - } - - let fd; +var Action = __webpack_require__(380); - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } +// Constants +var c = __webpack_require__(45); - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} +/*:nodoc:* + * new ActionAppend(options) + * - options (object): options hash see [[Action.new]] + * + * Note: options.nargs should be optional for constants + * and more then zero for other + **/ +var ActionAppend = module.exports = function ActionAppend(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for append actions must be > 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate'); + } + if (!!this.constant && this.nargs !== c.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionAppend, Action); -module.exports = readShebang; +/*:nodoc:* + * ActionAppend#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppend.prototype.call = function (parser, namespace, values) { + var items = (namespace[this.dest] || []).slice(); + items.push(values); + namespace.set(this.dest, items); +}; /***/ }), -/* 390 */, -/* 391 */, -/* 392 */, -/* 393 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 379 */, +/* 380 */ +/***/ (function(module, __unusedexports, __webpack_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()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const command_1 = __webpack_require__(431); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -/** - * 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 || (exports.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 = command_1.toCommandValue(val); - process.env[name] = convertedVal; - 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) { - 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) { - command_1.issueCommand('add-path', {}, inputPath); - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; /** - * Gets the value of an input. The value is also trimmed. + * class Action * - * @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}`); - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Sets the value of an output. + * Base class for all actions + * Do not call in your code, use this class only for inherits your own action * - * @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) { - command_1.issueCommand('set-output', { name }, 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. + * Information about how to convert command line strings to Javascript objects. + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the command + * line. The keyword arguments to the Action constructor are also all attributes + * of Action instances. * - */ -function setCommandEcho(enabled) { - 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) { - 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() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() - */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * 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. + * ##### Allowed keywords: * - * Output until the next `groupEnd` will be foldable in this group + * - `store` + * - `storeConstant` + * - `storeTrue` + * - `storeFalse` + * - `append` + * - `appendConstant` + * - `count` + * - `help` + * - `version` * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. + * Information about action options see [[Action.new]] * - * Returns the same type as the function itself. + * See also [original guide](http://docs.python.org/dev/library/argparse.html#action) * - * @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 -//----------------------------------------------------------------------- + **/ + + + + +// Constants +var c = __webpack_require__(45); + + /** - * Saves state for current action, the state can only be retrieved by this action's post job execution. + * new Action(options) * - * @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) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. + * Base class for all actions. Used only for inherits * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -//# sourceMappingURL=core.js.map + * + * ##### Options: + * + * - `optionStrings` A list of command-line option strings for the action. + * - `dest` Attribute to hold the created object(s) + * - `nargs` The number of command-line arguments that should be consumed. + * By default, one argument will be consumed and a single value will be + * produced. + * - `constant` Default value for an action with no value. + * - `defaultValue` The value to be produced if the option is not specified. + * - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If + * None, 'string'. + * - `choices` The choices available. + * - `required` True if the action must always be specified at the command + * line. + * - `help` The help describing the argument. + * - `metavar` The name to be used for the option's argument with the help + * string. If None, the 'dest' value will be used as the name. + * + * ##### nargs supported values: + * + * - `N` (an integer) consumes N arguments (and produces a list) + * - `?` consumes zero or one arguments + * - `*` consumes zero or more arguments (and produces a list) + * - `+` consumes one or more arguments (and produces a list) + * + * Note: that the difference between the default and nargs=1 is that with the + * default, a single value will be produced, while with nargs=1, a list + * containing a single value will be produced. + **/ +var Action = module.exports = function Action(options) { + options = options || {}; + this.optionStrings = options.optionStrings || []; + this.dest = options.dest; + this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null; + this.constant = typeof options.constant !== 'undefined' ? options.constant : null; + this.defaultValue = options.defaultValue; + this.type = typeof options.type !== 'undefined' ? options.type : null; + this.choices = typeof options.choices !== 'undefined' ? options.choices : null; + this.required = typeof options.required !== 'undefined' ? options.required : false; + this.help = typeof options.help !== 'undefined' ? options.help : null; + this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null; -/***/ }), -/* 394 */, -/* 395 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (!(this.optionStrings instanceof Array)) { + throw new Error('optionStrings should be an array'); + } + if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') { + throw new Error('required should be a boolean'); + } +}; -const { create } = __webpack_require__(214); -const core = __webpack_require__(393); -const noFileOptions = __webpack_require__(787); -const { findFilesToUpload } = __webpack_require__(84); -const { logger } = __webpack_require__(79); -var assert = __webpack_require__(357); +/** + * Action#getName -> String + * + * Tells action name + **/ +Action.prototype.getName = function () { + if (this.optionStrings.length > 0) { + return this.optionStrings.join('/'); + } else if (this.metavar !== null && this.metavar !== c.SUPPRESS) { + return this.metavar; + } else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) { + return this.dest; + } + return null; +}; -async function run(archiveArtifacts, on = ["success", "failure"]) { - assert(archiveArtifacts, "archiveArtifacts is not defined"); - assert(archiveArtifacts.paths, "archiveArtifacts.paths is not defined"); - assert(archiveArtifacts.name, "archiveArtifacts.name is not defined"); - const path = archiveArtifacts.paths - .filter(pathItem => pathItem && pathItem.path && on.includes(pathItem.on)) - .reduce((acc, pathItem) => acc.concat(pathItem.path, "\n"), "") - .trim(); - try { - logger.info(`Uploading artifacts for path [${path}]`); - const searchResult = await findFilesToUpload(path); - if (searchResult.filesToUpload.length === 0) { - switch (archiveArtifacts.ifNoFilesFound) { - case noFileOptions.error: { - core.setFailed( - `[ERROR] No files were found with the provided path: ${path}. No artifacts will be uploaded.` - ); - break; - } - case noFileOptions.ignore: { - core.info( - `[INFO] No files were found with the provided path: ${path}. No artifacts will be uploaded.` - ); - break; - } - case noFileOptions.warn: - default: { - core.warning( - `[WARNING] No files were found with the provided path: ${path}. No artifacts will be uploaded.` - ); - } - } - } else { - core.info( - `[INFO] With the provided path (${path}), there will be ${searchResult.filesToUpload.length} file(s) uploaded` - ); - core.debug( - `[DEBUG] Root artifact directory is ${searchResult.rootDirectory}` - ); +/** + * Action#isOptional -> Boolean + * + * Return true if optional + **/ +Action.prototype.isOptional = function () { + return !this.isPositional(); +}; - const artifactClient = create(); - const options = { - continueOnError: false - }; - const uploadResponse = await artifactClient.uploadArtifact( - archiveArtifacts.name, - searchResult.filesToUpload, - searchResult.rootDirectory, - options - ); - if (uploadResponse.failedItems.length > 0) { - core.setFailed( - `[ERROR] An error was encountered when uploading ${uploadResponse.artifactName}. There were ${uploadResponse.failedItems.length} items that failed to upload.` - ); - } else { - core.info( - `[INFO] Artifact ${uploadResponse.artifactName} has been successfully uploaded!` - ); - } - return uploadResponse; - } - } catch (err) { - core.setFailed(err.message); - } - return undefined; -} -module.exports = { - run +/** + * Action#isPositional -> Boolean + * + * Return true if positional + **/ +Action.prototype.isPositional = function () { + return (this.optionStrings.length === 0); +}; + +/** + * Action#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Should be implemented in inherited classes + * + * ##### Example + * + * ActionCount.prototype.call = function (parser, namespace, values, optionString) { + * namespace.set(this.dest, (namespace[this.dest] || 0) + 1); + * }; + * + **/ +Action.prototype.call = function () { + throw new Error('.call() not defined');// Not Implemented error }; /***/ }), -/* 396 */, -/* 397 */, -/* 398 */, -/* 399 */, -/* 400 */, -/* 401 */ -/***/ (function(__unusedmodule, exports) { +/* 381 */, +/* 382 */, +/* 383 */ +/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -// The number of concurrent uploads that happens at the same time -function getUploadFileConcurrency() { - return 2; -} -exports.getUploadFileConcurrency = getUploadFileConcurrency; -// When uploading large files that can't be uploaded with a single http call, this controls -// the chunk size that is used during upload -function getUploadChunkSize() { - return 8 * 1024 * 1024; // 8 MB Chunks -} -exports.getUploadChunkSize = getUploadChunkSize; -// The maximum number of retries that can be attempted before an upload or download fails -function getRetryLimit() { - return 5; -} -exports.getRetryLimit = getRetryLimit; -// With exponential backoff, the larger the retry count, the larger the wait time before another attempt -// The retry multiplier controls by how much the backOff time increases depending on the number of retries -function getRetryMultiplier() { - return 1.5; -} -exports.getRetryMultiplier = getRetryMultiplier; -// The initial wait time if an upload or download fails and a retry is being attempted for the first time -function getInitialRetryIntervalInMilliseconds() { - return 3000; -} -exports.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds; -// The number of concurrent downloads that happens at the same time -function getDownloadFileConcurrency() { - return 2; -} -exports.getDownloadFileConcurrency = getDownloadFileConcurrency; -function getRuntimeToken() { - const token = process.env['ACTIONS_RUNTIME_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_RUNTIME_TOKEN env variable'); - } - return token; -} -exports.getRuntimeToken = getRuntimeToken; -function getRuntimeUrl() { - const runtimeUrl = process.env['ACTIONS_RUNTIME_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_RUNTIME_URL env variable'); - } - return runtimeUrl; -} -exports.getRuntimeUrl = getRuntimeUrl; -function getWorkFlowRunId() { - const workFlowRunId = process.env['GITHUB_RUN_ID']; - if (!workFlowRunId) { - throw new Error('Unable to get GITHUB_RUN_ID env variable'); - } - return workFlowRunId; -} -exports.getWorkFlowRunId = getWorkFlowRunId; -function getWorkSpaceDirectory() { - const workspaceDirectory = process.env['GITHUB_WORKSPACE']; - if (!workspaceDirectory) { - throw new Error('Unable to get GITHUB_WORKSPACE env variable'); - } - return workspaceDirectory; -} -exports.getWorkSpaceDirectory = getWorkSpaceDirectory; -//# sourceMappingURL=config-variables.js.map -/***/ }), -/* 402 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +const process = __webpack_require__(765); -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. +const fse = __webpack_require__(226); +const { ArgumentParser } = __webpack_require__(470); +const { Octokit } = __webpack_require__(889); -module.exports = glob +const { ClientError, logger } = __webpack_require__(79); +const { createConfig, createConfigLocally } = __webpack_require__(148); +const { executeGitHubAction } = __webpack_require__(650); -var fs = __webpack_require__(747) -var rp = __webpack_require__(302) -var minimatch = __webpack_require__(571) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(689) -var EE = __webpack_require__(759).EventEmitter -var path = __webpack_require__(622) -var assert = __webpack_require__(357) -var isAbsolute = __webpack_require__(681) -var globSync = __webpack_require__(245) -var common = __webpack_require__(856) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(674) -var util = __webpack_require__(669) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +const pkg = __webpack_require__(731); -var once = __webpack_require__(969) +async function main() { + const parser = new ArgumentParser({ + prog: pkg.name, + version: pkg.version, + addHelp: true, + description: pkg.description + }); + parser.addArgument(["-t", "--trace"], { + action: "storeTrue", + help: "Show trace output" + }); + parser.addArgument(["-d", "--debug"], { + action: "storeTrue", + help: "Show debugging output" + }); + parser.addArgument(["url"], { + metavar: "", + nargs: "?", + help: "GitHub URL to process instead of environment variables" + }); -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} + const args = parser.parseArgs(); - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) + if (args.trace) { + logger.level = "trace"; + } else if (args.debug) { + logger.level = "debug"; } - return new Glob(pattern, options, cb) -} + const token = env("GITHUB_TOKEN"); + const octokit = new Octokit({ + auth: `token ${token}`, + userAgent: "kiegroup/github-build-chain-action" + }); -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync + let config = undefined; + if (args.url) { + config = await createConfigLocally(octokit, args.url, process.env); + } else { + const eventPath = env("GITHUB_EVENT_PATH"); + const eventDataStr = await fse.readFile(eventPath, "utf8"); + const eventData = JSON.parse(eventDataStr); + config = await createConfig(eventData, undefined, process.env); + } -// old api surface -glob.glob = glob + const context = { token, octokit, config }; + await executeGitHubAction(context); +} -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin +function env(name) { + const val = process.env[name]; + if (!val || !val.length) { + throw new ClientError(`environment variable ${name} not set!`); } + return val; +} - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin +if (require.main === require.cache[eval('__filename')]) { + main().catch(e => { + if (e instanceof ClientError) { + process.exitCode = 2; + logger.error(e); + } else { + process.exitCode = 1; + logger.error(e); + } + }); } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - var g = new Glob(pattern, options) - var set = g.minimatch.set +/***/ }), +/* 384 */, +/* 385 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (!pattern) - return false +"use strict"; - if (set.length > 1) - return true - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true +Object.defineProperty(exports, '__esModule', { value: true }); + +var isPlainObject = __webpack_require__(588); +var universalUserAgent = __webpack_require__(562); + +function lowercaseKeys(object) { + if (!object) { + return {}; } - return false + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); } -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach(key => { + if (isPlainObject.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; +} - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } } - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false + return obj; +} - // process each pattern in the minimatch set - var n = this.minimatch.set.length +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); + } // lowercase header names before merging with defaults to avoid duplicates - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - var self = this - this._processing = 0 + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - this._emitQueue = [] - this._processQueue = [] - this.paused = false + if (defaults && defaults.mediaType.previews.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + } - if (this.noprocess) - return this + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); + return mergedOptions; +} - if (n === 0) - return done() +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) + if (names.length === 0) { + return url; } - sync = false - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - } -} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - common.finish(this) - this.emit('end', this.found) + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); } -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true +const urlVariableRegex = /\{[^}]+\}/g; - var n = this.matches.length - if (n === 0) - return this._finish() +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); - function next () { - if (--n === 0) - self._finish() + if (!matches) { + return []; } -} -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} - var found = Object.keys(matchset) - var self = this - var n = found.length +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} - if (n === 0) - return cb() +// Based on https://github.com/bramstein/url-template, licensed under BSD +// TODO: create separate package. +// +// Copyright (c) 2012-2014, Bram Stein +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. The name of the author may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here +/* istanbul ignore file */ +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, "]"); + } - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) + return part; + }).join(""); } -Glob.prototype._mark = function (p) { - return common.mark(this, p) +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); } -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } } -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } +function isDefined(value) { + return value !== undefined && value !== null; } -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; } -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') +function getValues(context, operator, key, modifier) { + var value = context[key], + result = []; - if (this.aborted) - return + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } - //console.error('PROCESS %d', this._processing, pattern) + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + tmp.push(encodeValue(operator, value)); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + 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(""); + } } - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) + return result; } -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; } -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) + if (operator && operator !== "+") { + var separator = ","; + + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + + return (values.length !== 0 ? operator : "") + values.join(separator); } else { - m = e.match(pn) + return values.join(","); } - if (m) - matchedEntries.push(e) + } else { + return encodeReserved(literal); } - } + }); +} - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() + 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"]); // extract variable names from URL to calculate remaining variables later - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + 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 (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) + if (!isBinaryRequest) { + if (options.mediaType.format) { + // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw + headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); } - // This was the last one, and no stats were needed - return cb() - } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + if (options.mediaType.previews.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() -} + } // for GET/HEAD requests, set URL query parameters from remaining parameters + // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - if (isIgnored(this, e)) - return + 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; + } else { + headers["content-length"] = 0; + } + } + } // default content-type for JSON if body is set - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. + // fetch does not allow to set `content-length` header, but we can set body to an empty string - if (this.mark) - e = this._mark(e) - if (this.absolute) - e = abs + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present - if (this.matches[index][e]) - return - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); +} - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} - this.emit('match', e) +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS = merge(oldDefaults, newDefaults); + const endpoint = endpointWithDefaults.bind(null, DEFAULTS); + return Object.assign(endpoint, { + DEFAULTS, + defaults: withDefaults.bind(null, DEFAULTS), + merge: merge.bind(null, DEFAULTS), + parse + }); } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return +const VERSION = "6.0.8"; - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) +const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. +// So we use RequestParameters and add method as additional required property. - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) +const DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } +}; - if (lstatcb) - fs.lstat(abs, lstatcb) +const endpoint = withDefaults(null, DEFAULTS); - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } -} +/***/ }), +/* 386 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return +"use strict"; - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) +var Type = __webpack_require__(945); - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() +function resolveJavascriptUndefined() { + return true; +} - if (Array.isArray(c)) - return cb(null, c) - } +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) +function representJavascriptUndefined() { + return ''; } -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } +function isUndefined(object) { + return typeof object === 'undefined'; } -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - this.cache[abs] = entries - return cb(null, entries) -} +/***/ }), +/* 387 */, +/* 388 */, +/* 389 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return +"use strict"; - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +const fs = __webpack_require__(747); +const shebangCommand = __webpack_require__(866); - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + let buffer; - return cb() -} + if (Buffer.alloc) { + // Node.js v4.5+ / v5.10+ + buffer = Buffer.alloc(size); + } else { + // Old Node.js API + buffer = new Buffer(size); + buffer.fill(0); // zero-fill + } -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + let fd; + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +module.exports = readShebang; - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) +/***/ }), +/* 390 */, +/* 391 */, +/* 392 */ +/***/ (function(__unusedmodule, exports) { - var isSym = this.symlinks[abs] - var len = entries.length +"use strict"; - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +Object.defineProperty(exports, '__esModule', { value: true }); - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } - cb() + return ""; } -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map - //console.error('ps2', prefix, exists) - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) - - if (needDir && c === 'FILE') - return cb() - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } - - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return cb() - - return cb(null, c, stat) -} - - -/***/ }), -/* 403 */, -/* 404 */, -/* 405 */, -/* 406 */, -/* 407 */, -/* 408 */, -/* 409 */, -/* 410 */, -/* 411 */, -/* 412 */, -/* 413 */ -/***/ (function(module) { - -module.exports = require("stream"); - -/***/ }), -/* 414 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - - -var yaml = __webpack_require__(819); - - -module.exports = yaml; - - -/***/ }), -/* 415 */, -/* 416 */, -/* 417 */ -/***/ (function(module) { - -module.exports = require("crypto"); - -/***/ }), -/* 418 */, -/* 419 */, -/* 420 */, -/* 421 */, -/* 422 */, -/* 423 */, -/* 424 */, -/* 425 */, -/* 426 */, -/* 427 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -// Older verions of Node.js might not have `util.getSystemErrorName()`. -// In that case, fall back to a deprecated internal. -const util = __webpack_require__(669); - -let uv; - -if (typeof util.getSystemErrorName === 'function') { - module.exports = util.getSystemErrorName; -} else { - try { - uv = process.binding('uv'); - - if (typeof uv.errname !== 'function') { - throw new TypeError('uv.errname is not a function'); - } - } catch (err) { - console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); - uv = null; - } - - module.exports = code => errname(uv, code); -} - -// Used for testing the fallback behavior -module.exports.__test__ = errname; - -function errname(uv, code) { - if (uv) { - return uv.errname(code); - } - - if (!(code < 0)) { - throw new Error('err >= 0'); - } - - return `Unknown system error ${code}`; -} - - - -/***/ }), -/* 428 */, -/* 429 */, -/* 430 */, -/* 431 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ }), +/* 393 */ +/***/ (function(__unusedmodule, exports, __webpack_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()); + }); +}; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; @@ -11789,17850 +9843,18965 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", { value: true }); +const command_1 = __webpack_require__(431); +const file_command_1 = __webpack_require__(102); +const utils_1 = __webpack_require__(82); const os = __importStar(__webpack_require__(87)); +const path = __importStar(__webpack_require__(622)); /** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value + * The code to exit an action */ -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); +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 || (exports.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 = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_'; + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); + } + else { + command_1.issueCommand('set-env', { name }, convertedVal); + } } -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; +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + 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) { + file_command_1.issueCommand('PATH', inputPath); } - 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; + else { + command_1.issueCommand('add-path', {}, inputPath); } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } +exports.addPath = addPath; /** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; +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}`); } - return JSON.stringify(input); + return val.trim(); } -exports.toCommandValue = toCommandValue; -function escapeData(s) { - return toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); +exports.getInput = getInput; +/** + * 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) { + command_1.issueCommand('set-output', { name }, value); } -function escapeProperty(s) { - return toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); +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) { + command_1.issue('echo', enabled ? 'on' : 'off'); } -//# sourceMappingURL=command.js.map +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) { + 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() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * 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) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + 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) { + command_1.issueCommand('save-state', { name }, 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; +//# sourceMappingURL=core.js.map /***/ }), -/* 432 */, -/* 433 */, -/* 434 */, -/* 435 */, -/* 436 */, -/* 437 */, -/* 438 */, -/* 439 */, -/* 440 */, -/* 441 */, -/* 442 */, -/* 443 */, -/* 444 */, -/* 445 */, -/* 446 */, -/* 447 */, -/* 448 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); +/* 394 */, +/* 395 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var universalUserAgent = __webpack_require__(796); -var beforeAfterHook = __webpack_require__(523); -var request = __webpack_require__(753); -var graphql = __webpack_require__(898); -var authToken = __webpack_require__(813); +const { create } = __webpack_require__(214); +const core = __webpack_require__(393); +const noFileOptions = __webpack_require__(787); +const { findFilesToUpload } = __webpack_require__(84); +const { logger } = __webpack_require__(79); +var assert = __webpack_require__(357); -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } +async function run(archiveArtifacts, on = ["success", "failure"]) { + assert(archiveArtifacts, "archiveArtifacts is not defined"); + assert(archiveArtifacts.paths, "archiveArtifacts.paths is not defined"); + assert(archiveArtifacts.name, "archiveArtifacts.name is not defined"); + const path = archiveArtifacts.paths + .filter(pathItem => pathItem && pathItem.path && on.includes(pathItem.on)) + .reduce((acc, pathItem) => acc.concat(pathItem.path, "\n"), "") + .trim(); + try { + logger.info(`Uploading artifacts for path [${path}]`); + const searchResult = await findFilesToUpload(path); + if (searchResult.filesToUpload.length === 0) { + switch (archiveArtifacts.ifNoFilesFound) { + case noFileOptions.error: { + core.setFailed( + `[ERROR] No files were found with the provided path: ${path}. No artifacts will be uploaded.` + ); + break; + } + case noFileOptions.ignore: { + core.info( + `[INFO] No files were found with the provided path: ${path}. No artifacts will be uploaded.` + ); + break; + } + case noFileOptions.warn: + default: { + core.warning( + `[WARNING] No files were found with the provided path: ${path}. No artifacts will be uploaded.` + ); + } + } + } else { + core.info( + `[INFO] With the provided path (${path}), there will be ${searchResult.filesToUpload.length} file(s) uploaded` + ); + core.debug( + `[DEBUG] Root artifact directory is ${searchResult.rootDirectory}` + ); - return obj; + const artifactClient = create(); + const options = { + continueOnError: false + }; + const uploadResponse = await artifactClient.uploadArtifact( + archiveArtifacts.name, + searchResult.filesToUpload, + searchResult.rootDirectory, + options + ); + if (uploadResponse.failedItems.length > 0) { + core.setFailed( + `[ERROR] An error was encountered when uploading ${uploadResponse.artifactName}. There were ${uploadResponse.failedItems.length} items that failed to upload.` + ); + } else { + core.info( + `[INFO] Artifact ${uploadResponse.artifactName} has been successfully uploaded!` + ); + } + return uploadResponse; + } + } catch (err) { + core.setFailed(err.message); + } + return undefined; } +module.exports = { + run +}; -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } +/***/ }), +/* 396 */, +/* 397 */, +/* 398 */, +/* 399 */, +/* 400 */, +/* 401 */ +/***/ (function(__unusedmodule, exports) { - return keys; -} +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +// The number of concurrent uploads that happens at the same time +function getUploadFileConcurrency() { + return 2; +} +exports.getUploadFileConcurrency = getUploadFileConcurrency; +// When uploading large files that can't be uploaded with a single http call, this controls +// the chunk size that is used during upload +function getUploadChunkSize() { + return 8 * 1024 * 1024; // 8 MB Chunks +} +exports.getUploadChunkSize = getUploadChunkSize; +// The maximum number of retries that can be attempted before an upload or download fails +function getRetryLimit() { + return 5; +} +exports.getRetryLimit = getRetryLimit; +// With exponential backoff, the larger the retry count, the larger the wait time before another attempt +// The retry multiplier controls by how much the backOff time increases depending on the number of retries +function getRetryMultiplier() { + return 1.5; +} +exports.getRetryMultiplier = getRetryMultiplier; +// The initial wait time if an upload or download fails and a retry is being attempted for the first time +function getInitialRetryIntervalInMilliseconds() { + return 3000; +} +exports.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds; +// The number of concurrent downloads that happens at the same time +function getDownloadFileConcurrency() { + return 2; +} +exports.getDownloadFileConcurrency = getDownloadFileConcurrency; +function getRuntimeToken() { + const token = process.env['ACTIONS_RUNTIME_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_RUNTIME_TOKEN env variable'); + } + return token; +} +exports.getRuntimeToken = getRuntimeToken; +function getRuntimeUrl() { + const runtimeUrl = process.env['ACTIONS_RUNTIME_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_RUNTIME_URL env variable'); + } + return runtimeUrl; +} +exports.getRuntimeUrl = getRuntimeUrl; +function getWorkFlowRunId() { + const workFlowRunId = process.env['GITHUB_RUN_ID']; + if (!workFlowRunId) { + throw new Error('Unable to get GITHUB_RUN_ID env variable'); + } + return workFlowRunId; +} +exports.getWorkFlowRunId = getWorkFlowRunId; +function getWorkSpaceDirectory() { + const workspaceDirectory = process.env['GITHUB_WORKSPACE']; + if (!workspaceDirectory) { + throw new Error('Unable to get GITHUB_WORKSPACE env variable'); + } + return workspaceDirectory; +} +exports.getWorkSpaceDirectory = getWorkSpaceDirectory; +//# sourceMappingURL=config-variables.js.map -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; +/***/ }), +/* 402 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } +/*! + * Tmp + * + * Copyright (c) 2011-2017 KARASZI Istvan + * + * MIT Licensed + */ - return target; -} +/* + * Module dependencies. + */ +const fs = __webpack_require__(747); +const os = __webpack_require__(87); +const path = __webpack_require__(622); +const crypto = __webpack_require__(373); +const _c = fs.constants && os.constants ? + { fs: fs.constants, os: os.constants } : + process.binding('constants'); +const rimraf = __webpack_require__(569); -const VERSION = "2.5.4"; +/* + * The working inner variables. + */ +const + // the random characters to choose from + RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; // prepend default user agent with `options.userAgent` if set + TEMPLATE_PATTERN = /XXXXXX/, - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); + DEFAULT_TRIES = 3, - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } + CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } + EBADF = _c.EBADF || _c.os.errno.EBADF, + ENOENT = _c.ENOENT || _c.os.errno.ENOENT, - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } + DIR_MODE = 448 /* 0o700 */, + FILE_MODE = 384 /* 0o600 */, - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(_objectSpread2(_objectSpread2({}, requestDefaults), {}, { - baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api") - })); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. + EXIT = 'exit', - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + SIGINT = 'SIGINT', - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const auth = options.authStrategy(Object.assign({ - request: this.request - }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ + // this will hold the objects need to be removed on exit + _removeObjects = []; - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 +var + _gracefulCleanup = false; +/** + * Random name generator based on crypto. + * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript + * + * @param {number} howMany + * @returns {string} the generated random name + * @private + */ +function _randomChars(howMany) { + var + value = [], + rnd = null; - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); + // make sure that we do not fail because we ran out of entropy + try { + rnd = crypto.randomBytes(howMany); + } catch (e) { + rnd = crypto.pseudoRandomBytes(howMany); } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } - - }; - return OctokitWithDefaults; + for (var i = 0; i < howMany; i++) { + value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ + return value.join(''); +} - static plugin(p1, ...p2) { - var _a; +/** + * Checks whether the `obj` parameter is defined or not. + * + * @param {Object} obj + * @returns {boolean} true if the object is undefined + * @private + */ +function _isUndefined(obj) { + return typeof obj === 'undefined'; +} - if (p1 instanceof Array) { - console.warn(["Passing an array of plugins to Octokit.plugin() has been deprecated.", "Instead of:", " Octokit.plugin([plugin1, plugin2, ...])", "Use:", " Octokit.plugin(plugin1, plugin2, ...)"].join("\n")); - } +/** + * Parses the function arguments. + * + * This function helps to have optional arguments. + * + * @param {(Options|Function)} options + * @param {Function} callback + * @returns {Array} parsed arguments + * @private + */ +function _parseArguments(options, callback) { + /* istanbul ignore else */ + if (typeof options === 'function') { + return [{}, options]; + } - const currentPlugins = this.plugins; - let newPlugins = [...(p1 instanceof Array ? p1 : [p1]), ...p2]; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; + /* istanbul ignore else */ + if (_isUndefined(options)) { + return [{}, callback]; } + return [options, callback]; } -Octokit.VERSION = VERSION; -Octokit.plugins = []; -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map +/** + * Generates a new temporary name. + * + * @param {Object} opts + * @returns {string} the new random name according to opts + * @private + */ +function _generateTmpName(opts) { + const tmpDir = _getTmpDir(); -/***/ }), -/* 449 */, -/* 450 */, -/* 451 */, -/* 452 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // fail early on missing tmp dir + if (isBlank(opts.dir) && isBlank(tmpDir)) { + throw new Error('No tmp dir specified'); + } -"use strict"; -/** - * class ArgumentParser - * - * Object for parsing command line strings into js objects. - * - * Inherited from [[ActionContainer]] - **/ + /* istanbul ignore else */ + if (!isBlank(opts.name)) { + return path.join(opts.dir || tmpDir, opts.name); + } + // mkstemps like template + // opts.template has already been guarded in tmpName() below + /* istanbul ignore else */ + if (opts.template) { + var template = opts.template; + // make sure that we prepend the tmp path if none was given + /* istanbul ignore else */ + if (path.basename(template) === template) + template = path.join(opts.dir || tmpDir, template); + return template.replace(TEMPLATE_PATTERN, _randomChars(6)); + } -var util = __webpack_require__(669); -var format = __webpack_require__(669).format; -var Path = __webpack_require__(622); -var sprintf = __webpack_require__(552).sprintf; + // prefix and postfix + const name = [ + (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), + process.pid, + _randomChars(12), + (opts.postfix ? opts.postfix : '') + ].join(''); -// Constants -var c = __webpack_require__(45); + return path.join(opts.dir || tmpDir, name); +} -var $$ = __webpack_require__(255); +/** + * Gets a temporary file name. + * + * @param {(Options|tmpNameCallback)} options options or callback + * @param {?tmpNameCallback} callback the callback function + */ +function tmpName(options, callback) { + var + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1], + tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; -var ActionContainer = __webpack_require__(614); + /* istanbul ignore else */ + if (isNaN(tries) || tries < 0) + return cb(new Error('Invalid tries')); -// Errors -var argumentErrorHelper = __webpack_require__(287); + /* istanbul ignore else */ + if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) + return cb(new Error('Invalid template provided')); -var HelpFormatter = __webpack_require__(532); + (function _getUniqueName() { + try { + const name = _generateTmpName(opts); -var Namespace = __webpack_require__(515); + // check whether the path exists then retry if needed + fs.stat(name, function (err) { + /* istanbul ignore else */ + if (!err) { + /* istanbul ignore else */ + if (tries-- > 0) return _getUniqueName(); + + return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); + } + cb(null, name); + }); + } catch (err) { + cb(err); + } + }()); +} /** - * new ArgumentParser(options) - * - * Create a new ArgumentParser object. - * - * ##### Options: - * - `prog` The name of the program (default: Path.basename(process.argv[1])) - * - `usage` A usage message (default: auto-generated from arguments) - * - `description` A description of what the program does - * - `epilog` Text following the argument descriptions - * - `parents` Parsers whose arguments should be copied into this one - * - `formatterClass` HelpFormatter class for printing help messages - * - `prefixChars` Characters that prefix optional arguments - * - `fromfilePrefixChars` Characters that prefix files containing additional arguments - * - `argumentDefault` The default value for all arguments - * - `addHelp` Add a -h/-help option - * - `conflictHandler` Specifies how to handle conflicting argument names - * - `debug` Enable debug mode. Argument errors throw exception in - * debug mode and process.exit in normal. Used for development and - * testing (default: false) - * - * See also [original guide][1] + * Synchronous version of tmpName. * - * [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects - **/ -function ArgumentParser(options) { - if (!(this instanceof ArgumentParser)) { - return new ArgumentParser(options); - } - var self = this; - options = options || {}; + * @param {Object} options + * @returns {string} the generated random name + * @throws {Error} if the options are invalid or could not generate a filename + */ +function tmpNameSync(options) { + var + args = _parseArguments(options), + opts = args[0], + tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; - options.description = (options.description || null); - options.argumentDefault = (options.argumentDefault || null); - options.prefixChars = (options.prefixChars || '-'); - options.conflictHandler = (options.conflictHandler || 'error'); - ActionContainer.call(this, options); + /* istanbul ignore else */ + if (isNaN(tries) || tries < 0) + throw new Error('Invalid tries'); - options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp; - options.parents = options.parents || []; - // default program name - options.prog = (options.prog || Path.basename(process.argv[1])); - this.prog = options.prog; - this.usage = options.usage; - this.epilog = options.epilog; - this.version = options.version; - - this.debug = (options.debug === true); - - this.formatterClass = (options.formatterClass || HelpFormatter); - this.fromfilePrefixChars = options.fromfilePrefixChars || null; - this._positionals = this.addArgumentGroup({ title: 'Positional arguments' }); - this._optionals = this.addArgumentGroup({ title: 'Optional arguments' }); - this._subparsers = null; + /* istanbul ignore else */ + if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) + throw new Error('Invalid template provided'); - // register types - function FUNCTION_IDENTITY(o) { - return o; - } - this.register('type', 'auto', FUNCTION_IDENTITY); - this.register('type', null, FUNCTION_IDENTITY); - this.register('type', 'int', function (x) { - var result = parseInt(x, 10); - if (isNaN(result)) { - throw new Error(x + ' is not a valid integer.'); - } - return result; - }); - this.register('type', 'float', function (x) { - var result = parseFloat(x); - if (isNaN(result)) { - throw new Error(x + ' is not a valid float.'); + do { + const name = _generateTmpName(opts); + try { + fs.statSync(name); + } catch (e) { + return name; } - return result; - }); - this.register('type', 'string', function (x) { - return '' + x; - }); - - // add help and version arguments if necessary - var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0]; - if (options.addHelp) { - this.addArgument( - [ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ], - { - action: 'help', - defaultValue: c.SUPPRESS, - help: 'Show this help message and exit.' - } - ); - } - if (typeof this.version !== 'undefined') { - this.addArgument( - [ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ], - { - action: 'version', - version: this.version, - defaultValue: c.SUPPRESS, - help: "Show program's version number and exit." - } - ); - } + } while (tries-- > 0); - // add parent arguments and defaults - options.parents.forEach(function (parent) { - self._addContainerActions(parent); - if (typeof parent._defaults !== 'undefined') { - for (var defaultKey in parent._defaults) { - if (parent._defaults.hasOwnProperty(defaultKey)) { - self._defaults[defaultKey] = parent._defaults[defaultKey]; - } - } - } - }); + throw new Error('Could not get a unique tmp filename, max tries reached'); } -util.inherits(ArgumentParser, ActionContainer); - /** - * ArgumentParser#addSubparsers(options) -> [[ActionSubparsers]] - * - options (object): hash of options see [[ActionSubparsers.new]] - * - * See also [subcommands][1] + * Creates and opens a temporary file. * - * [1]:http://docs.python.org/dev/library/argparse.html#sub-commands - **/ -ArgumentParser.prototype.addSubparsers = function (options) { - if (this._subparsers) { - this.error('Cannot have multiple subparser arguments.'); - } - - options = options || {}; - options.debug = (this.debug === true); - options.optionStrings = []; - options.parserClass = (options.parserClass || ArgumentParser); + * @param {(Options|fileCallback)} options the config options or the callback function + * @param {?fileCallback} callback + */ +function file(options, callback) { + var + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1]; + // gets a temporary filename + tmpName(opts, function _tmpNameCreated(err, name) { + /* istanbul ignore else */ + if (err) return cb(err); - if (!!options.title || !!options.description) { + // create and open the file + fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { + /* istanbul ignore else */ + if (err) return cb(err); - this._subparsers = this.addArgumentGroup({ - title: (options.title || 'subcommands'), - description: options.description + if (opts.discardDescriptor) { + return fs.close(fd, function _discardCallback(err) { + /* istanbul ignore else */ + if (err) { + // Low probability, and the file exists, so this could be + // ignored. If it isn't we certainly need to unlink the + // file, and if that fails too its error is more + // important. + try { + fs.unlinkSync(name); + } catch (e) { + if (!isENOENT(e)) { + err = e; + } + } + return cb(err); + } + cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); + }); + } + /* istanbul ignore else */ + if (opts.detachDescriptor) { + return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); + } + cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); - delete options.title; - delete options.description; + }); +} - } else { - this._subparsers = this._positionals; - } +/** + * Synchronous version of file. + * + * @param {Options} options + * @returns {FileSyncObject} object consists of name, fd and removeCallback + * @throws {Error} if cannot create a file + */ +function fileSync(options) { + var + args = _parseArguments(options), + opts = args[0]; - // prog defaults to the usage message of this parser, skipping - // optional arguments and with no "usage:" prefix - if (!options.prog) { - var formatter = this._getFormatter(); - var positionals = this._getPositionalActions(); - var groups = this._mutuallyExclusiveGroups; - formatter.addUsage(this.usage, positionals, groups, ''); - options.prog = formatter.formatHelp().trim(); + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + const name = tmpNameSync(opts); + var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + /* istanbul ignore else */ + if (opts.discardDescriptor) { + fs.closeSync(fd); + fd = undefined; } - // create the parsers action and add it to the positionals list - var ParsersClass = this._popActionClass(options, 'parsers'); - var action = new ParsersClass(options); - this._subparsers._addAction(action); + return { + name: name, + fd: fd, + removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) + }; +} - // return the created parsers action - return action; -}; +/** + * Creates a temporary directory. + * + * @param {(Options|dirCallback)} options the options or the callback function + * @param {?dirCallback} callback + */ +function dir(options, callback) { + var + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1]; -ArgumentParser.prototype._addAction = function (action) { - if (action.isOptional()) { - this._optionals._addAction(action); - } else { - this._positionals._addAction(action); - } - return action; -}; + // gets a temporary filename + tmpName(opts, function _tmpNameCreated(err, name) { + /* istanbul ignore else */ + if (err) return cb(err); -ArgumentParser.prototype._getOptionalActions = function () { - return this._actions.filter(function (action) { - return action.isOptional(); - }); -}; + // create the directory + fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { + /* istanbul ignore else */ + if (err) return cb(err); -ArgumentParser.prototype._getPositionalActions = function () { - return this._actions.filter(function (action) { - return action.isPositional(); + cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); + }); }); -}; - +} /** - * ArgumentParser#parseArgs(args, namespace) -> Namespace|Object - * - args (array): input elements - * - namespace (Namespace|Object): result object - * - * Parsed args and throws error if some arguments are not recognized - * - * See also [original guide][1] + * Synchronous version of dir. * - * [1]:http://docs.python.org/dev/library/argparse.html#the-parse-args-method - **/ -ArgumentParser.prototype.parseArgs = function (args, namespace) { - var argv; - var result = this.parseKnownArgs(args, namespace); + * @param {Options} options + * @returns {DirSyncObject} object consists of name and removeCallback + * @throws {Error} if it cannot create a directory + */ +function dirSync(options) { + var + args = _parseArguments(options), + opts = args[0]; - args = result[0]; - argv = result[1]; - if (argv && argv.length > 0) { - this.error( - format('Unrecognized arguments: %s.', argv.join(' ')) - ); - } - return args; -}; + const name = tmpNameSync(opts); + fs.mkdirSync(name, opts.mode || DIR_MODE); + + return { + name: name, + removeCallback: _prepareTmpDirRemoveCallback(name, opts) + }; +} /** - * ArgumentParser#parseKnownArgs(args, namespace) -> array - * - args (array): input options - * - namespace (Namespace|Object): result object - * - * Parse known arguments and return tuple of result object - * and unknown args - * - * See also [original guide][1] + * Removes files asynchronously. * - * [1]:http://docs.python.org/dev/library/argparse.html#partial-parsing - **/ -ArgumentParser.prototype.parseKnownArgs = function (args, namespace) { - var self = this; - - // args default to the system args - args = args || process.argv.slice(2); - - // default Namespace built from parser defaults - namespace = namespace || new Namespace(); - - self._actions.forEach(function (action) { - if (action.dest !== c.SUPPRESS) { - if (!$$.has(namespace, action.dest)) { - if (action.defaultValue !== c.SUPPRESS) { - var defaultValue = action.defaultValue; - if (typeof action.defaultValue === 'string') { - defaultValue = self._getValue(action, defaultValue); - } - namespace[action.dest] = defaultValue; - } - } + * @param {Object} fdPath + * @param {Function} next + * @private + */ +function _removeFileAsync(fdPath, next) { + const _handler = function (err) { + if (err && !isENOENT(err)) { + // reraise any unanticipated error + return next(err); } - }); + next(); + } - Object.keys(self._defaults).forEach(function (dest) { - namespace[dest] = self._defaults[dest]; - }); + if (0 <= fdPath[0]) + fs.close(fdPath[0], function (err) { + fs.unlink(fdPath[1], _handler); + }); + else fs.unlink(fdPath[1], _handler); +} - // parse the arguments and exit if there are any errors +/** + * Removes files synchronously. + * + * @param {Object} fdPath + * @private + */ +function _removeFileSync(fdPath) { try { - var res = this._parseKnownArgs(args, namespace); - - namespace = res[0]; - args = res[1]; - if ($$.has(namespace, c._UNRECOGNIZED_ARGS_ATTR)) { - args = $$.arrayUnion(args, namespace[c._UNRECOGNIZED_ARGS_ATTR]); - delete namespace[c._UNRECOGNIZED_ARGS_ATTR]; - } - return [ namespace, args ]; + if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { - this.error(e); + // reraise any unanticipated error + if (!isEBADF(e) && !isENOENT(e)) throw e; + } finally { + try { + fs.unlinkSync(fdPath[1]); + } + catch (e) { + // reraise any unanticipated error + if (!isENOENT(e)) throw e; + } } -}; +} -ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) { - var self = this; +/** + * Prepares the callback for removal of the temporary file. + * + * @param {string} name the path of the file + * @param {number} fd file descriptor + * @param {Object} opts + * @returns {fileCallback} + * @private + */ +function _prepareTmpFileRemoveCallback(name, fd, opts) { + const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); + const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); - var extras = []; + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - // replace arg strings that are file references - if (this.fromfilePrefixChars !== null) { - argStrings = this._readArgsFromFiles(argStrings); - } - // map all mutually exclusive arguments to the other arguments - // they can't occur with - // Python has 'conflicts = action_conflicts.setdefault(mutex_action, [])' - // though I can't conceive of a way in which an action could be a member - // of two different mutually exclusive groups. + return removeCallback; +} - function actionHash(action) { - // some sort of hashable key for this action - // action itself cannot be a key in actionConflicts - // I think getName() (join of optionStrings) is unique enough - return action.getName(); - } +/** + * Simple wrapper for rimraf. + * + * @param {string} dirPath + * @param {Function} next + * @private + */ +function _rimrafRemoveDirWrapper(dirPath, next) { + rimraf(dirPath, next); +} - var conflicts, key; - var actionConflicts = {}; +/** + * Simple wrapper for rimraf.sync. + * + * @param {string} dirPath + * @private + */ +function _rimrafRemoveDirSyncWrapper(dirPath, next) { + try { + return next(null, rimraf.sync(dirPath)); + } catch (err) { + return next(err); + } +} - this._mutuallyExclusiveGroups.forEach(function (mutexGroup) { - mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) { - key = actionHash(mutexAction); - if (!$$.has(actionConflicts, key)) { - actionConflicts[key] = []; - } - conflicts = actionConflicts[key]; - conflicts.push.apply(conflicts, groupActions.slice(0, i)); - conflicts.push.apply(conflicts, groupActions.slice(i + 1)); - }); - }); +/** + * Prepares the callback for removal of the temporary directory. + * + * @param {string} name + * @param {Object} opts + * @returns {Function} the callback + * @private + */ +function _prepareTmpDirRemoveCallback(name, opts) { + const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); + const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); + const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); + const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - // find all option indices, and determine the arg_string_pattern - // which has an 'O' if there is an option at an index, - // an 'A' if there is an argument, or a '-' if there is a '--' - var optionStringIndices = {}; + return removeCallback; +} - var argStringPatternParts = []; +/** + * Creates a guarded function wrapping the removeFunction call. + * + * @param {Function} removeFunction + * @param {Object} arg + * @returns {Function} + * @private + */ +function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { + var called = false; - argStrings.forEach(function (argString, argStringIndex) { - if (argString === '--') { - argStringPatternParts.push('-'); - while (argStringIndex < argStrings.length) { - argStringPatternParts.push('A'); - argStringIndex++; - } - } else { - // otherwise, add the arg to the arg strings - // and note the index if it was an option - var pattern; - var optionTuple = self._parseOptional(argString); - if (!optionTuple) { - pattern = 'A'; - } else { - optionStringIndices[argStringIndex] = optionTuple; - pattern = 'O'; - } - argStringPatternParts.push(pattern); - } - }); - var argStringsPattern = argStringPatternParts.join(''); + return function _cleanupCallback(next) { + next = next || function () {}; + if (!called) { + const toRemove = cleanupCallbackSync || _cleanupCallback; + const index = _removeObjects.indexOf(toRemove); + /* istanbul ignore else */ + if (index >= 0) _removeObjects.splice(index, 1); - var seenActions = []; - var seenNonDefaultActions = []; + called = true; + // sync? + if (removeFunction.length === 1) { + try { + removeFunction(arg); + return next(null); + } + catch (err) { + // if no next is provided and since we are + // in silent cleanup mode on process exit, + // we will ignore the error + return next(err); + } + } else return removeFunction(arg, next); + } else return next(new Error('cleanup callback has already been called')); + }; +} +/** + * The garbage collector. + * + * @private + */ +function _garbageCollector() { + /* istanbul ignore else */ + if (!_gracefulCleanup) return; - function takeAction(action, argumentStrings, optionString) { - seenActions.push(action); - var argumentValues = self._getValues(action, argumentStrings); - - // error if this argument is not allowed with other previously - // seen arguments, assuming that actions that use the default - // value don't really count as "present" - if (argumentValues !== action.defaultValue) { - seenNonDefaultActions.push(action); - if (actionConflicts[actionHash(action)]) { - actionConflicts[actionHash(action)].forEach(function (actionConflict) { - if (seenNonDefaultActions.indexOf(actionConflict) >= 0) { - throw argumentErrorHelper( - action, - format('Not allowed with argument "%s".', actionConflict.getName()) - ); - } - }); - } - } - - if (argumentValues !== c.SUPPRESS) { - action.call(self, namespace, argumentValues, optionString); + // the function being called removes itself from _removeObjects, + // loop until _removeObjects is empty + while (_removeObjects.length) { + try { + _removeObjects[0](); + } catch (e) { + // already removed? } } +} - function consumeOptional(startIndex) { - // get the optional identified at this index - var optionTuple = optionStringIndices[startIndex]; - var action = optionTuple[0]; - var optionString = optionTuple[1]; - var explicitArg = optionTuple[2]; - - // identify additional optionals in the same arg string - // (e.g. -xyz is the same as -x -y -z if no args are required) - var actionTuples = []; - - var args, argCount, start, stop; - - for (;;) { - if (!action) { - extras.push(argStrings[startIndex]); - return startIndex + 1; - } - if (explicitArg) { - argCount = self._matchArgument(action, 'A'); +/** + * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. + */ +function isEBADF(error) { + return isExpectedError(error, -EBADF, 'EBADF'); +} - // if the action is a single-dash option and takes no - // arguments, try to parse more single-dash options out - // of the tail of the option string - var chars = self.prefixChars; - if (argCount === 0 && chars.indexOf(optionString[1]) < 0) { - actionTuples.push([ action, [], optionString ]); - optionString = optionString[0] + explicitArg[0]; - var newExplicitArg = explicitArg.slice(1) || null; - var optionalsMap = self._optionStringActions; +/** + * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. + */ +function isENOENT(error) { + return isExpectedError(error, -ENOENT, 'ENOENT'); +} - if (Object.keys(optionalsMap).indexOf(optionString) >= 0) { - action = optionalsMap[optionString]; - explicitArg = newExplicitArg; - } else { - throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); - } - } else if (argCount === 1) { - // if the action expect exactly one argument, we've - // successfully matched the option; exit the loop - stop = startIndex + 1; - args = [ explicitArg ]; - actionTuples.push([ action, args, optionString ]); - break; - } else { - // error if a double-dash option did not use the - // explicit argument - throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); - } - } else { - // if there is no explicit argument, try to match the - // optional's string arguments with the following strings - // if successful, exit the loop +/** + * Helper to determine whether the expected error code matches the actual code and errno, + * which will differ between the supported node versions. + * + * - Node >= 7.0: + * error.code {string} + * error.errno {string|number} any numerical value will be negated + * + * - Node >= 6.0 < 7.0: + * error.code {string} + * error.errno {number} negated + * + * - Node >= 4.0 < 6.0: introduces SystemError + * error.code {string} + * error.errno {number} negated + * + * - Node >= 0.10 < 4.0: + * error.code {number} negated + * error.errno n/a + */ +function isExpectedError(error, code, errno) { + return error.code === code || error.code === errno; +} - start = startIndex + 1; - var selectedPatterns = argStringsPattern.substr(start); +/** + * Helper which determines whether a string s is blank, that is undefined, or empty or null. + * + * @private + * @param {string} s + * @returns {Boolean} true whether the string s is blank, false otherwise + */ +function isBlank(s) { + return s === null || s === undefined || !s.trim(); +} - argCount = self._matchArgument(action, selectedPatterns); - stop = start + argCount; +/** + * Sets the graceful cleanup. + */ +function setGracefulCleanup() { + _gracefulCleanup = true; +} +/** + * Returns the currently configured tmp dir from os.tmpdir(). + * + * @private + * @returns {string} the currently configured tmp dir + */ +function _getTmpDir() { + return os.tmpdir(); +} - args = argStrings.slice(start, stop); +/** + * If there are multiple different versions of tmp in place, make sure that + * we recognize the old listeners. + * + * @param {Function} listener + * @private + * @returns {Boolean} true whether listener is a legacy listener + */ +function _is_legacy_listener(listener) { + return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') + && listener.toString().indexOf('_garbageCollector();') > -1; +} - actionTuples.push([ action, args, optionString ]); - break; - } +/** + * Safely install SIGINT listener. + * + * NOTE: this will only work on OSX and Linux. + * + * @private + */ +function _safely_install_sigint_listener() { + const listeners = process.listeners(SIGINT); + const existingListeners = []; + for (let i = 0, length = listeners.length; i < length; i++) { + const lstnr = listeners[i]; + /* istanbul ignore else */ + if (lstnr.name === '_tmp$sigint_listener') { + existingListeners.push(lstnr); + process.removeListener(SIGINT, lstnr); } - - // add the Optional to the list and return the index at which - // the Optional's string args stopped - if (actionTuples.length < 1) { - throw new Error('length should be > 0'); + } + process.on(SIGINT, function _tmp$sigint_listener(doExit) { + for (let i = 0, length = existingListeners.length; i < length; i++) { + // let the existing listener do the garbage collection (e.g. jest sandbox) + try { + existingListeners[i](false); + } catch (err) { + // ignore + } } - for (var i = 0; i < actionTuples.length; i++) { - takeAction.apply(self, actionTuples[i]); + try { + // force the garbage collector even it is called again in the exit listener + _garbageCollector(); + } finally { + if (!!doExit) { + process.exit(0); + } } - return stop; - } - - // the list of Positionals left to be parsed; this is modified - // by consume_positionals() - var positionals = self._getPositionalActions(); + }); +} - function consumePositionals(startIndex) { - // match as many Positionals as possible - var selectedPattern = argStringsPattern.substr(startIndex); - var argCounts = self._matchArgumentsPartial(positionals, selectedPattern); +/** + * Safely install process exit listener. + * + * @private + */ +function _safely_install_exit_listener() { + const listeners = process.listeners(EXIT); - // slice off the appropriate arg strings for each Positional - // and add the Positional and its args to the list - for (var i = 0; i < positionals.length; i++) { - var action = positionals[i]; - var argCount = argCounts[i]; - if (typeof argCount === 'undefined') { - continue; + // collect any existing listeners + const existingListeners = []; + for (let i = 0, length = listeners.length; i < length; i++) { + const lstnr = listeners[i]; + /* istanbul ignore else */ + // TODO: remove support for legacy listeners once release 1.0.0 is out + if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { + // we must forget about the uncaughtException listener, hopefully it is ours + if (lstnr.name !== '_uncaughtExceptionThrown') { + existingListeners.push(lstnr); } - var args = argStrings.slice(startIndex, startIndex + argCount); - - startIndex += argCount; - takeAction(action, args); + process.removeListener(EXIT, lstnr); } - - // slice off the Positionals that we just parsed and return the - // index at which the Positionals' string args stopped - positionals = positionals.slice(argCounts.length); - return startIndex; } + // TODO: what was the data parameter good for? + process.addListener(EXIT, function _tmp$safe_listener(data) { + for (let i = 0, length = existingListeners.length; i < length; i++) { + // let the existing listener do the garbage collection (e.g. jest sandbox) + try { + existingListeners[i](data); + } catch (err) { + // ignore + } + } + _garbageCollector(); + }); +} - // consume Positionals and Optionals alternately, until we have - // passed the last option string - var startIndex = 0; - var position; - - var maxOptionStringIndex = -1; - - Object.keys(optionStringIndices).forEach(function (position) { - maxOptionStringIndex = Math.max(maxOptionStringIndex, parseInt(position, 10)); - }); - - var positionalsEndIndex, nextOptionStringIndex; +_safely_install_exit_listener(); +_safely_install_sigint_listener(); - while (startIndex <= maxOptionStringIndex) { - // consume any Positionals preceding the next option - nextOptionStringIndex = null; - for (position in optionStringIndices) { - if (!optionStringIndices.hasOwnProperty(position)) { continue; } +/** + * Configuration options. + * + * @typedef {Object} Options + * @property {?number} tries the number of tries before give up the name generation + * @property {?string} template the "mkstemp" like filename template + * @property {?string} name fix name + * @property {?string} dir the tmp directory to use + * @property {?string} prefix prefix for the generated name + * @property {?string} postfix postfix for the generated name + * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty + */ - position = parseInt(position, 10); - if (position >= startIndex) { - if (nextOptionStringIndex !== null) { - nextOptionStringIndex = Math.min(nextOptionStringIndex, position); - } else { - nextOptionStringIndex = position; - } - } - } +/** + * @typedef {Object} FileSyncObject + * @property {string} name the name of the file + * @property {string} fd the file descriptor + * @property {fileCallback} removeCallback the callback function to remove the file + */ - if (startIndex !== nextOptionStringIndex) { - positionalsEndIndex = consumePositionals(startIndex); - // only try to parse the next optional if we didn't consume - // the option string during the positionals parsing - if (positionalsEndIndex > startIndex) { - startIndex = positionalsEndIndex; - continue; - } else { - startIndex = positionalsEndIndex; - } - } +/** + * @typedef {Object} DirSyncObject + * @property {string} name the name of the directory + * @property {fileCallback} removeCallback the callback function to remove the directory + */ - // if we consumed all the positionals we could and we're not - // at the index of an option string, there were extra arguments - if (!optionStringIndices[startIndex]) { - var strings = argStrings.slice(startIndex, nextOptionStringIndex); - extras = extras.concat(strings); - startIndex = nextOptionStringIndex; - } - // consume the next optional and any arguments for it - startIndex = consumeOptional(startIndex); - } +/** + * @callback tmpNameCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + */ - // consume any positionals following the last Optional - var stopIndex = consumePositionals(startIndex); +/** + * @callback fileCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {number} fd the file descriptor + * @param {cleanupCallback} fn the cleanup callback function + */ - // if we didn't consume all the argument strings, there were extras - extras = extras.concat(argStrings.slice(stopIndex)); +/** + * @callback dirCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {cleanupCallback} fn the cleanup callback function + */ - // if we didn't use all the Positional objects, there were too few - // arg strings supplied. - if (positionals.length > 0) { - self.error('too few arguments'); +/** + * Removes the temporary created file or directory. + * + * @callback cleanupCallback + * @param {simpleCallback} [next] function to call after entry was removed + */ + +/** + * Callback function for function composition. + * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} + * + * @callback simpleCallback + */ + +// exporting all the needed methods + +// evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will +// allow users to reconfigure the temporary directory +Object.defineProperty(module.exports, 'tmpdir', { + enumerable: true, + configurable: false, + get: function () { + return _getTmpDir(); } +}); - // make sure all required actions were present - self._actions.forEach(function (action) { - if (action.required) { - if (seenActions.indexOf(action) < 0) { - self.error(format('Argument "%s" is required', action.getName())); - } - } - }); +module.exports.dir = dir; +module.exports.dirSync = dirSync; - // make sure all required groups have one option present - var actionUsed = false; - self._mutuallyExclusiveGroups.forEach(function (group) { - if (group.required) { - actionUsed = group._groupActions.some(function (action) { - return seenNonDefaultActions.indexOf(action) !== -1; - }); +module.exports.file = file; +module.exports.fileSync = fileSync; - // if no actions were used, report the error - if (!actionUsed) { - var names = []; - group._groupActions.forEach(function (action) { - if (action.help !== c.SUPPRESS) { - names.push(action.getName()); - } - }); - names = names.join(' '); - var msg = 'one of the arguments ' + names + ' is required'; - self.error(msg); - } - } - }); +module.exports.tmpName = tmpName; +module.exports.tmpNameSync = tmpNameSync; - // return the updated namespace and the extra arguments - return [ namespace, extras ]; -}; +module.exports.setGracefulCleanup = setGracefulCleanup; -ArgumentParser.prototype._readArgsFromFiles = function (argStrings) { - // expand arguments referencing files - var self = this; - var fs = __webpack_require__(747); - var newArgStrings = []; - argStrings.forEach(function (argString) { - if (self.fromfilePrefixChars.indexOf(argString[0]) < 0) { - // for regular arguments, just add them back into the list - newArgStrings.push(argString); - } else { - // replace arguments referencing files with the file content - try { - var argstrs = []; - var filename = argString.slice(1); - var content = fs.readFileSync(filename, 'utf8'); - content = content.trim().split('\n'); - content.forEach(function (argLine) { - self.convertArgLineToArgs(argLine).forEach(function (arg) { - argstrs.push(arg); - }); - argstrs = self._readArgsFromFiles(argstrs); - }); - newArgStrings.push.apply(newArgStrings, argstrs); - } catch (error) { - return self.error(error.message); - } - } - }); - return newArgStrings; -}; -ArgumentParser.prototype.convertArgLineToArgs = function (argLine) { - return [ argLine ]; -}; +/***/ }), +/* 403 */, +/* 404 */, +/* 405 */, +/* 406 */, +/* 407 */, +/* 408 */, +/* 409 */, +/* 410 */, +/* 411 */, +/* 412 */, +/* 413 */ +/***/ (function(module) { -ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) { +module.exports = require("stream"); - // match the pattern for this action to the arg strings - var regexpNargs = new RegExp('^' + this._getNargsPattern(action)); - var matches = regexpArgStrings.match(regexpNargs); - var message; +/***/ }), +/* 414 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // throw an exception if we weren't able to find a match - if (!matches) { - switch (action.nargs) { - /*eslint-disable no-undefined*/ - case undefined: - case null: - message = 'Expected one argument.'; - break; - case c.OPTIONAL: - message = 'Expected at most one argument.'; - break; - case c.ONE_OR_MORE: - message = 'Expected at least one argument.'; - break; - default: - message = 'Expected %s argument(s)'; - } +"use strict"; - throw argumentErrorHelper( - action, - format(message, action.nargs) - ); - } - // return the number of arguments matched - return matches[1].length; -}; -ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgStrings) { - // progressively shorten the actions list by slicing off the - // final actions until we find a match - var self = this; - var result = []; - var actionSlice, pattern, matches; - var i, j; - function getLength(string) { - return string.length; - } +var yaml = __webpack_require__(819); - for (i = actions.length; i > 0; i--) { - pattern = ''; - actionSlice = actions.slice(0, i); - for (j = 0; j < actionSlice.length; j++) { - pattern += self._getNargsPattern(actionSlice[j]); - } - - pattern = new RegExp('^' + pattern); - matches = regexpArgStrings.match(pattern); - if (matches && matches.length > 0) { - // need only groups - matches = matches.splice(1); - result = result.concat(matches.map(getLength)); - break; - } - } +module.exports = yaml; - // return the list of arg string counts - return result; -}; -ArgumentParser.prototype._parseOptional = function (argString) { - var action, optionString, argExplicit, optionTuples; +/***/ }), +/* 415 */, +/* 416 */, +/* 417 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // if it's an empty string, it was meant to be a positional - if (!argString) { - return null; - } +"use strict"; - // if it doesn't start with a prefix, it was meant to be positional - if (this.prefixChars.indexOf(argString[0]) < 0) { - return null; - } - // if the option string is present in the parser, return the action - if (this._optionStringActions[argString]) { - return [ this._optionStringActions[argString], argString, null ]; - } +var common = __webpack_require__(740); +var Type = __webpack_require__(945); - // if it's just a single character, it was meant to be positional - if (argString.length === 1) { - return null; - } +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); - // if the option string before the "=" is present, return the action - if (argString.indexOf('=') >= 0) { - optionString = argString.split('=', 1)[0]; - argExplicit = argString.slice(optionString.length + 1); +function resolveYamlFloat(data) { + if (data === null) return false; - if (this._optionStringActions[optionString]) { - action = this._optionStringActions[optionString]; - return [ action, optionString, argExplicit ]; - } + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - // search through all possible prefixes of the option string - // and all actions in the parser for possible interpretations - optionTuples = this._getOptionTuples(argString); - - // if multiple actions match, the option string was ambiguous - if (optionTuples.length > 1) { - var optionStrings = optionTuples.map(function (optionTuple) { - return optionTuple[1]; - }); - this.error(format( - 'Ambiguous option: "%s" could match %s.', - argString, optionStrings.join(', ') - )); - // if exactly one action matched, this segmentation is good, - // so return the parsed action - } else if (optionTuples.length === 1) { - return optionTuples[0]; - } + return true; +} - // if it was not found as an option, but it looks like a negative - // number, it was meant to be positional - // unless there are negative-number-like options - if (argString.match(this._regexpNegativeNumber)) { - if (!this._hasNegativeNumberOptionals.some(Boolean)) { - return null; - } - } - // if it contains a space, it was meant to be a positional - if (argString.search(' ') >= 0) { - return null; - } +function constructYamlFloat(data) { + var value, sign, base, digits; - // it was meant to be an optional but there is no such option - // in this parser (though it might be a valid option in a subparser) - return [ null, argString, null ]; -}; + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; -ArgumentParser.prototype._getOptionTuples = function (optionString) { - var result = []; - var chars = this.prefixChars; - var optionPrefix; - var argExplicit; - var action; - var actionOptionString; + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } - // option strings starting with two prefix characters are only split at - // the '=' - if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) >= 0) { - if (optionString.indexOf('=') >= 0) { - var optionStringSplit = optionString.split('=', 1); + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - optionPrefix = optionStringSplit[0]; - argExplicit = optionStringSplit[1]; - } else { - optionPrefix = optionString; - argExplicit = null; - } + } else if (value === '.nan') { + return NaN; - for (actionOptionString in this._optionStringActions) { - if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { - action = this._optionStringActions[actionOptionString]; - result.push([ action, actionOptionString, argExplicit ]); - } - } + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); - // single character options can be concatenated with their arguments - // but multiple character options always have to have their argument - // separate - } else if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) < 0) { - optionPrefix = optionString; - argExplicit = null; - var optionPrefixShort = optionString.substr(0, 2); - var argExplicitShort = optionString.substr(2); + value = 0.0; + base = 1; - for (actionOptionString in this._optionStringActions) { - if (!$$.has(this._optionStringActions, actionOptionString)) continue; + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); - action = this._optionStringActions[actionOptionString]; - if (actionOptionString === optionPrefixShort) { - result.push([ action, actionOptionString, argExplicitShort ]); - } else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { - result.push([ action, actionOptionString, argExplicit ]); - } - } + return sign * value; - // shouldn't ever get here - } else { - throw new Error(format('Unexpected option string: %s.', optionString)); } - // return the collected option tuples - return result; -}; + return sign * parseFloat(value, 10); +} -ArgumentParser.prototype._getNargsPattern = function (action) { - // in all examples below, we have to allow for '--' args - // which are represented as '-' in the pattern - var regexpNargs; - switch (action.nargs) { - // the default (null) is assumed to be a single argument - case undefined: - case null: - regexpNargs = '(-*A-*)'; - break; - // allow zero or more arguments - case c.OPTIONAL: - regexpNargs = '(-*A?-*)'; - break; - // allow zero or more arguments - case c.ZERO_OR_MORE: - regexpNargs = '(-*[A-]*)'; - break; - // allow one or more arguments - case c.ONE_OR_MORE: - regexpNargs = '(-*A[A-]*)'; - break; - // allow any number of options or arguments - case c.REMAINDER: - regexpNargs = '([-AO]*)'; - break; - // allow one argument followed by any number of options or arguments - case c.PARSER: - regexpNargs = '(-*A[-AO]*)'; - break; - // all others should be integers - default: - regexpNargs = '(-*' + $$.repeat('-*A', action.nargs) + '-*)'; - } +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - // if this is an optional action, -- is not allowed - if (action.isOptional()) { - regexpNargs = regexpNargs.replace(/-\*/g, ''); - regexpNargs = regexpNargs.replace(/-/g, ''); +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; } - // return the pattern - return regexpNargs; -}; + res = object.toString(10); -// -// Value conversion methods -// + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack -ArgumentParser.prototype._getValues = function (action, argStrings) { - var self = this; + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} - // for everything but PARSER args, strip out '--' - if (action.nargs !== c.PARSER && action.nargs !== c.REMAINDER) { - argStrings = argStrings.filter(function (arrayElement) { - return arrayElement !== '--'; - }); - } +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} - var value, argString; +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - // optional argument produces a default when not present - if (argStrings.length === 0 && action.nargs === c.OPTIONAL) { - value = (action.isOptional()) ? action.constant : action.defaultValue; +/***/ }), +/* 418 */, +/* 419 */, +/* 420 */, +/* 421 */, +/* 422 */, +/* 423 */, +/* 424 */, +/* 425 */, +/* 426 */, +/* 427 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (typeof (value) === 'string') { - value = this._getValue(action, value); - this._checkValue(action, value); - } +"use strict"; - // when nargs='*' on a positional, if there were no command-line - // args, use the default if it is anything other than None - } else if (argStrings.length === 0 && action.nargs === c.ZERO_OR_MORE && - action.optionStrings.length === 0) { +// Older verions of Node.js might not have `util.getSystemErrorName()`. +// In that case, fall back to a deprecated internal. +const util = __webpack_require__(669); - value = (action.defaultValue || argStrings); - this._checkValue(action, value); +let uv; - // single argument or optional argument produces a single value - } else if (argStrings.length === 1 && - (!action.nargs || action.nargs === c.OPTIONAL)) { +if (typeof util.getSystemErrorName === 'function') { + module.exports = util.getSystemErrorName; +} else { + try { + uv = process.binding('uv'); - argString = argStrings[0]; - value = this._getValue(action, argString); - this._checkValue(action, value); + if (typeof uv.errname !== 'function') { + throw new TypeError('uv.errname is not a function'); + } + } catch (err) { + console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); + uv = null; + } - // REMAINDER arguments convert all values, checking none - } else if (action.nargs === c.REMAINDER) { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); + module.exports = code => errname(uv, code); +} - // PARSER arguments convert all values, but check only the first - } else if (action.nargs === c.PARSER) { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); - this._checkValue(action, value[0]); +// Used for testing the fallback behavior +module.exports.__test__ = errname; - // all other types of nargs produce a list - } else { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); - value.forEach(function (v) { - self._checkValue(action, v); - }); - } +function errname(uv, code) { + if (uv) { + return uv.errname(code); + } - // return the converted value - return value; -}; + if (!(code < 0)) { + throw new Error('err >= 0'); + } -ArgumentParser.prototype._getValue = function (action, argString) { - var result; + return `Unknown system error ${code}`; +} - var typeFunction = this._registryGet('type', action.type, action.type); - if (typeof typeFunction !== 'function') { - var message = format('%s is not callable', typeFunction); - throw argumentErrorHelper(action, message); - } - // convert the value to the appropriate type - try { - result = typeFunction(argString); - // ArgumentTypeErrors indicate errors - // If action.type is not a registered string, it is a function - // Try to deduce its name for inclusion in the error message - // Failing that, include the error message it raised. - } catch (e) { - var name = null; - if (typeof action.type === 'string') { - name = action.type; - } else { - name = action.type.name || action.type.displayName || ''; - } - var msg = format('Invalid %s value: %s', name, argString); - if (name === '') { msg += '\n' + e.message; } - throw argumentErrorHelper(action, msg); - } - // return the converted value - return result; -}; +/***/ }), +/* 428 */, +/* 429 */, +/* 430 */, +/* 431 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -ArgumentParser.prototype._checkValue = function (action, value) { - // converted value must be one of the choices (if specified) - var choices = action.choices; - if (choices) { - // choise for argument can by array or string - if ((typeof choices === 'string' || Array.isArray(choices)) && - choices.indexOf(value) !== -1) { - return; +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +/** + * 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; } - // choise for subparsers can by only hash - if (typeof choices === 'object' && !Array.isArray(choices) && choices[value]) { - return; + 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 utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return 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 - if (typeof choices === 'string') { - choices = choices.split('').join(', '); - } else if (Array.isArray(choices)) { - choices = choices.join(', '); - } else { - choices = Object.keys(choices).join(', '); - } - var message = format('Invalid choice: %s (choose from [%s])', value, choices); - throw argumentErrorHelper(action, message); - } -}; +/***/ }), +/* 432 */, +/* 433 */, +/* 434 */, +/* 435 */, +/* 436 */, +/* 437 */, +/* 438 */, +/* 439 */, +/* 440 */, +/* 441 */, +/* 442 */, +/* 443 */ +/***/ (function(module) { -// -// Help formatting methods -// +function getBuild(project, buildConfiguration) { + const build = buildConfiguration.build + ? overrideProperties( + buildConfiguration.default, + buildConfiguration.build.find( + projectBuild => project === projectBuild.project + ) + ) + : buildConfiguration.default; + delete build.project; + return manipulateArchiveArtifacts(manipulateProperties(build), project); +} /** - * ArgumentParser#formatUsage -> string - * - * Return usage string + * Override properties from one object to another * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.formatUsage = function () { - var formatter = this._getFormatter(); - formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); - return formatter.formatHelp(); -}; - -/** - * ArgumentParser#formatHelp -> string - * - * Return help - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.formatHelp = function () { - var formatter = this._getFormatter(); - - // usage - formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + * @param {Object} target + * @param {Object} source + */ +function overrideProperties(target, source) { + const targetClone = { ...target }; + const sourceClone = { ...source }; + Object.entries(targetClone) + .filter(([key]) => sourceClone[key]) + .forEach(([key, value]) => { + if (typeof value === "object") { + targetClone[key] = overrideProperties( + targetClone[key], + sourceClone[key] + ); + } else { + targetClone[key] = sourceClone[key]; + } + }); - // description - formatter.addText(this.description); + Object.keys(sourceClone) + .filter(key => !targetClone[key]) + .forEach(key => (targetClone[key] = sourceClone[key])); + return targetClone; +} - // positionals, optionals and user-defined groups - this._actionGroups.forEach(function (actionGroup) { - formatter.startSection(actionGroup.title); - formatter.addText(actionGroup.description); - formatter.addArguments(actionGroup._groupActions); - formatter.endSection(); +/** + * manipulates certains properties from an object. It basically converts String lists to Arrays + * @param {Object} properties the properties to manipulate + */ +function manipulateProperties(properties) { + const propertiesClone = { ...properties }; + Object.entries(propertiesClone).forEach(([key, value]) => { + if (typeof value === "object" && !Array.isArray(value)) { + propertiesClone[key] = manipulateProperties(propertiesClone[key]); + } else { + propertiesClone[key] = value.includes("\n") + ? value.split("\n").filter(e => e) + : value; + } }); + return propertiesClone; +} - // epilog - formatter.addText(this.epilog); +/** + * manipulates `archive-artifacts` properties + * @param {Object} build the node's build section + * @param {String} project the project name + */ +function manipulateArchiveArtifacts(build, project) { + const archiveArtifacts = build["archive-artifacts"]; + if (archiveArtifacts) { + archiveArtifacts["if-no-files-found"] = build["archive-artifacts"][ + "if-no-files-found" + ] + ? archiveArtifacts["if-no-files-found"] + : "warn"; + archiveArtifacts.dependencies = archiveArtifacts.dependencies + ? archiveArtifacts.dependencies + : "none"; + archiveArtifacts.name = archiveArtifacts.name + ? archiveArtifacts.name + : project; + archiveArtifacts.paths = treatArchiveArtifactsPath(archiveArtifacts.path); + } + return build; +} + +function treatArchiveArtifactsPath(archiveArtifactsPath) { + return (Array.isArray(archiveArtifactsPath) + ? archiveArtifactsPath + : archiveArtifactsPath.split("\n") + ) + .filter(line => line) + .reduce((acc, pathExpression) => { + acc.push(convertPathExpressionToPath(pathExpression)); + return acc; + }, []); +} - // determine help from format above - return formatter.formatHelp(); -}; +function convertPathExpressionToPath(pathExpression) { + const match = pathExpression.match(/([^@]*)@?(always|success|failure)?/); + return match + ? { + path: match[1], + on: match[2] ? match[2] : "success" + } + : pathExpression; +} -ArgumentParser.prototype._getFormatter = function () { - var FormatterClass = this.formatterClass; - var formatter = new FormatterClass({ prog: this.prog }); - return formatter; -}; +function treatProject(project, buildConfiguration) { + return { build: getBuild(project, buildConfiguration) }; +} -// -// Print functions -// +module.exports = { treatProject }; -/** - * ArgumentParser#printUsage() -> Void - * - * Print usage - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.printUsage = function () { - this._printMessage(this.formatUsage()); -}; -/** - * ArgumentParser#printHelp() -> Void - * - * Print help - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.printHelp = function () { - this._printMessage(this.formatHelp()); -}; +/***/ }), +/* 444 */, +/* 445 */, +/* 446 */, +/* 447 */, +/* 448 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -ArgumentParser.prototype._printMessage = function (message, stream) { - if (!stream) { - stream = process.stdout; - } - if (message) { - stream.write('' + message); - } -}; +"use strict"; -// -// Exit functions -// -/** - * ArgumentParser#exit(status=0, message) -> Void - * - status (int): exit status - * - message (string): message - * - * Print message in stderr/stdout and exit program - **/ -ArgumentParser.prototype.exit = function (status, message) { - if (message) { - if (status === 0) { - this._printMessage(message); - } else { - this._printMessage(message, process.stderr); - } - } +Object.defineProperty(exports, '__esModule', { value: true }); - process.exit(status); -}; +var universalUserAgent = __webpack_require__(796); +var beforeAfterHook = __webpack_require__(523); +var request = __webpack_require__(753); +var graphql = __webpack_require__(898); +var authToken = __webpack_require__(813); -/** - * ArgumentParser#error(message) -> Void - * - err (Error|string): message - * - * Error method Prints a usage message incorporating the message to stderr and - * exits. If you override this in a subclass, - * it should not return -- it should - * either exit or throw an exception. - * - **/ -ArgumentParser.prototype.error = function (err) { - var message; - if (err instanceof Error) { - if (this.debug === true) { - throw err; - } - message = err.message; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); } else { - message = err; - } - var msg = format('%s: error: %s', this.prog, message) + c.EOL; - - if (this.debug === true) { - throw new Error(msg); + obj[key] = value; } - this.printUsage(process.stderr); - - return this.exit(2, msg); -}; + return obj; +} -module.exports = ArgumentParser; +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } -/***/ }), -/* 453 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + return keys; +} -var once = __webpack_require__(969) -var eos = __webpack_require__(9) -var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } -var isFn = function (fn) { - return typeof fn === 'function' + return target; } -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) -} +const VERSION = "2.5.4"; -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} +class Octokit { + constructor(options = {}) { + const hook = new beforeAfterHook.Collection(); + const requestDefaults = { + baseUrl: request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; // prepend default user agent with `options.userAgent` if set -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - var closed = false - stream.on('close', function () { - closed = true - }) + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } - 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 + this.request = request.request.defaults(requestDefaults); + this.graphql = graphql.withCustomRequest(this.request).defaults(_objectSpread2(_objectSpread2({}, requestDefaults), {}, { + baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api") + })); + this.log = Object.assign({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, options.log); + this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance + // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred. + // (2) If only `options.auth` is set, use the default token authentication strategy. + // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. + // TODO: type `options.auth` based on `options.authStrategy`. - if (isFn(stream.destroy)) return stream.destroy() + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - callback(err || new Error('stream was destroyed')) + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const auth = options.authStrategy(Object.assign({ + request: this.request + }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } // apply plugins + // https://stackoverflow.com/a/16345172 + + + const classConstructor = this.constructor; + classConstructor.plugins.forEach(plugin => { + Object.assign(this, plugin(this, options)); + }); } -} -var call = function (fn) { - fn() -} + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null)); + } -var pipe = function (from, to) { - return from.pipe(to) -} + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ -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') + static plugin(p1, ...p2) { + var _a; - 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) - }) - }) + if (p1 instanceof Array) { + console.warn(["Passing an array of plugins to Octokit.plugin() has been deprecated.", "Instead of:", " Octokit.plugin([plugin1, plugin2, ...])", "Use:", " Octokit.plugin(plugin1, plugin2, ...)"].join("\n")); + } + + const currentPlugins = this.plugins; + let newPlugins = [...(p1 instanceof Array ? p1 : [p1]), ...p2]; + const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); + return NewOctokit; + } - return streams.reduce(pipe) } +Octokit.VERSION = VERSION; +Octokit.plugins = []; -module.exports = pump +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map /***/ }), -/* 454 */ -/***/ (function(module, exports, __webpack_require__) { +/* 449 */, +/* 450 */, +/* 451 */, +/* 452 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/** + * class ArgumentParser + * + * Object for parsing command line strings into js objects. + * + * Inherited from [[ActionContainer]] + **/ -Object.defineProperty(exports, '__esModule', { value: true }); +var util = __webpack_require__(669); +var format = __webpack_require__(669).format; +var Path = __webpack_require__(622); +var sprintf = __webpack_require__(552).sprintf; -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +// Constants +var c = __webpack_require__(45); -var Stream = _interopDefault(__webpack_require__(413)); -var http = _interopDefault(__webpack_require__(605)); -var Url = _interopDefault(__webpack_require__(835)); -var https = _interopDefault(__webpack_require__(34)); -var zlib = _interopDefault(__webpack_require__(761)); +var $$ = __webpack_require__(255); -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js +var ActionContainer = __webpack_require__(614); -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; +// Errors +var argumentErrorHelper = __webpack_require__(287); -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); +var HelpFormatter = __webpack_require__(532); -class Blob { - constructor() { - this[TYPE] = ''; +var Namespace = __webpack_require__(515); - const blobParts = arguments[0]; - const options = arguments[1]; - const buffers = []; - let size = 0; +/** + * new ArgumentParser(options) + * + * Create a new ArgumentParser object. + * + * ##### Options: + * - `prog` The name of the program (default: Path.basename(process.argv[1])) + * - `usage` A usage message (default: auto-generated from arguments) + * - `description` A description of what the program does + * - `epilog` Text following the argument descriptions + * - `parents` Parsers whose arguments should be copied into this one + * - `formatterClass` HelpFormatter class for printing help messages + * - `prefixChars` Characters that prefix optional arguments + * - `fromfilePrefixChars` Characters that prefix files containing additional arguments + * - `argumentDefault` The default value for all arguments + * - `addHelp` Add a -h/-help option + * - `conflictHandler` Specifies how to handle conflicting argument names + * - `debug` Enable debug mode. Argument errors throw exception in + * debug mode and process.exit in normal. Used for development and + * testing (default: false) + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects + **/ +function ArgumentParser(options) { + if (!(this instanceof ArgumentParser)) { + return new ArgumentParser(options); + } + var self = this; + options = options || {}; - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } + options.description = (options.description || null); + options.argumentDefault = (options.argumentDefault || null); + options.prefixChars = (options.prefixChars || '-'); + options.conflictHandler = (options.conflictHandler || 'error'); + ActionContainer.call(this, options); - this[BUFFER] = Buffer.concat(buffers); + options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp; + options.parents = options.parents || []; + // default program name + options.prog = (options.prog || Path.basename(process.argv[1])); + this.prog = options.prog; + this.usage = options.usage; + this.epilog = options.epilog; + this.version = options.version; - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; + this.debug = (options.debug === true); - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); + this.formatterClass = (options.formatterClass || HelpFormatter); + this.fromfilePrefixChars = options.fromfilePrefixChars || null; + this._positionals = this.addArgumentGroup({ title: 'Positional arguments' }); + this._optionals = this.addArgumentGroup({ title: 'Optional arguments' }); + this._subparsers = null; - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} + // register types + function FUNCTION_IDENTITY(o) { + return o; + } + this.register('type', 'auto', FUNCTION_IDENTITY); + this.register('type', null, FUNCTION_IDENTITY); + this.register('type', 'int', function (x) { + var result = parseInt(x, 10); + if (isNaN(result)) { + throw new Error(x + ' is not a valid integer.'); + } + return result; + }); + this.register('type', 'float', function (x) { + var result = parseFloat(x); + if (isNaN(result)) { + throw new Error(x + ' is not a valid float.'); + } + return result; + }); + this.register('type', 'string', function (x) { + return '' + x; + }); -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); + // add help and version arguments if necessary + var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0]; + if (options.addHelp) { + this.addArgument( + [ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ], + { + action: 'help', + defaultValue: c.SUPPRESS, + help: 'Show this help message and exit.' + } + ); + } + if (typeof this.version !== 'undefined') { + this.addArgument( + [ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ], + { + action: 'version', + version: this.version, + defaultValue: c.SUPPRESS, + help: "Show program's version number and exit." + } + ); + } -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); + // add parent arguments and defaults + options.parents.forEach(function (parent) { + self._addContainerActions(parent); + if (typeof parent._defaults !== 'undefined') { + for (var defaultKey in parent._defaults) { + if (parent._defaults.hasOwnProperty(defaultKey)) { + self._defaults[defaultKey] = parent._defaults[defaultKey]; + } + } + } + }); +} -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ +util.inherits(ArgumentParser, ActionContainer); /** - * Create FetchError instance + * ArgumentParser#addSubparsers(options) -> [[ActionSubparsers]] + * - options (object): hash of options see [[ActionSubparsers.new]] * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); + * See also [subcommands][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#sub-commands + **/ +ArgumentParser.prototype.addSubparsers = function (options) { + if (this._subparsers) { + this.error('Cannot have multiple subparser arguments.'); + } - this.message = message; - this.type = type; + options = options || {}; + options.debug = (this.debug === true); + options.optionStrings = []; + options.parserClass = (options.parserClass || ArgumentParser); - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; + + if (!!options.title || !!options.description) { + + this._subparsers = this.addArgumentGroup({ + title: (options.title || 'subcommands'), + description: options.description + }); + delete options.title; + delete options.description; + + } else { + this._subparsers = this._positionals; } - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (!options.prog) { + var formatter = this._getFormatter(); + var positionals = this._getPositionalActions(); + var groups = this._mutuallyExclusiveGroups; + formatter.addUsage(this.usage, positionals, groups, ''); + options.prog = formatter.formatHelp().trim(); + } -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; + // create the parsers action and add it to the positionals list + var ParsersClass = this._popActionClass(options, 'parsers'); + var action = new ParsersClass(options); + this._subparsers._addAction(action); -let convert; -try { - convert = __webpack_require__(18).convert; -} catch (e) {} + // return the created parsers action + return action; +}; -const INTERNALS = Symbol('Body internals'); +ArgumentParser.prototype._addAction = function (action) { + if (action.isOptional()) { + this._optionals._addAction(action); + } else { + this._positionals._addAction(action); + } + return action; +}; + +ArgumentParser.prototype._getOptionalActions = function () { + return this._actions.filter(function (action) { + return action.isOptional(); + }); +}; + +ArgumentParser.prototype._getPositionalActions = function () { + return this._actions.filter(function (action) { + return action.isPositional(); + }); +}; -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; /** - * Body mixin + * ArgumentParser#parseArgs(args, namespace) -> Namespace|Object + * - args (array): input elements + * - namespace (Namespace|Object): result object * - * Ref: https://fetch.spec.whatwg.org/#body + * Parsed args and throws error if some arguments are not recognized * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-parse-args-method + **/ +ArgumentParser.prototype.parseArgs = function (args, namespace) { + var argv; + var result = this.parseKnownArgs(args, namespace); - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; + args = result[0]; + argv = result[1]; + if (argv && argv.length > 0) { + this.error( + format('Unrecognized arguments: %s.', argv.join(' ')) + ); + } + return args; +}; - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; +/** + * ArgumentParser#parseKnownArgs(args, namespace) -> array + * - args (array): input options + * - namespace (Namespace|Object): result object + * + * Parse known arguments and return tuple of result object + * and unknown args + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#partial-parsing + **/ +ArgumentParser.prototype.parseKnownArgs = function (args, namespace) { + var self = this; - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} + // args default to the system args + args = args || process.argv.slice(2); -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, + // default Namespace built from parser defaults + namespace = namespace || new Namespace(); - get bodyUsed() { - return this[INTERNALS].disturbed; - }, + self._actions.forEach(function (action) { + if (action.dest !== c.SUPPRESS) { + if (!$$.has(namespace, action.dest)) { + if (action.defaultValue !== c.SUPPRESS) { + var defaultValue = action.defaultValue; + if (typeof action.defaultValue === 'string') { + defaultValue = self._getValue(action, defaultValue); + } + namespace[action.dest] = defaultValue; + } + } + } + }); - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, + Object.keys(self._defaults).forEach(function (dest) { + namespace[dest] = self._defaults[dest]; + }); - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, + // parse the arguments and exit if there are any errors + try { + var res = this._parseKnownArgs(args, namespace); - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; + namespace = res[0]; + args = res[1]; + if ($$.has(namespace, c._UNRECOGNIZED_ARGS_ATTR)) { + args = $$.arrayUnion(args, namespace[c._UNRECOGNIZED_ARGS_ATTR]); + delete namespace[c._UNRECOGNIZED_ARGS_ATTR]; + } + return [ namespace, args ]; + } catch (e) { + this.error(e); + } +}; - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, +ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) { + var self = this; - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, + var extras = []; - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, + // replace arg strings that are file references + if (this.fromfilePrefixChars !== null) { + argStrings = this._readArgsFromFiles(argStrings); + } + // map all mutually exclusive arguments to the other arguments + // they can't occur with + // Python has 'conflicts = action_conflicts.setdefault(mutex_action, [])' + // though I can't conceive of a way in which an action could be a member + // of two different mutually exclusive groups. - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; + function actionHash(action) { + // some sort of hashable key for this action + // action itself cannot be a key in actionConflicts + // I think getName() (join of optionStrings) is unique enough + return action.getName(); + } - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; + var conflicts, key; + var actionConflicts = {}; -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); + this._mutuallyExclusiveGroups.forEach(function (mutexGroup) { + mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) { + key = actionHash(mutexAction); + if (!$$.has(actionConflicts, key)) { + actionConflicts[key] = []; + } + conflicts = actionConflicts[key]; + conflicts.push.apply(conflicts, groupActions.slice(0, i)); + conflicts.push.apply(conflicts, groupActions.slice(i + 1)); + }); + }); -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + var optionStringIndices = {}; -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; + var argStringPatternParts = []; - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } + argStrings.forEach(function (argString, argStringIndex) { + if (argString === '--') { + argStringPatternParts.push('-'); + while (argStringIndex < argStrings.length) { + argStringPatternParts.push('A'); + argStringIndex++; + } + } else { + // otherwise, add the arg to the arg strings + // and note the index if it was an option + var pattern; + var optionTuple = self._parseOptional(argString); + if (!optionTuple) { + pattern = 'A'; + } else { + optionStringIndices[argStringIndex] = optionTuple; + pattern = 'O'; + } + argStringPatternParts.push(pattern); + } + }); + var argStringsPattern = argStringPatternParts.join(''); - this[INTERNALS].disturbed = true; + var seenActions = []; + var seenNonDefaultActions = []; - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - let body = this.body; + function takeAction(action, argumentStrings, optionString) { + seenActions.push(action); + var argumentValues = self._getValues(action, argumentStrings); - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argumentValues !== action.defaultValue) { + seenNonDefaultActions.push(action); + if (actionConflicts[actionHash(action)]) { + actionConflicts[actionHash(action)].forEach(function (actionConflict) { + if (seenNonDefaultActions.indexOf(actionConflict) >= 0) { + throw argumentErrorHelper( + action, + format('Not allowed with argument "%s".', actionConflict.getName()) + ); + } + }); + } + } - // body is blob - if (isBlob(body)) { - body = body.stream(); - } + if (argumentValues !== c.SUPPRESS) { + action.call(self, namespace, argumentValues, optionString); + } + } - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + function consumeOptional(startIndex) { + // get the optional identified at this index + var optionTuple = optionStringIndices[startIndex]; + var action = optionTuple[0]; + var optionString = optionTuple[1]; + var explicitArg = optionTuple[2]; - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + var actionTuples = []; - return new Body.Promise(function (resolve, reject) { - let resTimeout; + var args, argCount, start, stop; - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } + for (;;) { + if (!action) { + extras.push(argStrings[startIndex]); + return startIndex + 1; + } + if (explicitArg) { + argCount = self._matchArgument(action, 'A'); - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + var chars = self.prefixChars; + if (argCount === 0 && chars.indexOf(optionString[1]) < 0) { + actionTuples.push([ action, [], optionString ]); + optionString = optionString[0] + explicitArg[0]; + var newExplicitArg = explicitArg.slice(1) || null; + var optionalsMap = self._optionStringActions; - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } + if (Object.keys(optionalsMap).indexOf(optionString) >= 0) { + action = optionalsMap[optionString]; + explicitArg = newExplicitArg; + } else { + throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); + } + } else if (argCount === 1) { + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + stop = startIndex + 1; + args = [ explicitArg ]; + actionTuples.push([ action, args, optionString ]); + break; + } else { + // error if a double-dash option did not use the + // explicit argument + throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); + } + } else { + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } + start = startIndex + 1; + var selectedPatterns = argStringsPattern.substr(start); - accumBytes += chunk.length; - accum.push(chunk); - }); + argCount = self._matchArgument(action, selectedPatterns); + stop = start + argCount; - body.on('end', function () { - if (abort) { - return; - } - clearTimeout(resTimeout); + args = argStrings.slice(start, stop); - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} + actionTuples.push([ action, args, optionString ]); + break; + } -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } + } - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; + // add the Optional to the list and return the index at which + // the Optional's string args stopped + if (actionTuples.length < 1) { + throw new Error('length should be > 0'); + } + for (var i = 0; i < actionTuples.length; i++) { + takeAction.apply(self, actionTuples[i]); + } + return stop; + } - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + var positionals = self._getPositionalActions(); - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); + function consumePositionals(startIndex) { + // match as many Positionals as possible + var selectedPattern = argStringsPattern.substr(startIndex); + var argCounts = self._matchArgumentsPartial(positionals, selectedPattern); - // html5 - if (!res && str) { - res = /= startIndex) { + if (nextOptionStringIndex !== null) { + nextOptionStringIndex = Math.min(nextOptionStringIndex, position); + } else { + nextOptionStringIndex = position; + } + } + } -/** - * Check if `obj` is a W3C `Blob` object (which `File` inherits from) - * @param {*} obj - * @return {boolean} - */ -function isBlob(obj) { - return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); -} + if (startIndex !== nextOptionStringIndex) { + positionalsEndIndex = consumePositionals(startIndex); + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionalsEndIndex > startIndex) { + startIndex = positionalsEndIndex; + continue; + } else { + startIndex = positionalsEndIndex; + } + } -/** - * Clone body given Res/Req instance - * - * @param Mixed instance Response or Request instance - * @return Mixed - */ -function clone(instance) { - let p1, p2; - let body = instance.body; - - // don't allow cloning a used body - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used'); - } + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!optionStringIndices[startIndex]) { + var strings = argStrings.slice(startIndex, nextOptionStringIndex); + extras = extras.concat(strings); + startIndex = nextOptionStringIndex; + } + // consume the next optional and any arguments for it + startIndex = consumeOptional(startIndex); + } - // check that body is a stream and not form-data object - // note: we can't clone the form-data object without having it as a dependency - if (body instanceof Stream && typeof body.getBoundary !== 'function') { - // tee instance body - p1 = new PassThrough(); - p2 = new PassThrough(); - body.pipe(p1); - body.pipe(p2); - // set instance body to teed body and return the other teed body - instance[INTERNALS].body = p1; - body = p2; - } + // consume any positionals following the last Optional + var stopIndex = consumePositionals(startIndex); - return body; -} + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(argStrings.slice(stopIndex)); -/** - * Performs the operation "extract a `Content-Type` value from |object|" as - * specified in the specification: - * https://fetch.spec.whatwg.org/#concept-bodyinit-extract - * - * This function assumes that instance.body is present. - * - * @param Mixed instance Any options.body input - */ -function extractContentType(body) { - if (body === null) { - // body is null - return null; - } else if (typeof body === 'string') { - // body is string - return 'text/plain;charset=UTF-8'; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - return 'application/x-www-form-urlencoded;charset=UTF-8'; - } else if (isBlob(body)) { - // body is blob - return body.type || null; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return null; - } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - return null; - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - return null; - } else if (typeof body.getBoundary === 'function') { - // detect form data input from form-data module - return `multipart/form-data;boundary=${body.getBoundary()}`; - } else if (body instanceof Stream) { - // body is stream - // can't really do much about this - return null; - } else { - // Body constructor defaults other things to string - return 'text/plain;charset=UTF-8'; - } -} + // if we didn't use all the Positional objects, there were too few + // arg strings supplied. + if (positionals.length > 0) { + self.error('too few arguments'); + } -/** - * The Fetch Standard treats this as if "total bytes" is a property on the body. - * For us, we have to explicitly get it with a function. - * - * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes - * - * @param Body instance Instance of Body - * @return Number? Number of bytes, or null if not possible - */ -function getTotalBytes(instance) { - const body = instance.body; + // make sure all required actions were present + self._actions.forEach(function (action) { + if (action.required) { + if (seenActions.indexOf(action) < 0) { + self.error(format('Argument "%s" is required', action.getName())); + } + } + }); + // make sure all required groups have one option present + var actionUsed = false; + self._mutuallyExclusiveGroups.forEach(function (group) { + if (group.required) { + actionUsed = group._groupActions.some(function (action) { + return seenNonDefaultActions.indexOf(action) !== -1; + }); - if (body === null) { - // body is null - return 0; - } else if (isBlob(body)) { - return body.size; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return body.length; - } else if (body && typeof body.getLengthSync === 'function') { - // detect form data input from form-data module - if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x - body.hasKnownLength && body.hasKnownLength()) { - // 2.x - return body.getLengthSync(); - } - return null; - } else { - // body is stream - return null; - } -} + // if no actions were used, report the error + if (!actionUsed) { + var names = []; + group._groupActions.forEach(function (action) { + if (action.help !== c.SUPPRESS) { + names.push(action.getName()); + } + }); + names = names.join(' '); + var msg = 'one of the arguments ' + names + ' is required'; + self.error(msg); + } + } + }); -/** - * Write a Body to a Node.js WritableStream (e.g. http.Request) object. - * - * @param Body instance Instance of Body - * @return Void - */ -function writeToStream(dest, instance) { - const body = instance.body; + // return the updated namespace and the extra arguments + return [ namespace, extras ]; +}; +ArgumentParser.prototype._readArgsFromFiles = function (argStrings) { + // expand arguments referencing files + var self = this; + var fs = __webpack_require__(747); + var newArgStrings = []; + argStrings.forEach(function (argString) { + if (self.fromfilePrefixChars.indexOf(argString[0]) < 0) { + // for regular arguments, just add them back into the list + newArgStrings.push(argString); + } else { + // replace arguments referencing files with the file content + try { + var argstrs = []; + var filename = argString.slice(1); + var content = fs.readFileSync(filename, 'utf8'); + content = content.trim().split('\n'); + content.forEach(function (argLine) { + self.convertArgLineToArgs(argLine).forEach(function (arg) { + argstrs.push(arg); + }); + argstrs = self._readArgsFromFiles(argstrs); + }); + newArgStrings.push.apply(newArgStrings, argstrs); + } catch (error) { + return self.error(error.message); + } + } + }); + return newArgStrings; +}; - if (body === null) { - // body is null - dest.end(); - } else if (isBlob(body)) { - body.stream().pipe(dest); - } else if (Buffer.isBuffer(body)) { - // body is buffer - dest.write(body); - dest.end(); - } else { - // body is stream - body.pipe(dest); - } -} +ArgumentParser.prototype.convertArgLineToArgs = function (argLine) { + return [ argLine ]; +}; -// expose Promise -Body.Promise = global.Promise; +ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) { -/** - * headers.js - * - * Headers class offers convenient helpers - */ + // match the pattern for this action to the arg strings + var regexpNargs = new RegExp('^' + this._getNargsPattern(action)); + var matches = regexpArgStrings.match(regexpNargs); + var message; -const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + // throw an exception if we weren't able to find a match + if (!matches) { + switch (action.nargs) { + /*eslint-disable no-undefined*/ + case undefined: + case null: + message = 'Expected one argument.'; + break; + case c.OPTIONAL: + message = 'Expected at most one argument.'; + break; + case c.ONE_OR_MORE: + message = 'Expected at least one argument.'; + break; + default: + message = 'Expected %s argument(s)'; + } -function validateName(name) { - name = `${name}`; - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`); - } -} + throw argumentErrorHelper( + action, + format(message, action.nargs) + ); + } + // return the number of arguments matched + return matches[1].length; +}; -function validateValue(value) { - value = `${value}`; - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`); - } -} +ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgStrings) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + var self = this; + var result = []; + var actionSlice, pattern, matches; + var i, j; -/** - * Find the key in the map object given a header name. - * - * Returns undefined if not found. - * - * @param String name Header name - * @return String|Undefined - */ -function find(map, name) { - name = name.toLowerCase(); - for (const key in map) { - if (key.toLowerCase() === name) { - return key; - } - } - return undefined; -} + function getLength(string) { + return string.length; + } -const MAP = Symbol('map'); -class Headers { - /** - * Headers class - * - * @param Object headers Response headers - * @return Void - */ - constructor() { - let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + for (i = actions.length; i > 0; i--) { + pattern = ''; + actionSlice = actions.slice(0, i); + for (j = 0; j < actionSlice.length; j++) { + pattern += self._getNargsPattern(actionSlice[j]); + } - this[MAP] = Object.create(null); + pattern = new RegExp('^' + pattern); + matches = regexpArgStrings.match(pattern); - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); + if (matches && matches.length > 0) { + // need only groups + matches = matches.splice(1); + result = result.concat(matches.map(getLength)); + break; + } + } - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } + // return the list of arg string counts + return result; +}; - return; - } +ArgumentParser.prototype._parseOptional = function (argString) { + var action, optionString, argExplicit, optionTuples; - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } + // if it's an empty string, it was meant to be a positional + if (!argString) { + return null; + } - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } + // if it doesn't start with a prefix, it was meant to be positional + if (this.prefixChars.indexOf(argString[0]) < 0) { + return null; + } - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } + // if the option string is present in the parser, return the action + if (this._optionStringActions[argString]) { + return [ this._optionStringActions[argString], argString, null ]; + } - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } + // if it's just a single character, it was meant to be positional + if (argString.length === 1) { + return null; + } - return this[MAP][key].join(', '); - } + // if the option string before the "=" is present, return the action + if (argString.indexOf('=') >= 0) { + optionString = argString.split('=', 1)[0]; + argExplicit = argString.slice(optionString.length + 1); - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + if (this._optionStringActions[optionString]) { + action = this._optionStringActions[optionString]; + return [ action, optionString, argExplicit ]; + } + } - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + optionTuples = this._getOptionTuples(argString); - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } + // if multiple actions match, the option string was ambiguous + if (optionTuples.length > 1) { + var optionStrings = optionTuples.map(function (optionTuple) { + return optionTuple[1]; + }); + this.error(format( + 'Ambiguous option: "%s" could match %s.', + argString, optionStrings.join(', ') + )); + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (optionTuples.length === 1) { + return optionTuples[0]; + } - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (argString.match(this._regexpNegativeNumber)) { + if (!this._hasNegativeNumberOptionals.some(Boolean)) { + return null; + } + } + // if it contains a space, it was meant to be a positional + if (argString.search(' ') >= 0) { + return null; + } - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [ null, argString, null ]; +}; - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } +ArgumentParser.prototype._getOptionTuples = function (optionString) { + var result = []; + var chars = this.prefixChars; + var optionPrefix; + var argExplicit; + var action; + var actionOptionString; - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } + // option strings starting with two prefix characters are only split at + // the '=' + if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) >= 0) { + if (optionString.indexOf('=') >= 0) { + var optionStringSplit = optionString.split('=', 1); - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } + optionPrefix = optionStringSplit[0]; + argExplicit = optionStringSplit[1]; + } else { + optionPrefix = optionString; + argExplicit = null; + } - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } + for (actionOptionString in this._optionStringActions) { + if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + action = this._optionStringActions[actionOptionString]; + result.push([ action, actionOptionString, argExplicit ]); + } + } - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) < 0) { + optionPrefix = optionString; + argExplicit = null; + var optionPrefixShort = optionString.substr(0, 2); + var argExplicitShort = optionString.substr(2); - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + for (actionOptionString in this._optionStringActions) { + if (!$$.has(this._optionStringActions, actionOptionString)) continue; -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); + action = this._optionStringActions[actionOptionString]; + if (actionOptionString === optionPrefixShort) { + result.push([ action, actionOptionString, argExplicitShort ]); + } else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + result.push([ action, actionOptionString, argExplicit ]); + } + } -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); + // shouldn't ever get here + } else { + throw new Error(format('Unexpected option string: %s.', optionString)); + } + // return the collected option tuples + return result; +}; -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; +ArgumentParser.prototype._getNargsPattern = function (action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + var regexpNargs; - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} + switch (action.nargs) { + // the default (null) is assumed to be a single argument + case undefined: + case null: + regexpNargs = '(-*A-*)'; + break; + // allow zero or more arguments + case c.OPTIONAL: + regexpNargs = '(-*A?-*)'; + break; + // allow zero or more arguments + case c.ZERO_OR_MORE: + regexpNargs = '(-*[A-]*)'; + break; + // allow one or more arguments + case c.ONE_OR_MORE: + regexpNargs = '(-*A[A-]*)'; + break; + // allow any number of options or arguments + case c.REMAINDER: + regexpNargs = '([-AO]*)'; + break; + // allow one argument followed by any number of options or arguments + case c.PARSER: + regexpNargs = '(-*A[-AO]*)'; + break; + // all others should be integers + default: + regexpNargs = '(-*' + $$.repeat('-*A', action.nargs) + '-*)'; + } -const INTERNAL = Symbol('internal'); + // if this is an optional action, -- is not allowed + if (action.isOptional()) { + regexpNargs = regexpNargs.replace(/-\*/g, ''); + regexpNargs = regexpNargs.replace(/-/g, ''); + } -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} + // return the pattern + return regexpNargs; +}; -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } +// +// Value conversion methods +// - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; +ArgumentParser.prototype._getValues = function (action, argStrings) { + var self = this; - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } + // for everything but PARSER args, strip out '--' + if (action.nargs !== c.PARSER && action.nargs !== c.REMAINDER) { + argStrings = argStrings.filter(function (arrayElement) { + return arrayElement !== '--'; + }); + } - this[INTERNAL].index = index + 1; + var value, argString; - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + // optional argument produces a default when not present + if (argStrings.length === 0 && action.nargs === c.OPTIONAL) { -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); + value = (action.isOptional()) ? action.constant : action.defaultValue; -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); + if (typeof (value) === 'string') { + value = this._getValue(action, value); + this._checkValue(action, value); + } - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (argStrings.length === 0 && action.nargs === c.ZERO_OR_MORE && + action.optionStrings.length === 0) { - return obj; -} + value = (action.defaultValue || argStrings); + this._checkValue(action, value); -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} + // single argument or optional argument produces a single value + } else if (argStrings.length === 1 && + (!action.nargs || action.nargs === c.OPTIONAL)) { -const INTERNALS$1 = Symbol('Response internals'); + argString = argStrings[0]; + value = this._getValue(action, argString); + this._checkValue(action, value); -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === c.REMAINDER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === c.PARSER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + this._checkValue(action, value[0]); - Body.call(this, body, opts); + // all other types of nargs produce a list + } else { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + value.forEach(function (v) { + self._checkValue(action, v); + }); + } - const status = opts.status || 200; - const headers = new Headers(opts.headers); + // return the converted value + return value; +}; - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +ArgumentParser.prototype._getValue = function (action, argString) { + var result; - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } + var typeFunction = this._registryGet('type', action.type, action.type); + if (typeof typeFunction !== 'function') { + var message = format('%s is not callable', typeFunction); + throw argumentErrorHelper(action, message); + } - get url() { - return this[INTERNALS$1].url || ''; - } + // convert the value to the appropriate type + try { + result = typeFunction(argString); - get status() { - return this[INTERNALS$1].status; - } + // ArgumentTypeErrors indicate errors + // If action.type is not a registered string, it is a function + // Try to deduce its name for inclusion in the error message + // Failing that, include the error message it raised. + } catch (e) { + var name = null; + if (typeof action.type === 'string') { + name = action.type; + } else { + name = action.type.name || action.type.displayName || ''; + } + var msg = format('Invalid %s value: %s', name, argString); + if (name === '') { msg += '\n' + e.message; } + throw argumentErrorHelper(action, msg); + } + // return the converted value + return result; +}; - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } +ArgumentParser.prototype._checkValue = function (action, value) { + // converted value must be one of the choices (if specified) + var choices = action.choices; + if (choices) { + // choise for argument can by array or string + if ((typeof choices === 'string' || Array.isArray(choices)) && + choices.indexOf(value) !== -1) { + return; + } + // choise for subparsers can by only hash + if (typeof choices === 'object' && !Array.isArray(choices) && choices[value]) { + return; + } - get redirected() { - return this[INTERNALS$1].counter > 0; - } + if (typeof choices === 'string') { + choices = choices.split('').join(', '); + } else if (Array.isArray(choices)) { + choices = choices.join(', '); + } else { + choices = Object.keys(choices).join(', '); + } + var message = format('Invalid choice: %s (choose from [%s])', value, choices); + throw argumentErrorHelper(action, message); + } +}; - get statusText() { - return this[INTERNALS$1].statusText; - } +// +// Help formatting methods +// - get headers() { - return this[INTERNALS$1].headers; - } +/** + * ArgumentParser#formatUsage -> string + * + * Return usage string + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatUsage = function () { + var formatter = this._getFormatter(); + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + return formatter.formatHelp(); +}; - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} +/** + * ArgumentParser#formatHelp -> string + * + * Return help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatHelp = function () { + var formatter = this._getFormatter(); -Body.mixIn(Response.prototype); + // usage + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); + // description + formatter.addText(this.description); -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); + // positionals, optionals and user-defined groups + this._actionGroups.forEach(function (actionGroup) { + formatter.startSection(actionGroup.title); + formatter.addText(actionGroup.description); + formatter.addArguments(actionGroup._groupActions); + formatter.endSection(); + }); -const INTERNALS$2 = Symbol('Request internals'); + // epilog + formatter.addText(this.epilog); -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; + // determine help from format above + return formatter.formatHelp(); +}; -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; +ArgumentParser.prototype._getFormatter = function () { + var FormatterClass = this.formatterClass; + var formatter = new FormatterClass({ prog: this.prog }); + return formatter; +}; + +// +// Print functions +// /** - * Check if a value is an instance of Request. + * ArgumentParser#printUsage() -> Void * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} + * Print usage + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printUsage = function () { + this._printMessage(this.formatUsage()); +}; /** - * Request class + * ArgumentParser#printHelp() -> Void * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parse_url(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); - } - input = {}; - } else { - parsedURL = parse_url(input.url); - } + * Print help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printHelp = function () { + this._printMessage(this.formatHelp()); +}; - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +ArgumentParser.prototype._printMessage = function (message, stream) { + if (!stream) { + stream = process.stdout; + } + if (message) { + stream.write('' + message); + } +}; - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } +// +// Exit functions +// - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; +/** + * ArgumentParser#exit(status=0, message) -> Void + * - status (int): exit status + * - message (string): message + * + * Print message in stderr/stdout and exit program + **/ +ArgumentParser.prototype.exit = function (status, message) { + if (message) { + if (status === 0) { + this._printMessage(message); + } else { + this._printMessage(message, process.stderr); + } + } - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); + process.exit(status); +}; - const headers = new Headers(init.headers || input.headers || {}); +/** + * ArgumentParser#error(message) -> Void + * - err (Error|string): message + * + * Error method Prints a usage message incorporating the message to stderr and + * exits. If you override this in a subclass, + * it should not return -- it should + * either exit or throw an exception. + * + **/ +ArgumentParser.prototype.error = function (err) { + var message; + if (err instanceof Error) { + if (this.debug === true) { + throw err; + } + message = err.message; + } else { + message = err; + } + var msg = format('%s: error: %s', this.prog, message) + c.EOL; - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } + if (this.debug === true) { + throw new Error(msg); + } - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; + this.printUsage(process.stderr); - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } + return this.exit(2, msg); +}; - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; +module.exports = ArgumentParser; - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - get method() { - return this[INTERNALS$2].method; - } +/***/ }), +/* 453 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } +var once = __webpack_require__(969) +var eos = __webpack_require__(9) +var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes - get headers() { - return this[INTERNALS$2].headers; - } +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) - get redirect() { - return this[INTERNALS$2].redirect; - } +var isFn = function (fn) { + return typeof fn === 'function' +} - get signal() { - return this[INTERNALS$2].signal; - } +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) +} - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) } -Body.mixIn(Request.prototype); +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); + var closed = false + stream.on('close', function () { + closed = true + }) -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } + 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 - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } + if (isFn(stream.destroy)) return stream.destroy() - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } + callback(err || new Error('stream was destroyed')) + } +} - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } +var call = function (fn) { + fn() +} - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } +var pipe = function (from, to) { + return from.pipe(to) +} - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } + 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) + }) + }) - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); + return streams.reduce(pipe) +} + +module.exports = pump + + +/***/ }), +/* 454 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__webpack_require__(413)); +var http = _interopDefault(__webpack_require__(605)); +var Url = _interopDefault(__webpack_require__(835)); +var https = _interopDefault(__webpack_require__(34)); +var zlib = _interopDefault(__webpack_require__(761)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + /** - * abort-error.js + * fetch-error.js * - * AbortError interface for cancelled requests + * FetchError interface for operational errors */ /** - * Create AbortError instance + * Create FetchError instance * * @param String message Error message for human - * @return AbortError + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError */ -function AbortError(message) { +function FetchError(message, type, systemError) { Error.call(this, message); - this.type = 'aborted'; this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; +let convert; +try { + convert = __webpack_require__(18).convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; /** - * Fetch function + * Body mixin * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; +function Body(body) { + var _this = this; - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - let response = null; + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} - // send request - const req = send(options); - let reqTimeout; +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } + get bodyUsed() { + return this[INTERNALS].disturbed; + }, - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf }); - } + }); + }, - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } }); + }, - req.on('response', function (res) { - clearTimeout(reqTimeout); + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, - const headers = createHeadersLenient(res.headers); + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; - // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout - }; +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } + this[INTERNALS].disturbed = true; - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); + let body = this.body; - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + // body is blob + if (isBlob(body)) { + body = body.stream(); + } - // HTTP-network fetch step 12.1.1.4: handle content codings + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); } + }); - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); + body.on('data', function (chunk) { + if (abort || chunk === null) { return; } - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); return; } - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); + accumBytes += chunk.length; + accum.push(chunk); }); - writeToStream(req, request); + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); }); } + /** - * Redirect code matching + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding * - * @param Number code Status code - * @return Boolean + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; - -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; - - -/***/ }), -/* 455 */, -/* 456 */, -/* 457 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -/*eslint-disable max-len,no-use-before-define*/ - -var common = __webpack_require__(740); -var YAMLException = __webpack_require__(556); -var Mark = __webpack_require__(180); -var DEFAULT_SAFE_SCHEMA = __webpack_require__(830); -var DEFAULT_FULL_SCHEMA = __webpack_require__(910); - +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -var _hasOwnProperty = Object.prototype.hasOwnProperty; + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + // html5 + if (!res && str) { + res = /> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } } +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; +// expose Promise +Body.Promise = global.Promise; - this.documents = []; +/** + * headers.js + * + * Headers class offers convenient helpers + */ - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } } - -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } } -function throwError(state, message) { - throw generateError(state, message); +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; } -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + this[MAP] = Object.create(null); -var directiveHandlers = { + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); - YAML: function handleYamlDirective(state, name, args) { + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } + return; + } - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } + return this[MAP][key].join(', '); + } - state.version = args[0]; - state.checkLineBreaks = (minor < 2); + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; - TAG: function handleTagDirective(state, name, args) { + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } - var handle, prefix; + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } - handle = args[0]; - prefix = args[1]; + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } - state.tagMap[handle] = prefix; - } -}; + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); - if (start < end) { - _result = state.input.slice(start, end); +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - state.result += _result; - } + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); } -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; +const INTERNAL = Symbol('internal'); - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; } -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } + this[INTERNAL].index = index + 1; + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - keyNode = String(keyNode); +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); - if (_result === null) { - _result = {}; - } +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } - return _result; + return obj; } -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; } -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); +const INTERNALS$1 = Symbol('Response internals'); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (is_EOL(ch)) { - readLineBreak(state); + Body.call(this, body, opts); - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; + const status = opts.status || 200; + const headers = new Headers(opts.headers); - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } - return lineBreaks; -} + get url() { + return this[INTERNALS$1].url || ''; + } -function testDocumentSeparator(state) { - var _position = state.position, - ch; + get status() { + return this[INTERNALS$1].status; + } - ch = state.input.charCodeAt(_position); + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { + get redirected() { + return this[INTERNALS$1].counter > 0; + } - _position += 3; + get statusText() { + return this[INTERNALS$1].statusText; + } - ch = state.input.charCodeAt(_position); + get headers() { + return this[INTERNALS$1].headers; + } - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } } -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} +Body.mixIn(Response.prototype); +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); - ch = state.input.charCodeAt(state.position); +const INTERNALS$2 = Symbol('Request internals'); - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } + let parsedURL; - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } - if (is_WS_OR_EOL(preceding)) { - break; - } + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } + const headers = new Headers(init.headers || input.headers || {}); - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - ch = state.input.charCodeAt(++state.position); - } + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; - captureSegment(state, captureStart, captureEnd, false); + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } - if (state.result) { - return true; - } + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; - state.kind = _kind; - state.result = _result; - return false; -} + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; + get method() { + return this[INTERNALS$2].method; + } - ch = state.input.charCodeAt(state.position); + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } - if (ch !== 0x27/* ' */) { - return false; - } + get headers() { + return this[INTERNALS$2].headers; + } - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + get redirect() { + return this[INTERNALS$2].redirect; + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + get signal() { + return this[INTERNALS$2].signal; + } - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; +Body.mixIn(Request.prototype); - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); - } else { - state.position++; - captureEnd = state.position; - } - } +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } - ch = state.input.charCodeAt(state.position); + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } - if (ch !== 0x22/* " */) { - return false; - } + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} - } else { - throwError(state, 'expected hexadecimal character'); - } - } +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ - state.result += charFromCodepoint(hexResult); +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); - state.position++; + this.type = 'aborted'; + this.message = message; - } else { - throwError(state, 'unknown escape sequence'); - } + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} - captureStart = captureEnd = state.position; +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { - } else { - state.position++; - captureEnd = state.position; - } - } + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} + Body.Promise = fetch.Promise; -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); - ch = state.input.charCodeAt(state.position); + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } + let response = null; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; - ch = state.input.charCodeAt(++state.position); + if (signal && signal.aborted) { + abort(); + return; + } - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; - ch = state.input.charCodeAt(state.position); + // send request + const req = send(options); + let reqTimeout; - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); + req.on('response', function (res) { + clearTimeout(reqTimeout); - ch = state.input.charCodeAt(state.position); + const headers = createHeadersLenient(res.headers); - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); - } + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); - skipSeparationSpace(state, true, nodeIndent); + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } - ch = state.input.charCodeAt(state.position); + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; - throwError(state, 'unexpected end of the stream within a flow collection'); -} + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } - ch = state.input.charCodeAt(state.position); + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); - state.kind = 'scalar'; - state.result = ''; + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } + // HTTP-network fetch step 12.1.1.4: handle content codings - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } - } else { - break; - } - } + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } - ch = state.input.charCodeAt(state.position); + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; - if (is_EOL(ch)) { - emptyLines++; - continue; - } +// expose Promise +fetch.Promise = global.Promise; - // End of the scalar. - if (state.lineIndent < textIndent) { +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - // Break this `while` cycle and go to the funciton's epilogue. - break; - } +/***/ }), +/* 455 */, +/* 456 */, +/* 457 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // Folded style: use fancy rules to handle line breaks. - if (folding) { +"use strict"; - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); +/*eslint-disable max-len,no-use-before-define*/ - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } +var common = __webpack_require__(740); +var YAMLException = __webpack_require__(556); +var Mark = __webpack_require__(180); +var DEFAULT_SAFE_SCHEMA = __webpack_require__(830); +var DEFAULT_FULL_SCHEMA = __webpack_require__(910); - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } +var _hasOwnProperty = Object.prototype.hasOwnProperty; - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; - captureSegment(state, captureStart, state.position, false); - } - return true; -} +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - ch = state.input.charCodeAt(state.position); - while (ch !== 0) { +function _class(obj) { return Object.prototype.toString.call(obj); } - if (ch !== 0x2D/* - */) { - break; - } +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} - following = state.input.charCodeAt(state.position + 1); +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} - if (!is_WS_OR_EOL(following)) { - break; - } +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} - detected = true; - state.position++; +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } +function fromHexCode(c) { + var lc; - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - ch = state.input.charCodeAt(state.position); + /*eslint-disable no-bitwise*/ + lc = c | 0x20; - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; } - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; + return -1; } -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; } - ch = state.input.charCodeAt(state.position); + return -1; +} - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - state.position += 1; - ch = following; +function State(input, options) { + this.input = input; - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); + this.documents = []; - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } +} - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } +function throwError(state, message) { + throw generateError(state, message); +} - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - } else { - break; // Reading is done. Go to the epilogue. - } +var directiveHandlers = { - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } + YAML: function handleYamlDirective(state, name, args) { - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } + var match, major, minor; - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); } - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); } - } - // - // Epilogue. - // + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); - return detected; -} + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; + state.version = args[0]; + state.checkLineBreaks = (minor < 2); - ch = state.input.charCodeAt(state.position); + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, - if (ch !== 0x21/* ! */) return false; + TAG: function handleTagDirective(state, name, args) { - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } + var handle, prefix; - ch = state.input.charCodeAt(++state.position); + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); + handle = args[0]; + prefix = args[1]; - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } - } else { - tagHandle = '!'; - } + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } - _position = state.position; + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); + state.tagMap[handle] = prefix; + } +}; - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } + if (start < end) { + _result = state.input.slice(start, end); - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); } } - - ch = state.input.charCodeAt(++state.position); + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); } - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } + state.result += _result; } +} - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; + sourceKeys = Object.keys(source); - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } } - - return true; } -function readAnchorProperty(state) { - var _position, - ch; +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; - ch = state.input.charCodeAt(state.position); + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); - if (ch !== 0x26/* & */) return false; + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } } - ch = state.input.charCodeAt(++state.position); - _position = state.position; + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; } - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; } - state.anchor = state.input.slice(_position, state.position); - return true; + return _result; } -function readAlias(state) { - var _position, alias, - ch; +function readLineBreak(state) { + var ch; ch = state.input.charCodeAt(state.position); - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!state.anchorMap.hasOwnProperty(alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); } - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; + state.line += 1; + state.lineStart = state.position; } -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } + } else { + break; } } - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); } - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } + return lineBreaks; +} - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } +function testDocumentSeparator(state) { + var _position = state.position, + ch; - blockIndent = state.position - state.lineStart; + ch = state.input.charCodeAt(_position); - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { - } else if (readAlias(state)) { - hasContent = true; + _position += 3; - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } + ch = state.input.charCodeAt(_position); - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } - if (state.tag === null) { - state.tag = '?'; - } - } + return false; +} - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); } +} - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - } - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); + ch = state.input.charCodeAt(state.position); - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; } + } - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; } - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { break; } - if (is_EOL(ch)) break; + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - _position = state.position; + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; } - - directiveArgs.push(state.input.slice(_position, state.position)); } - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; } - } - - skipSeparationSpace(state, true, -1); - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); + ch = state.input.charCodeAt(++state.position); } - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); + captureSegment(state, captureStart, captureEnd, false); - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + if (state.result) { + return true; } - state.documents.push(state.result); + state.kind = _kind; + state.result = _result; + return false; +} - if (state.position === state.lineStart && testDocumentSeparator(state)) { +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } + ch = state.input.charCodeAt(state.position); - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; + if (ch !== 0x27/* ' */) { + return false; } -} + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; -function loadDocuments(input, options) { - input = String(input); - options = options || {}; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - if (input.length !== 0) { + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; } } - var state = new State(input, options); + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} - var nullpos = input.indexOf('\0'); +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; } - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; - while (state.position < (state.length - 1)) { - readDocument(state); - } + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - return state.documents; -} + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; - var documents = loadDocuments(input, options); + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); - if (typeof iterator !== 'function') { - return documents; - } + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} + } else { + throwError(state, 'expected hexadecimal character'); + } + } + state.result += charFromCodepoint(hexResult); -function load(input, options) { - var documents = loadDocuments(input, options); + state.position++; - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} + } else { + throwError(state, 'unknown escape sequence'); + } + captureStart = captureEnd = state.position; -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + } else { + state.position++; + captureEnd = state.position; + } + } -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); + throwError(state, 'unexpected end of the stream within a double quoted scalar'); } +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -/***/ }), -/* 458 */, -/* 459 */, -/* 460 */, -/* 461 */, -/* 462 */ -/***/ (function(module) { + ch = state.input.charCodeAt(++state.position); -"use strict"; + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + ch = state.input.charCodeAt(state.position); -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; - return arg; -} + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } - // Algorithm below is based on https://qntm.org/cmd + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + ch = state.input.charCodeAt(state.position); - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } - // All other backslashes occur literally + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } - // Quote the whole thing: - arg = `"${arg}"`; + skipSeparationSpace(state, true, nodeIndent); - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + ch = state.input.charCodeAt(state.position); - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; } + } - return arg; + throwError(state, 'unexpected end of the stream within a flow collection'); } -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; - - -/***/ }), -/* 463 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; -"use strict"; + ch = state.input.charCodeAt(state.position); + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } -Object.defineProperty(exports, '__esModule', { value: true }); + state.kind = 'scalar'; + state.result = ''; -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); -var deprecation = __webpack_require__(692); -var once = _interopDefault(__webpack_require__(969)); - -const logOnce = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } - this.name = "HttpError"; - this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); } - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options + } else { + break; + } + } - const requestCopy = Object.assign({}, options.request); + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; } -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + ch = state.input.charCodeAt(state.position); -/***/ }), -/* 464 */, -/* 465 */, -/* 466 */, -/* 467 */, -/* 468 */, -/* 469 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } -"use strict"; + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + if (is_EOL(ch)) { + emptyLines++; + continue; + } -const jsonFile = __webpack_require__(666) + // End of the scalar. + if (state.lineIndent < textIndent) { -module.exports = { - // jsonfile exports - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync -} + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + // Break this `while` cycle and go to the funciton's epilogue. + break; + } -/***/ }), -/* 470 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Folded style: use fancy rules to handle line breaks. + if (folding) { -"use strict"; + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); -module.exports = __webpack_require__(600); + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } -/***/ }), -/* 471 */, -/* 472 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } -"use strict"; + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } -const file = __webpack_require__(149) -const link = __webpack_require__(900) -const symlink = __webpack_require__(849) + captureSegment(state, captureStart, state.position, false); + } -module.exports = { - // file - createFile: file.createFile, - createFileSync: file.createFileSync, - ensureFile: file.createFile, - ensureFileSync: file.createFileSync, - // link - createLink: link.createLink, - createLinkSync: link.createLinkSync, - ensureLink: link.createLink, - ensureLinkSync: link.createLinkSync, - // symlink - createSymlink: symlink.createSymlink, - createSymlinkSync: symlink.createSymlinkSync, - ensureSymlink: symlink.createSymlink, - ensureSymlinkSync: symlink.createSymlinkSync + return true; } +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; -/***/ }), -/* 473 */, -/* 474 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -"use strict"; + ch = state.input.charCodeAt(state.position); + while (ch !== 0) { -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const assert = __webpack_require__(357) + if (ch !== 0x2D/* - */) { + break; + } -const isWindows = (process.platform === 'win32') + following = state.input.charCodeAt(state.position + 1); -function defaults (options) { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) + if (!is_WS_OR_EOL(following)) { + break; + } - options.maxBusyTries = options.maxBusyTries || 3 -} + detected = true; + state.position++; -function rimraf (p, options, cb) { - let busyTries = 0 + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } - if (typeof options === 'function') { - cb = options - options = {} - } + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') + ch = state.input.charCodeAt(state.position); - defaults(options) + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && - busyTries < options.maxBusyTries) { - busyTries++ - const time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), time) - } - - // already gone - if (er.code === 'ENOENT') er = null - } - - cb(er) - }) + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === 'ENOENT') { - return cb(null) - } +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === 'EPERM' && isWindows) { - return fixWinEPERM(p, options, er, cb) - } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb) - } + ch = state.input.charCodeAt(state.position); - options.unlink(p, er => { - if (er) { - if (er.code === 'ENOENT') { - return cb(null) - } - if (er.code === 'EPERM') { - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - } - if (er.code === 'EISDIR') { - return rmdir(p, options, er, cb) - } - } - return cb(er) - }) - }) -} + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - options.chmod(p, 0o666, er2 => { - if (er2) { - cb(er2.code === 'ENOENT' ? null : er) - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === 'ENOENT' ? null : er) - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb) - } else { - options.unlink(p, cb) + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; } - }) - } - }) -} -function fixWinEPERMSync (p, options, er) { - let stats - - assert(p) - assert(options) + detected = true; + atExplicitKey = true; + allowCompact = true; - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === 'ENOENT') { - return - } else { - throw er - } - } + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === 'ENOENT') { - return - } else { - throw er - } - } + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } - if (stats.isDirectory()) { - rmdirSync(p, options, er) - } else { - options.unlinkSync(p) - } -} + state.position += 1; + ch = following; -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { - rmkids(p, options, cb) - } else if (er && er.code === 'ENOTDIR') { - cb(originalEr) - } else { - cb(er) - } - }) -} + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -function rmkids (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - options.readdir(p, (er, files) => { - if (er) return cb(er) + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); - let n = files.length - let errState + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } - if (n === 0) return options.rmdir(p, cb) + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) { - return - } - if (er) return cb(errState = er) - if (--n === 0) { - options.rmdir(p, cb) - } - }) - }) - }) -} + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - let st + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - options = options || {} - defaults(options) + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === 'ENOENT') { - return - } + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } - // Windows can EPERM on stat. Life is suffering. - if (er.code === 'EPERM' && isWindows) { - fixWinEPERMSync(p, options, er) + } else { + break; // Reading is done. Go to the epilogue. } - } - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) { - rmdirSync(p, options, null) - } else { - options.unlinkSync(p) + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); } - } catch (er) { - if (er.code === 'ENOENT') { - return - } else if (er.code === 'EPERM') { - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - } else if (er.code !== 'EISDIR') { - throw er + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; } - rmdirSync(p, options, er) } -} -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) + // + // Epilogue. + // - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === 'ENOTDIR') { - throw originalEr - } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { - rmkidsSync(p, options) - } else if (er.code !== 'ENOENT') { - throw er - } + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - if (isWindows) { - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const startTime = Date.now() - do { - try { - const ret = options.rmdirSync(p, options) - return ret - } catch {} - } while (Date.now() - startTime < 500) // give up after 500ms - } else { - const ret = options.rmdirSync(p, options) - return ret + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; } + + return detected; } -module.exports = rimraf -rimraf.sync = rimrafSync +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + ch = state.input.charCodeAt(state.position); -/***/ }), -/* 475 */, -/* 476 */, -/* 477 */, -/* 478 */, -/* 479 */, -/* 480 */, -/* 481 */, -/* 482 */, -/* 483 */, -/* 484 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (ch !== 0x21/* ! */) return false; -const { spawn } = __webpack_require__(129); -var assert = __webpack_require__(357); + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } -const { TimeoutError, logger } = __webpack_require__(79); -const fs = __webpack_require__(747); + ch = state.input.charCodeAt(++state.position); -class ExitError extends Error { - constructor(message, code) { - super(message); - this.code = code; - } -} + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); -const FETCH_DEPTH = 10; + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); -const COMMON_ARGS = [ - "-c", - "user.name=GitHub", - "-c", - "user.email=noreply@github.com" -]; + } else { + tagHandle = '!'; + } -function git(cwd, ...args) { - const stdio = [ - "ignore", - "pipe", - logger.level === "trace" || logger.level === "debug" ? "inherit" : "pipe" - ]; - // the URL passed to the clone command could contain a password! - const command = `git ${args.join(" ")}`; - logger.debug("Executing", command); - return new Promise((resolve, reject) => { - const proc = spawn( - "git", - COMMON_ARGS.concat(args.filter(a => a !== null)), - { cwd, stdio } - ); - const buffers = []; - proc.stdout.on("data", data => buffers.push(data)); - proc.stderr.on("data", data => buffers.push(data)); + _position = state.position; - proc.on("error", () => { - reject(new Error(`command failed: ${command}`)); - }); - proc.on("exit", code => { - const stdoutData = Buffer.concat(buffers); - if (code === 0) { - resolve(stdoutData.toString("utf8").trim()); - } else { - reject( - new ExitError( - `command ${command} failed with code ${code}. Error Message: ${stdoutData}`, - code - ) - ); - } - }); - }); -} + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); -async function clone(from, to, branch) { - if (!fs.existsSync(to)) { - await git( - ".", - "clone", - "--quiet", - "--shallow-submodules", - "--no-tags", - "--branch", - branch, - from, - to - ); + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } } else { - logger.warn(`Folder ${to} already exist. Won't clone`); - } -} + while (ch !== 0 && !is_WS_OR_EOL(ch)) { -async function fetch(dir, branch) { - await git( - dir, - "fetch", - "--quiet", - "origin", - `${branch}:refs/remotes/origin/${branch}` - ); -} + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); -async function fetchUntilMergeBase(dir, branch, timeout) { - const maxTime = new Date().getTime() + timeout; - const ref = `refs/remotes/origin/${branch}`; - while (new Date().getTime() < maxTime) { - const base = await mergeBase(dir, "HEAD", ref); - if (base) { - const bases = [base]; - const parents = await mergeCommits(dir, ref); - let fetchMore = false; - for (const parent of parents.flat()) { - const b = await mergeBase(dir, parent, ref); - if (b) { - if (!bases.includes(b)) { - bases.push(b); + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); } + + isNamed = true; + _position = state.position + 1; } else { - // we found a commit which does not have a common ancestor with - // the branch we want to merge, so we need to fetch more - fetchMore = true; - break; - } - } - if (!fetchMore) { - const commonBase = await mergeBase(dir, ...bases); - if (!commonBase) { - throw new Error(`failed to find common base for ${bases}`); + throwError(state, 'tag suffix cannot contain exclamation marks'); } - return commonBase; } + + ch = state.input.charCodeAt(++state.position); } - await fetchDeepen(dir); - } - throw new TimeoutError(); -} -async function fetchDeepen(dir) { - await git(dir, "fetch", "--quiet", "--deepen", FETCH_DEPTH); -} + tagName = state.input.slice(_position, state.position); -async function mergeBase(dir, ...refs) { - if (refs.length === 1) { - return refs[0]; - } else if (refs.length < 1) { - throw new Error("empty refs!"); - } - let todo = refs; - try { - while (todo.length > 1) { - const base = await git(dir, "merge-base", todo[0], todo[1]); - todo = [base].concat(todo.slice(2)); - } - return todo[0]; - } catch (e) { - if (e instanceof ExitError && e.code === 1) { - return null; - } else { - throw e; + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); } } -} -async function mergeCommits(dir, ref) { - return (await git(dir, "rev-list", "--parents", `${ref}..HEAD`)) - .split(/\n/g) - .map(line => line.split(/ /g).slice(1)) - .filter(commit => commit.length > 1); -} - -async function merge(dir, group, repositoryName, branch) { - return await git( - dir, - "pull", - `https://github.com/${group}/${repositoryName}`, - branch - ); -} + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } -async function head(dir) { - return await git(dir, "show-ref", "--head", "-s", "/HEAD"); -} + if (isVerbatim) { + state.tag = tagName; -async function sha(dir, branch) { - return await git(dir, "show-ref", "-s", `refs/remotes/origin/${branch}`); -} + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; -async function rebase(dir, branch) { - return await git(dir, "rebase", "--quiet", "--autosquash", branch); -} + } else if (tagHandle === '!') { + state.tag = '!' + tagName; -async function push(dir, force, branch) { - return await git( - dir, - "push", - "--quiet", - force ? "--force-with-lease" : null, - "origin", - branch - ); -} + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; -async function doesBranchExist(octokit, owner, repo, branch) { - assert(owner, "owner is not defined"); - assert(repo, "repo is not defined"); - assert(branch, "branch is not defined"); - try { - const { status } = await octokit.repos.getBranch({ - owner, - repo, - branch - }); - return status == 200; - } catch (e) { - logger.warn( - `project github.com/${owner}/${repo}:${branch} does not exist. It's not necessarily an error.` - ); - return false; + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } -} -/** - * Checks if there is a pull request either from a forked project or the same project - * @param {Object} octokit instance - * @param {String} owner the repo owner or group - * @param {String} repo the repository name - * @param {String} branch the branch of the pull request to look for - * @param {String} fromAuthor the pull request author - */ -async function hasPullRequest(octokit, owner, repo, branch, fromAuthor) { - return ( - (await hasForkPullRequest(octokit, owner, repo, branch, fromAuthor)) || - (await hasOriginPullRequest(octokit, owner, repo, branch)) - ); + return true; } -/** - * Checks if there is a pull request from a forked project - * @param {Object} octokit instance - * @param {String} owner the repo owner or group - * @param {String} repo the repository name - * @param {String} branch the branch of the pull request to look for - * @param {String} fromAuthor the pull request author - */ -async function hasForkPullRequest(octokit, owner, repo, branch, fromAuthor) { - assert(owner, "owner is not defined"); - assert(repo, "repo is not defined"); - assert(branch, "branch is not defined"); - assert(fromAuthor, "fromAuthor is not defined"); - try { - const { status, data } = await octokit.pulls.list({ - owner, - repo, - state: "open", - head: `${fromAuthor}:${branch}` - }); - return status == 200 && data.length > 0; - } catch (e) { - logger.error( - `Error getting pull request list from https://api.github.com/repos/${owner}/${repo}/pulls?head=${fromAuthor}:${branch}&state=open'".` - ); - throw e; +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); } -} -/** - * Checks if there is a pull request from the same project - * @param {Object} octokit instance - * @param {String} owner the repo owner or group - * @param {String} repo the repository name - * @param {String} branch the branch of the pull request to look for - */ -async function hasOriginPullRequest(octokit, owner, repo, branch) { - assert(owner, "owner is not defined"); - assert(repo, "repo is not defined"); - assert(branch, "branch is not defined"); - try { - const { status, data } = await octokit.pulls.list({ - owner, - repo, - state: "open", - head: `${owner}:${branch}` - }); - return status == 200 && data.length > 0; - } catch (e) { - logger.error( - `Error getting pull request list from https://api.github.com/repos/${owner}/${repo}/pulls?head=${owner}:${branch}&state=open'".` - ); - throw e; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } -} -async function getForkedProject( - octokit, - owner, - repo, - wantedOwner, - page = 1, - per_page = 100 -) { - assert(owner, "owner is not defined"); - assert(repo, "repo is not defined"); - assert(wantedOwner, "wantedOwner is not defined"); - assert(page, "page is not defined"); - try { - const { status, data } = await octokit.repos.listForks({ - owner, - repo, - page - }); - if (status == 200) { - if (data && data.length > 0) { - const forkedProject = data.find( - forkedProject => forkedProject.owner.login === wantedOwner - ); - return forkedProject - ? forkedProject - : await getForkedProject( - octokit, - owner, - repo, - wantedOwner, - ++page, - per_page - ); - } else { - return undefined; - } - } - } catch (e) { - logger.error( - `Error getting forked project list from https://api.github.com/repos/${owner}/${repo}/forks?per_page=${per_page}&page=${page}'".` - ); - throw e; + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); } -} -module.exports = { - ExitError, - git, - clone, - fetch, - fetchUntilMergeBase, - fetchDeepen, - mergeBase, - mergeCommits, - merge, - head, - sha, - rebase, - push, - doesBranchExist, - hasPullRequest, - getForkedProject -}; + state.anchor = state.input.slice(_position, state.position); + return true; +} +function readAlias(state) { + var _position, alias, + ch; -/***/ }), -/* 485 */, -/* 486 */, -/* 487 */, -/* 488 */, -/* 489 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + ch = state.input.charCodeAt(state.position); -"use strict"; + if (ch !== 0x2A/* * */) return false; + ch = state.input.charCodeAt(++state.position); + _position = state.position; -const path = __webpack_require__(622); -const which = __webpack_require__(814); -const pathKey = __webpack_require__(39)(); + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } -function resolveCommandAttempt(parsed, withoutPathExt) { - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (hasCustomCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } - - let resolved; - - try { - resolved = which.sync(parsed.command, { - path: (parsed.options.env || process.env)[pathKey], - pathExt: withoutPathExt ? path.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - process.chdir(cwd); - } + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } + alias = state.input.slice(_position, state.position); - return resolved; -} + if (!state.anchorMap.hasOwnProperty(alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; } -module.exports = resolveCommand; - +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } } - const overwrite = opts.overwrite || opts.clobber || false - - stat.checkPaths(src, dest, 'move', (err, stats) => { - if (err) return cb(err) - const { srcStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'move', err => { - if (err) return cb(err) - mkdirp(path.dirname(dest), err => { - if (err) return cb(err) - return doRename(src, dest, overwrite, cb) - }) - }) - }) -} + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; -function doRename (src, dest, overwrite, cb) { - if (overwrite) { - return remove(dest, err => { - if (err) return cb(err) - return rename(src, dest, overwrite, cb) - }) + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } } - pathExists(dest, (err, destExists) => { - if (err) return cb(err) - if (destExists) return cb(new Error('dest already exists.')) - return rename(src, dest, overwrite, cb) - }) -} - -function rename (src, dest, overwrite, cb) { - fs.rename(src, dest, err => { - if (!err) return cb() - if (err.code !== 'EXDEV') return cb(err) - return moveAcrossDevice(src, dest, overwrite, cb) - }) -} -function moveAcrossDevice (src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } - copy(src, dest, opts, err => { - if (err) return cb(err) - return remove(src, cb) - }) -} -module.exports = move + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + blockIndent = state.position - state.lineStart; -/***/ }), -/* 501 */, -/* 502 */, -/* 503 */, -/* 504 */, -/* 505 */, -/* 506 */, -/* 507 */, -/* 508 */, -/* 509 */, -/* 510 */ -/***/ (function(module) { + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; -module.exports = addHook + } else if (readAlias(state)) { + hasContent = true; -function addHook (state, kind, name, hook) { - var orig = hook - if (!state.registry[name]) { - state.registry[name] = [] - } + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - if (kind === 'before') { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)) - } - } + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; - 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 (state.tag === null) { + state.tag = '?'; + } + } - if (kind === 'error') { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options) - }) + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } - state.registry[name].push({ - hook: hook, - orig: orig - }) -} - - -/***/ }), -/* 511 */, -/* 512 */, -/* 513 */, -/* 514 */, -/* 515 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/** - * class Namespace - * - * Simple object for storing attributes. Implements equality by attribute names - * and values, and provides a simple string representation. - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object - **/ + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; -var $$ = __webpack_require__(255); + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; -/** - * new Namespace(options) - * - options(object): predefined propertis for result object - * - **/ -var Namespace = module.exports = function Namespace(options) { - $$.extend(this, options); -}; + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } -/** - * Namespace#isset(key) -> Boolean - * - key (string|number): property name - * - * Tells whenever `namespace` contains given `key` or not. - **/ -Namespace.prototype.isset = function (key) { - return $$.has(this, key); -}; + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } -/** - * Namespace#set(key, value) -> self - * -key (string|number|object): propery name - * -value (mixed): new property value - * - * Set the property named key with value. - * If key object then set all key properties to namespace object - **/ -Namespace.prototype.set = function (key, value) { - if (typeof (key) === 'object') { - $$.extend(this, key); - } else { - this[key] = value; + if (state.listener !== null) { + state.listener('close', state); } - return this; -}; + return state.tag !== null || state.anchor !== null || hasContent; +} -/** - * Namespace#get(key, defaultValue) -> mixed - * - key (string|number): property name - * - defaultValue (mixed): default value - * - * Return the property key or defaulValue if not set - **/ -Namespace.prototype.get = function (key, defaultValue) { - return !this[key] ? defaultValue : this[key]; -}; +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; -/** - * Namespace#unset(key, defaultValue) -> mixed - * - key (string|number): property name - * - defaultValue (mixed): default value - * - * Return data[key](and delete it) or defaultValue - **/ -Namespace.prototype.unset = function (key, defaultValue) { - var value = this[key]; - if (value !== null) { - delete this[key]; - return value; - } - return defaultValue; -}; + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); -/***/ }), -/* 516 */, -/* 517 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + ch = state.input.charCodeAt(state.position); -"use strict"; + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; -const u = __webpack_require__(676).fromCallback -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const mkdir = __webpack_require__(727) -const pathExists = __webpack_require__(322).pathExists + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } -function outputFile (file, data, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding - encoding = 'utf8' - } + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - const dir = path.dirname(file) - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return fs.writeFile(file, data, encoding, callback) + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } - mkdir.mkdirs(dir, err => { - if (err) return callback(err) + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - fs.writeFile(file, data, encoding, callback) - }) - }) -} + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } -function outputFileSync (file, ...args) { - const dir = path.dirname(file) - if (fs.existsSync(dir)) { - return fs.writeFileSync(file, ...args) - } - mkdir.mkdirsSync(dir) - fs.writeFileSync(file, ...args) -} + if (is_EOL(ch)) break; -module.exports = { - outputFile: u(outputFile), - outputFileSync -} + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } -/***/ }), -/* 518 */, -/* 519 */, -/* 520 */, -/* 521 */, -/* 522 */, -/* 523 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + directiveArgs.push(state.input.slice(_position, state.position)); + } -var register = __webpack_require__(280) -var addHook = __webpack_require__(510) -var removeHook = __webpack_require__(763) + if (ch !== 0) readLineBreak(state); -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef + skipSeparationSpace(state, true, -1); - ;['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) - }) -} + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} -function HookCollection () { - var state = { - registry: {} + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } - var hook = register.bind(null, state) - bindApi(hook, state) + state.documents.push(state.result); - return hook -} + if (state.position === state.lineStart && testDocumentSeparator(state)) { -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 + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; } - 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 +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + if (input.length !== 0) { -/***/ }), -/* 524 */, -/* 525 */, -/* 526 */, -/* 527 */, -/* 528 */, -/* 529 */, -/* 530 */, -/* 531 */, -/* 532 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } -"use strict"; -/** - * class HelpFormatter - * - * Formatter for generating usage messages and argument help strings. Only the - * name of this class is considered a public API. All the methods provided by - * the class are considered an implementation detail. - * - * Do not call in your code, use this class only for inherits your own forvatter - * - * ToDo add [additonal formatters][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#formatter-class - **/ + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + var state = new State(input, options); -var sprintf = __webpack_require__(552).sprintf; + var nullpos = input.indexOf('\0'); -// Constants -var c = __webpack_require__(45); + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } -var $$ = __webpack_require__(255); + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } -/*:nodoc:* internal - * new Support(parent, heding) - * - parent (object): parent section - * - heading (string): header string - * - **/ -function Section(parent, heading) { - this._parent = parent; - this._heading = heading; - this._items = []; -} + while (state.position < (state.length - 1)) { + readDocument(state); + } -/*:nodoc:* internal - * Section#addItem(callback) -> Void - * - callback (array): tuple with function and args - * - * Add function for single element - **/ -Section.prototype.addItem = function (callback) { - this._items.push(callback); -}; + return state.documents; +} -/*:nodoc:* internal - * Section#formatHelp(formatter) -> string - * - formatter (HelpFormatter): current formatter - * - * Form help section string - * - **/ -Section.prototype.formatHelp = function (formatter) { - var itemHelp, heading; - // format the indented section - if (this._parent) { - formatter._indent(); +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; } - itemHelp = this._items.map(function (item) { - var obj, func, args; - - obj = formatter; - func = item[0]; - args = item[1]; - return func.apply(obj, args); - }); - itemHelp = formatter._joinParts(itemHelp); + var documents = loadDocuments(input, options); - if (this._parent) { - formatter._dedent(); + if (typeof iterator !== 'function') { + return documents; } - // return nothing if the section was empty - if (!itemHelp) { - return ''; + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); } +} - // add the heading if the section was non-empty - heading = ''; - if (this._heading && this._heading !== c.SUPPRESS) { - var currentIndent = formatter.currentIndent; - heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL; + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; } + throw new YAMLException('expected a single document in the stream, but found more'); +} - // join the section-initialize newline, the heading and the help - return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]); -}; -/** - * new HelpFormatter(options) - * - * #### Options: - * - `prog`: program name - * - `indentIncriment`: indent step, default value 2 - * - `maxHelpPosition`: max help position, default value = 24 - * - `width`: line width - * - **/ -var HelpFormatter = module.exports = function HelpFormatter(options) { - options = options || {}; +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - this._prog = options.prog; + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - this._maxHelpPosition = options.maxHelpPosition || 24; - this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); - this._currentIndent = 0; - this._indentIncriment = options.indentIncriment || 2; - this._level = 0; - this._actionMaxLength = 0; +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - this._rootSection = new Section(null); - this._currentSection = this._rootSection; - this._whitespaceMatcher = new RegExp('\\s+', 'g'); - this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g'); -}; +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; -HelpFormatter.prototype._indent = function () { - this._currentIndent += this._indentIncriment; - this._level += 1; -}; -HelpFormatter.prototype._dedent = function () { - this._currentIndent -= this._indentIncriment; - this._level -= 1; - if (this._currentIndent < 0) { - throw new Error('Indent decreased below 0.'); - } -}; +/***/ }), +/* 458 */, +/* 459 */, +/* 460 */, +/* 461 */, +/* 462 */ +/***/ (function(module) { -HelpFormatter.prototype._addItem = function (func, args) { - this._currentSection.addItem([ func, args ]); -}; +"use strict"; -// -// Message building methods -// -/** - * HelpFormatter#startSection(heading) -> Void - * - heading (string): header string - * - * Start new help section - * - * See alse [code example][1] - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.startSection = function (heading) { - this._indent(); - var section = new Section(this._currentSection, heading); - var func = section.formatHelp.bind(section); - this._addItem(func, [ this ]); - this._currentSection = section; -}; +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; -/** - * HelpFormatter#endSection -> Void - * - * End help section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - **/ -HelpFormatter.prototype.endSection = function () { - this._currentSection = this._currentSection._parent; - this._dedent(); -}; +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); -/** - * HelpFormatter#addText(text) -> Void - * - text (string): plain text - * - * Add plain text into current section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.addText = function (text) { - if (text && text !== c.SUPPRESS) { - this._addItem(this._formatText, [ text ]); - } -}; + return arg; +} -/** - * HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void - * - usage (string): usage text - * - actions (array): actions list - * - groups (array): groups list - * - prefix (string): usage prefix - * - * Add usage data into current section - * - * ##### Example - * - * formatter.addUsage(this.usage, this._actions, []); - * return formatter.formatHelp(); - * - **/ -HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { - if (usage !== c.SUPPRESS) { - this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]); - } -}; +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; -/** - * HelpFormatter#addArgument(action) -> Void - * - action (object): action - * - * Add argument into current section - * - * Single variant of [[HelpFormatter#addArguments]] - **/ -HelpFormatter.prototype.addArgument = function (action) { - if (action.help !== c.SUPPRESS) { - var self = this; + // Algorithm below is based on https://qntm.org/cmd - // find all invocations - var invocations = [ this._formatActionInvocation(action) ]; - var invocationLength = invocations[0].length; + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - var actionLength; + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); - if (action._getSubactions) { - this._indent(); - action._getSubactions().forEach(function (subaction) { + // All other backslashes occur literally - var invocationNew = self._formatActionInvocation(subaction); - invocations.push(invocationNew); - invocationLength = Math.max(invocationLength, invocationNew.length); + // Quote the whole thing: + arg = `"${arg}"`; - }); - this._dedent(); + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); } - // update the maximum item length - actionLength = invocationLength + this._currentIndent; - this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); + return arg; +} - // add the item to the list - this._addItem(this._formatAction, [ action ]); - } -}; +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; -/** - * HelpFormatter#addArguments(actions) -> Void - * - actions (array): actions list - * - * Mass add arguments into current section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.addArguments = function (actions) { - var self = this; - actions.forEach(function (action) { - self.addArgument(action); - }); -}; -// -// Help-formatting methods -// +/***/ }), +/* 463 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/** - * HelpFormatter#formatHelp -> string - * - * Format help - * - * ##### Example - * - * formatter.addText(this.epilog); - * return formatter.formatHelp(); - * - **/ -HelpFormatter.prototype.formatHelp = function () { - var help = this._rootSection.formatHelp(this); - if (help) { - help = help.replace(this._longBreakMatcher, c.EOL + c.EOL); - help = $$.trimChars(help, c.EOL) + c.EOL; - } - return help; -}; +"use strict"; -HelpFormatter.prototype._joinParts = function (partStrings) { - return partStrings.filter(function (part) { - return (part && part !== c.SUPPRESS); - }).join(''); -}; -HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { - if (!prefix && typeof prefix !== 'string') { - prefix = 'usage: '; - } +Object.defineProperty(exports, '__esModule', { value: true }); - actions = actions || []; - groups = groups || []; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +var deprecation = __webpack_require__(692); +var once = _interopDefault(__webpack_require__(969)); - // if usage is specified, use that - if (usage) { - usage = sprintf(usage, { prog: this._prog }); +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ - // if no optionals or positionals are available, usage is just prog - } else if (!usage && actions.length === 0) { - usage = this._prog; +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) - // if optionals and positionals are available, calculate usage - } else if (!usage) { - var prog = this._prog; - var optionals = []; - var positionals = []; - var actionUsage; - var textWidth; + /* istanbul ignore next */ - // split optionals from positionals - actions.forEach(function (action) { - if (action.isOptional()) { - optionals.push(action); - } else { - positionals.push(action); - } - }); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - // build full usage string - actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); - usage = [ prog, actionUsage ].join(' '); + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } - // wrap the usage parts if it's too long - textWidth = this._width - this._currentIndent; - if ((prefix.length + usage.length) > textWidth) { + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options - // break usage into wrappable parts - var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); - var optionalUsage = this._formatActionsUsage(optionals, groups); - var positionalUsage = this._formatActionsUsage(positionals, groups); + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } - var optionalParts = optionalUsage.match(regexpPart); - var positionalParts = positionalUsage.match(regexpPart) || []; + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } - if (optionalParts.join(' ') !== optionalUsage) { - throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); - } - if (positionalParts.join(' ') !== positionalUsage) { - throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); - } +} - // helper for wrapping lines - /*eslint-disable func-style*/ // node 0.10 compat - var _getLines = function (parts, indent, prefix) { - var lines = []; - var line = []; +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map - var lineLength = prefix ? prefix.length - 1 : indent.length - 1; - parts.forEach(function (part) { - if (lineLength + 1 + part.length > textWidth) { - lines.push(indent + line.join(' ')); - line = []; - lineLength = indent.length - 1; - } - line.push(part); - lineLength += part.length + 1; - }); +/***/ }), +/* 464 */, +/* 465 */, +/* 466 */, +/* 467 */, +/* 468 */, +/* 469 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (line) { - lines.push(indent + line.join(' ')); - } - if (prefix) { - lines[0] = lines[0].substr(indent.length); - } - return lines; - }; +"use strict"; - var lines, indent, parts; - // if prog is short, follow it with optionals or positionals - if (prefix.length + prog.length <= 0.75 * textWidth) { - indent = $$.repeat(' ', (prefix.length + prog.length + 1)); - if (optionalParts) { - lines = [].concat( - _getLines([ prog ].concat(optionalParts), indent, prefix), - _getLines(positionalParts, indent) - ); - } else if (positionalParts) { - lines = _getLines([ prog ].concat(positionalParts), indent, prefix); - } else { - lines = [ prog ]; - } - // if prog is long, put it on its own line - } else { - indent = $$.repeat(' ', prefix.length); - parts = optionalParts.concat(positionalParts); - lines = _getLines(parts, indent); - if (lines.length > 1) { - lines = [].concat( - _getLines(optionalParts, indent), - _getLines(positionalParts, indent) - ); - } - lines = [ prog ].concat(lines); - } - // join lines into usage - usage = lines.join(c.EOL); - } - } +const jsonFile = __webpack_require__(666) - // prefix with 'usage:' - return prefix + usage + c.EOL + c.EOL; -}; +module.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync +} -HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { - // find group indices and identify actions in groups - var groupActions = []; - var inserts = []; - var self = this; - groups.forEach(function (group) { - var end; - var i; +/***/ }), +/* 470 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var start = actions.indexOf(group._groupActions[0]); - if (start >= 0) { - end = start + group._groupActions.length; +"use strict"; - //if (actions.slice(start, end) === group._groupActions) { - if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) { - group._groupActions.forEach(function (action) { - groupActions.push(action); - }); - if (!group.required) { - if (inserts[start]) { - inserts[start] += ' ['; - } else { - inserts[start] = '['; - } - inserts[end] = ']'; - } else { - if (inserts[start]) { - inserts[start] += ' ('; - } else { - inserts[start] = '('; - } - inserts[end] = ')'; - } - for (i = start + 1; i < end; i += 1) { - inserts[i] = '|'; - } - } - } - }); +module.exports = __webpack_require__(600); - // collect all actions format strings - var parts = []; - actions.forEach(function (action, actionIndex) { - var part; - var optionString; - var argsDefault; - var argsString; +/***/ }), +/* 471 */, +/* 472 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // suppressed arguments are marked with None - // remove | separators for suppressed arguments - if (action.help === c.SUPPRESS) { - parts.push(null); - if (inserts[actionIndex] === '|') { - inserts.splice(actionIndex, actionIndex); - } else if (inserts[actionIndex + 1] === '|') { - inserts.splice(actionIndex + 1, actionIndex + 1); - } +"use strict"; - // produce all arg strings - } else if (!action.isOptional()) { - part = self._formatArgs(action, action.dest); - // if it's in a group, strip the outer [] - if (groupActions.indexOf(action) >= 0) { - if (part[0] === '[' && part[part.length - 1] === ']') { - part = part.slice(1, -1); - } - } - // add the action string to the list - parts.push(part); +const file = __webpack_require__(149) +const link = __webpack_require__(900) +const symlink = __webpack_require__(849) - // produce the first way to invoke the option in brackets - } else { - optionString = action.optionStrings[0]; +module.exports = { + // file + createFile: file.createFile, + createFileSync: file.createFileSync, + ensureFile: file.createFile, + ensureFileSync: file.createFileSync, + // link + createLink: link.createLink, + createLinkSync: link.createLinkSync, + ensureLink: link.createLink, + ensureLinkSync: link.createLinkSync, + // symlink + createSymlink: symlink.createSymlink, + createSymlinkSync: symlink.createSymlinkSync, + ensureSymlink: symlink.createSymlink, + ensureSymlinkSync: symlink.createSymlinkSync +} - // if the Optional doesn't take a value, format is: -s or --long - if (action.nargs === 0) { - part = '' + optionString; - // if the Optional takes a value, format is: -s ARGS or --long ARGS - } else { - argsDefault = action.dest.toUpperCase(); - argsString = self._formatArgs(action, argsDefault); - part = optionString + ' ' + argsString; - } - // make it look optional if it's not required or in a group - if (!action.required && groupActions.indexOf(action) < 0) { - part = '[' + part + ']'; - } - // add the action string to the list - parts.push(part); - } - }); +/***/ }), +/* 473 */, +/* 474 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // insert things at the necessary indices - for (var i = inserts.length - 1; i >= 0; --i) { - if (inserts[i] !== null) { - parts.splice(i, 0, inserts[i]); - } - } +"use strict"; - // join all the action items with spaces - var text = parts.filter(function (part) { - return !!part; - }).join(' '); - // clean up separators for mutually exclusive groups - text = text.replace(/([\[(]) /g, '$1'); // remove spaces - text = text.replace(/ ([\])])/g, '$1'); - text = text.replace(/\[ *\]/g, ''); // remove empty groups - text = text.replace(/\( *\)/g, ''); - text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const assert = __webpack_require__(357) - text = text.trim(); +const isWindows = (process.platform === 'win32') - // return the text - return text; -}; +function defaults (options) { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) -HelpFormatter.prototype._formatText = function (text) { - text = sprintf(text, { prog: this._prog }); - var textWidth = this._width - this._currentIndent; - var indentIncriment = $$.repeat(' ', this._currentIndent); - return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL; -}; + options.maxBusyTries = options.maxBusyTries || 3 +} -HelpFormatter.prototype._formatAction = function (action) { - var self = this; +function rimraf (p, options, cb) { + let busyTries = 0 - var helpText; - var helpLines; - var parts; - var indentFirst; + if (typeof options === 'function') { + cb = options + options = {} + } - // determine the required width and the entry label - var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); - var helpWidth = this._width - helpPosition; - var actionWidth = helpPosition - this._currentIndent - 2; - var actionHeader = this._formatActionInvocation(action); + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - // no help; start on same line and add a final newline - if (!action.help) { - actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; + defaults(options) - // short action name; start on the same line and pad two spaces - } else if (actionHeader.length <= actionWidth) { - actionHeader = $$.repeat(' ', this._currentIndent) + - actionHeader + - ' ' + - $$.repeat(' ', actionWidth - actionHeader.length); - indentFirst = 0; - - // long action name; start on the next line - } else { - actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; - indentFirst = helpPosition; - } - - // collect the pieces of the action help - parts = [ actionHeader ]; - - // if there was help for the action, add lines of help text - if (action.help) { - helpText = this._expandHelp(action); - helpLines = this._splitLines(helpText, helpWidth); - parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL); - helpLines.slice(1).forEach(function (line) { - parts.push($$.repeat(' ', helpPosition) + line + c.EOL); - }); - - // or add a newline if the description doesn't end with one - } else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) { - parts.push(c.EOL); - } - // if there are any sub-actions, add their help as well - if (action._getSubactions) { - this._indent(); - action._getSubactions().forEach(function (subaction) { - parts.push(self._formatAction(subaction)); - }); - this._dedent(); - } - // return a single string - return this._joinParts(parts); -}; - -HelpFormatter.prototype._formatActionInvocation = function (action) { - if (!action.isOptional()) { - var format_func = this._metavarFormatter(action, action.dest); - var metavars = format_func(1); - return metavars[0]; - } - - var parts = []; - var argsDefault; - var argsString; - - // if the Optional doesn't take a value, format is: -s, --long - if (action.nargs === 0) { - parts = parts.concat(action.optionStrings); + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && + busyTries < options.maxBusyTries) { + busyTries++ + const time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), time) + } - // if the Optional takes a value, format is: -s ARGS, --long ARGS - } else { - argsDefault = action.dest.toUpperCase(); - argsString = this._formatArgs(action, argsDefault); - action.optionStrings.forEach(function (optionString) { - parts.push(optionString + ' ' + argsString); - }); - } - return parts.join(', '); -}; + // already gone + if (er.code === 'ENOENT') er = null + } -HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { - var result; + cb(er) + }) +} - if (action.metavar || action.metavar === '') { - result = action.metavar; - } else if (action.choices) { - var choices = action.choices; +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') - if (typeof choices === 'string') { - choices = choices.split('').join(', '); - } else if (Array.isArray(choices)) { - choices = choices.join(','); - } else { - choices = Object.keys(choices).join(','); + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === 'ENOENT') { + return cb(null) } - result = '{' + choices + '}'; - } else { - result = metavarDefault; - } - return function (size) { - if (Array.isArray(result)) { - return result; + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === 'EPERM' && isWindows) { + return fixWinEPERM(p, options, er, cb) } - var metavars = []; - for (var i = 0; i < size; i += 1) { - metavars.push(result); + if (st && st.isDirectory()) { + return rmdir(p, options, er, cb) } - return metavars; - }; -}; -HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { - var result; - var metavars; + options.unlink(p, er => { + if (er) { + if (er.code === 'ENOENT') { + return cb(null) + } + if (er.code === 'EPERM') { + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + } + if (er.code === 'EISDIR') { + return rmdir(p, options, er, cb) + } + } + return cb(er) + }) + }) +} - var buildMetavar = this._metavarFormatter(action, metavarDefault); +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') - switch (action.nargs) { - /*eslint-disable no-undefined*/ - case undefined: - case null: - metavars = buildMetavar(1); - result = '' + metavars[0]; - break; - case c.OPTIONAL: - metavars = buildMetavar(1); - result = '[' + metavars[0] + ']'; - break; - case c.ZERO_OR_MORE: - metavars = buildMetavar(2); - result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; - break; - case c.ONE_OR_MORE: - metavars = buildMetavar(2); - result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; - break; - case c.REMAINDER: - result = '...'; - break; - case c.PARSER: - metavars = buildMetavar(1); - result = metavars[0] + ' ...'; - break; - default: - metavars = buildMetavar(action.nargs); - result = metavars.join(' '); - } - return result; -}; + options.chmod(p, 0o666, er2 => { + if (er2) { + cb(er2.code === 'ENOENT' ? null : er) + } else { + options.stat(p, (er3, stats) => { + if (er3) { + cb(er3.code === 'ENOENT' ? null : er) + } else if (stats.isDirectory()) { + rmdir(p, options, er, cb) + } else { + options.unlink(p, cb) + } + }) + } + }) +} -HelpFormatter.prototype._expandHelp = function (action) { - var params = { prog: this._prog }; +function fixWinEPERMSync (p, options, er) { + let stats - Object.keys(action).forEach(function (actionProperty) { - var actionValue = action[actionProperty]; + assert(p) + assert(options) - if (actionValue !== c.SUPPRESS) { - params[actionProperty] = actionValue; + try { + options.chmodSync(p, 0o666) + } catch (er2) { + if (er2.code === 'ENOENT') { + return + } else { + throw er } - }); + } - if (params.choices) { - if (typeof params.choices === 'string') { - params.choices = params.choices.split('').join(', '); - } else if (Array.isArray(params.choices)) { - params.choices = params.choices.join(', '); + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === 'ENOENT') { + return } else { - params.choices = Object.keys(params.choices).join(', '); + throw er } } - return sprintf(this._getHelpString(action), params); -}; - -HelpFormatter.prototype._splitLines = function (text, width) { - var lines = []; - var delimiters = [ ' ', '.', ',', '!', '?' ]; - var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); - - text = text.replace(/[\n\|\t]/g, ' '); + if (stats.isDirectory()) { + rmdirSync(p, options, er) + } else { + options.unlinkSync(p) + } +} - text = text.trim(); - text = text.replace(this._whitespaceMatcher, ' '); +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') - // Wraps the single paragraph in text (a string) so every line - // is at most width characters long. - text.split(c.EOL).forEach(function (line) { - if (width >= line.length) { - lines.push(line); - return; + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { + rmkids(p, options, cb) + } else if (er && er.code === 'ENOTDIR') { + cb(originalEr) + } else { + cb(er) } + }) +} - var wrapStart = 0; - var wrapEnd = width; - var delimiterIndex = 0; - while (wrapEnd <= line.length) { - if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { - delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; - wrapEnd = wrapStart + delimiterIndex + 1; - } - lines.push(line.substring(wrapStart, wrapEnd)); - wrapStart = wrapEnd; - wrapEnd += width; +function rmkids (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, (er, files) => { + if (er) return cb(er) + + let n = files.length + let errState + + if (n === 0) return options.rmdir(p, cb) + + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) { + return + } + if (er) return cb(errState = er) + if (--n === 0) { + options.rmdir(p, cb) + } + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + let st + + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') + + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === 'ENOENT') { + return } - if (wrapStart < line.length) { - lines.push(line.substring(wrapStart, wrapEnd)); + + // Windows can EPERM on stat. Life is suffering. + if (er.code === 'EPERM' && isWindows) { + fixWinEPERMSync(p, options, er) } - }); + } - return lines; -}; + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) { + rmdirSync(p, options, null) + } else { + options.unlinkSync(p) + } + } catch (er) { + if (er.code === 'ENOENT') { + return + } else if (er.code === 'EPERM') { + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + } else if (er.code !== 'EISDIR') { + throw er + } + rmdirSync(p, options, er) + } +} -HelpFormatter.prototype._fillText = function (text, width, indent) { - var lines = this._splitLines(text, width); - lines = lines.map(function (line) { - return indent + line; - }); - return lines.join(c.EOL); -}; +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) -HelpFormatter.prototype._getHelpString = function (action) { - return action.help; -}; + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === 'ENOTDIR') { + throw originalEr + } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { + rmkidsSync(p, options) + } else if (er.code !== 'ENOENT') { + throw er + } + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) + + if (isWindows) { + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const startTime = Date.now() + do { + try { + const ret = options.rmdirSync(p, options) + return ret + } catch {} + } while (Date.now() - startTime < 500) // give up after 500ms + } else { + const ret = options.rmdirSync(p, options) + return ret + } +} + +module.exports = rimraf +rimraf.sync = rimrafSync /***/ }), -/* 533 */, -/* 534 */, -/* 535 */, -/* 536 */, -/* 537 */, -/* 538 */, -/* 539 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 475 */, +/* 476 */, +/* 477 */, +/* 478 */, +/* 479 */, +/* 480 */, +/* 481 */, +/* 482 */, +/* 483 */, +/* 484 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +const { spawn } = __webpack_require__(129); +var assert = __webpack_require__(357); -Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); -const http = __webpack_require__(605); -const https = __webpack_require__(34); -const pm = __webpack_require__(950); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; +const { TimeoutError, logger } = __webpack_require__(79); +const fs = __webpack_require__(747); + +class ExitError extends Error { + constructor(message, code) { + super(message); + this.code = code; + } } -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout + +const FETCH_DEPTH = 10; + +const COMMON_ARGS = [ + "-c", + "user.name=GitHub", + "-c", + "user.email=noreply@github.com" ]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } + +function git(cwd, ...args) { + const stdio = [ + "ignore", + "pipe", + logger.level === "trace" || logger.level === "debug" ? "inherit" : "pipe" + ]; + // the URL passed to the clone command could contain a password! + const command = `git ${args.join(" ")}`; + logger.debug("Executing", command); + return new Promise((resolve, reject) => { + const proc = spawn( + "git", + COMMON_ARGS.concat(args.filter(a => a !== null)), + { cwd, stdio } + ); + const buffers = []; + proc.stdout.on("data", data => buffers.push(data)); + proc.stderr.on("data", data => buffers.push(data)); + + proc.on("error", () => { + reject(new Error(`command failed: ${command}`)); + }); + proc.on("exit", code => { + const stdoutData = Buffer.concat(buffers); + if (code === 0) { + resolve(stdoutData.toString("utf8").trim()); + } else { + reject( + new ExitError( + `command ${command} failed with code ${code}. Error Message: ${stdoutData}`, + code + ) + ); + } + }); + }); } -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = url.parse(requestUrl); - return parsedUrl.protocol === 'https:'; + +async function clone(from, to, branch) { + if (!fs.existsSync(to)) { + await git( + ".", + "clone", + "--quiet", + "--shallow-submodules", + "--no-tags", + "--branch", + branch, + from, + to + ); + } else { + logger.warn(`Folder ${to} already exist. Won't clone`); + } } -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } + +async function fetch(dir, branch) { + await git( + dir, + "fetch", + "--quiet", + "origin", + `${branch}:refs/remotes/origin/${branch}` + ); +} + +async function fetchUntilMergeBase(dir, branch, timeout) { + const maxTime = new Date().getTime() + timeout; + const ref = `refs/remotes/origin/${branch}`; + while (new Date().getTime() < maxTime) { + const base = await mergeBase(dir, "HEAD", ref); + if (base) { + const bases = [base]; + const parents = await mergeCommits(dir, ref); + let fetchMore = false; + for (const parent of parents.flat()) { + const b = await mergeBase(dir, parent, ref); + if (b) { + if (!bases.includes(b)) { + bases.push(b); + } + } else { + // we found a commit which does not have a common ancestor with + // the branch we want to merge, so we need to fetch more + fetchMore = true; + break; } + } + if (!fetchMore) { + const commonBase = await mergeBase(dir, ...bases); + if (!commonBase) { + throw new Error(`failed to find common base for ${bases}`); + } + return commonBase; + } } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); + await fetchDeepen(dir); + } + throw new TimeoutError(); +} + +async function fetchDeepen(dir) { + await git(dir, "fetch", "--quiet", "--deepen", FETCH_DEPTH); +} + +async function mergeBase(dir, ...refs) { + if (refs.length === 1) { + return refs[0]; + } else if (refs.length < 1) { + throw new Error("empty refs!"); + } + let todo = refs; + try { + while (todo.length > 1) { + const base = await git(dir, "merge-base", todo[0], todo[1]); + todo = [base].concat(todo.slice(2)); } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); + return todo[0]; + } catch (e) { + if (e instanceof ExitError && e.code === 1) { + return null; + } else { + throw e; } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = url.parse(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = url.parse(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = url.parse(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(872); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - proxyAuth: proxyUrl.auth, - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: 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 - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new Error(msg); - // attach statusCode and body obj (if available) to the error object - err['statusCode'] = statusCode; - if (response.result) { - err['result'] = response.result; - } - reject(err); - } - else { - resolve(response); - } - }); + } +} + +async function mergeCommits(dir, ref) { + return (await git(dir, "rev-list", "--parents", `${ref}..HEAD`)) + .split(/\n/g) + .map(line => line.split(/ /g).slice(1)) + .filter(commit => commit.length > 1); +} + +async function merge(dir, group, repositoryName, branch) { + return await git( + dir, + "pull", + `https://github.com/${group}/${repositoryName}`, + branch + ); +} + +async function head(dir) { + return await git(dir, "show-ref", "--head", "-s", "/HEAD"); +} + +async function sha(dir, branch) { + return await git(dir, "show-ref", "-s", `refs/remotes/origin/${branch}`); +} + +async function rebase(dir, branch) { + return await git(dir, "rebase", "--quiet", "--autosquash", branch); +} + +async function push(dir, force, branch) { + return await git( + dir, + "push", + "--quiet", + force ? "--force-with-lease" : null, + "origin", + branch + ); +} + +async function doesBranchExist(octokit, owner, repo, branch) { + assert(owner, "owner is not defined"); + assert(repo, "repo is not defined"); + assert(branch, "branch is not defined"); + try { + const { status } = await octokit.repos.getBranch({ + owner, + repo, + branch + }); + return status == 200; + } catch (e) { + logger.warn( + `project github.com/${owner}/${repo}:${branch} does not exist. It's not necessarily an error.` + ); + return false; + } +} + +/** + * Checks if there is a pull request either from a forked project or the same project + * @param {Object} octokit instance + * @param {String} owner the repo owner or group + * @param {String} repo the repository name + * @param {String} branch the branch of the pull request to look for + * @param {String} fromAuthor the pull request author + */ +async function hasPullRequest(octokit, owner, repo, branch, fromAuthor) { + return ( + (await hasForkPullRequest(octokit, owner, repo, branch, fromAuthor)) || + (await hasOriginPullRequest(octokit, owner, repo, branch)) + ); +} + +/** + * Checks if there is a pull request from a forked project + * @param {Object} octokit instance + * @param {String} owner the repo owner or group + * @param {String} repo the repository name + * @param {String} branch the branch of the pull request to look for + * @param {String} fromAuthor the pull request author + */ +async function hasForkPullRequest(octokit, owner, repo, branch, fromAuthor) { + assert(owner, "owner is not defined"); + assert(repo, "repo is not defined"); + assert(branch, "branch is not defined"); + assert(fromAuthor, "fromAuthor is not defined"); + try { + const { status, data } = await octokit.pulls.list({ + owner, + repo, + state: "open", + head: `${fromAuthor}:${branch}` + }); + return status == 200 && data.length > 0; + } catch (e) { + logger.error( + `Error getting pull request list from https://api.github.com/repos/${owner}/${repo}/pulls?head=${fromAuthor}:${branch}&state=open'".` + ); + throw e; + } +} + +/** + * Checks if there is a pull request from the same project + * @param {Object} octokit instance + * @param {String} owner the repo owner or group + * @param {String} repo the repository name + * @param {String} branch the branch of the pull request to look for + */ +async function hasOriginPullRequest(octokit, owner, repo, branch) { + assert(owner, "owner is not defined"); + assert(repo, "repo is not defined"); + assert(branch, "branch is not defined"); + try { + const { status, data } = await octokit.pulls.list({ + owner, + repo, + state: "open", + head: `${owner}:${branch}` + }); + return status == 200 && data.length > 0; + } catch (e) { + logger.error( + `Error getting pull request list from https://api.github.com/repos/${owner}/${repo}/pulls?head=${owner}:${branch}&state=open'".` + ); + throw e; + } +} + +async function getForkedProject( + octokit, + owner, + repo, + wantedOwner, + page = 1, + per_page = 100 +) { + assert(owner, "owner is not defined"); + assert(repo, "repo is not defined"); + assert(wantedOwner, "wantedOwner is not defined"); + assert(page, "page is not defined"); + try { + const { status, data } = await octokit.repos.listForks({ + owner, + repo, + page + }); + if (status == 200) { + if (data && data.length > 0) { + const forkedProject = data.find( + forkedProject => forkedProject.owner.login === wantedOwner + ); + return forkedProject + ? forkedProject + : await getForkedProject( + octokit, + owner, + repo, + wantedOwner, + ++page, + per_page + ); + } else { + return undefined; + } } + } catch (e) { + logger.error( + `Error getting forked project list from https://api.github.com/repos/${owner}/${repo}/forks?per_page=${per_page}&page=${page}'".` + ); + throw e; + } } -exports.HttpClient = HttpClient; +module.exports = { + ExitError, + git, + clone, + fetch, + fetchUntilMergeBase, + fetchDeepen, + mergeBase, + mergeCommits, + merge, + head, + sha, + rebase, + push, + doesBranchExist, + hasPullRequest, + getForkedProject +}; -/***/ }), -/* 540 */, -/* 541 */, -/* 542 */, -/* 543 */, -/* 544 */, -/* 545 */, -/* 546 */, -/* 547 */, -/* 548 */ -/***/ (function(module) { - -"use strict"; +/***/ }), +/* 485 */, +/* 486 */, +/* 487 */, +/* 488 */, +/* 489 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/*! - * isobject - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ +"use strict"; -function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false; -} -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ +const path = __webpack_require__(622); +const which = __webpack_require__(814); +const pathKey = __webpack_require__(39)(); -function isObjectObject(o) { - return isObject(o) === true - && Object.prototype.toString.call(o) === '[object Object]'; -} +function resolveCommandAttempt(parsed, withoutPathExt) { + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; -function isPlainObject(o) { - var ctor,prot; + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (hasCustomCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } - if (isObjectObject(o) === false) return false; + let resolved; - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; + try { + resolved = which.sync(parsed.command, { + path: (parsed.options.env || process.env)[pathKey], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + process.chdir(cwd); + } - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + return resolved; +} - // Most likely a plain Object - return true; +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } -module.exports = isPlainObject; +module.exports = resolveCommand; /***/ }), -/* 549 */, -/* 550 */, -/* 551 */, -/* 552 */ -/***/ (function(__unusedmodule, exports) { - -(function(window) { - var re = { - not_string: /[^s]/, - number: /[diefg]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ - } +/* 490 */, +/* 491 */, +/* 492 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - function sprintf() { - var key = arguments[0], cache = sprintf.cache - if (!(cache[key] && cache.hasOwnProperty(key))) { - cache[key] = sprintf.parse(key) - } - return sprintf.format.call(null, cache[key], arguments) - } +const assert = __webpack_require__(357); - sprintf.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]) - if (node_type === "string") { - output[output.length] = parse_tree[i] - } - else if (node_type === "array") { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } +const allowedVersions = ["1.0"]; - if (get_type(arg) == "function") { - arg = arg() - } +function validateDefinition(definition) { + validateVersion(definition.version, "definition"); +} - if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { - throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) - } +function validateDependencies(dependencies) { + validateVersion(dependencies.version, "dependencies"); +} - if (re.number.test(match[8])) { - is_positive = arg >= 0 - } +function validateVersion(version, fileName) { + assert( + version, + `version is not defined on ${fileName} file. Please add version: x, where x is one of these values ${allowedVersions}` + ); + assert( + allowedVersions.includes(version), + `version ${version} is not allowed in ${fileName} file. Allowed versions: ${allowedVersions}` + ); +} - switch (match[8]) { - case "b": - arg = arg.toString(2) - break - case "c": - arg = String.fromCharCode(arg) - break - case "d": - case "i": - arg = parseInt(arg, 10) - break - case "j": - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case "e": - arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() - break - case "f": - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case "g": - arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) - break - case "o": - arg = arg.toString(8) - break - case "s": - arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) - break - case "u": - arg = arg >>> 0 - break - case "x": - arg = arg.toString(16) - break - case "X": - arg = arg.toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output[output.length] = arg - } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? "+" : "-" - arg = arg.toString().replace(re.sign, "") - } - else { - sign = "" - } - pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" - output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) - } - } - } - return output.join("") - } +function validateNode(node) { + assert( + node, + "node is undefined. Please check your definition file. For example, projects declared as a dependency for another project has to be already defined (I mean from order point of view)." + ); + assert( + node.project, + "project can't be undefined, please properly define your file." + ); + assert( + node.project.split("/").length === 2, + `project has to defined following \`group/project\` pattern (i.e. \`kiegroup/drools\`). "${node.project}" instead` + ); +} - sprintf.cache = {} - - sprintf.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = match[0] - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = "%" - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - } - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") - } - parse_tree[parse_tree.length] = match - } - else { - throw new SyntaxError("[sprintf] unexpected placeholder") - } - _fmt = _fmt.substring(match[0].length) - } - return parse_tree - } - - var vsprintf = function(fmt, argv, _argv) { - _argv = (argv || []).slice(0) - _argv.splice(0, 0, fmt) - return sprintf.apply(null, _argv) - } - - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() - } - - function str_repeat(input, multiplier) { - return Array(multiplier + 1).join(input) - } - - /** - * export to either browser or node.js - */ - if (true) { - exports.sprintf = sprintf - exports.vsprintf = vsprintf - } - else {} -})(typeof window === "undefined" ? this : window); +module.exports = { validateDefinition, validateDependencies, validateNode }; /***/ }), -/* 553 */, -/* 554 */, -/* 555 */, -/* 556 */ -/***/ (function(module) { +/* 493 */, +/* 494 */, +/* 495 */, +/* 496 */, +/* 497 */, +/* 498 */, +/* 499 */, +/* 500 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const copy = __webpack_require__(774).copy +const remove = __webpack_require__(723).remove +const mkdirp = __webpack_require__(727).mkdirp +const pathExists = __webpack_require__(322).pathExists +const stat = __webpack_require__(127) - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; +function move (src, dest, opts, cb) { + if (typeof opts === 'function') { + cb = opts + opts = {} } -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; + const overwrite = opts.overwrite || opts.clobber || false -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; + stat.checkPaths(src, dest, 'move', (err, stats) => { + if (err) return cb(err) + const { srcStat } = stats + stat.checkParentPaths(src, srcStat, dest, 'move', err => { + if (err) return cb(err) + mkdirp(path.dirname(dest), err => { + if (err) return cb(err) + return doRename(src, dest, overwrite, cb) + }) + }) + }) +} - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); +function doRename (src, dest, overwrite, cb) { + if (overwrite) { + return remove(dest, err => { + if (err) return cb(err) + return rename(src, dest, overwrite, cb) + }) } + pathExists(dest, (err, destExists) => { + if (err) return cb(err) + if (destExists) return cb(new Error('dest already exists.')) + return rename(src, dest, overwrite, cb) + }) +} - return result; -}; +function rename (src, dest, overwrite, cb) { + fs.rename(src, dest, err => { + if (!err) return cb() + if (err.code !== 'EXDEV') return cb(err) + return moveAcrossDevice(src, dest, overwrite, cb) + }) +} +function moveAcrossDevice (src, dest, overwrite, cb) { + const opts = { + overwrite, + errorOnExist: true + } + copy(src, dest, opts, err => { + if (err) return cb(err) + return remove(src, cb) + }) +} -module.exports = YAMLException; +module.exports = move /***/ }), -/* 557 */, -/* 558 */, -/* 559 */, -/* 560 */, -/* 561 */, -/* 562 */, -/* 563 */, -/* 564 */, -/* 565 */, -/* 566 */, -/* 567 */, -/* 568 */ +/* 501 */, +/* 502 */, +/* 503 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - +const { run: uploadArtifacts } = __webpack_require__(395); +const { logger } = __webpack_require__(79); -const path = __webpack_require__(622); -const niceTry = __webpack_require__(948); -const resolveCommand = __webpack_require__(489); -const escape = __webpack_require__(462); -const readShebang = __webpack_require__(389); -const semver = __webpack_require__(48); +async function archiveArtifacts(nodeTirggering, nodeArray, on) { + const nodesToArchive = getNodesToArchive(nodeTirggering, nodeArray); + logger.info( + nodesToArchive.length > 0 + ? `Archiving artifacts for ${nodesToArchive.map(node => node.project)}` + : "No artifacts to archive" + ); -const isWin = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + await uploadNodes(nodesToArchive, on); +} -// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0 -const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false; +function getNodesToArchive(nodeTriggering, nodeArray) { + const archiveDependencies = + nodeTriggering.build["archive-artifacts"] && + nodeTriggering.build["archive-artifacts"].dependencies + ? nodeTriggering.build["archive-artifacts"].dependencies + : "none"; + + return archiveDependencies === "none" + ? [nodeTriggering].filter( + node => + node.build["archive-artifacts"] && + node.build["archive-artifacts"].paths + ) + : nodeArray.filter( + node => + node.build["archive-artifacts"] && + node.build["archive-artifacts"].paths && + (archiveDependencies === "all" || + archiveDependencies.includes(node.project) || + node.project === nodeTriggering.project) + ); +} -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); +async function uploadNodes(nodesToArchive, on) { + await Promise.allSettled( + nodesToArchive.map(async node => { + logger.info(`Project [${node.project}]. Uploading artifacts...`); + const uploadResponse = await uploadArtifacts( + node.build["archive-artifacts"], + on + ); + if (uploadResponse) { + const uploadArtifactsMessage = + uploadResponse.artifactItems && + uploadResponse.artifactItems.length > 0 + ? `Uploaded Items (${uploadResponse.artifactItems.length}): ${uploadResponse.artifactItems}.` + : ""; + if ( + uploadResponse.failedItems && + uploadResponse.failedItems.length > 0 + ) { + logger.error( + `Project [${node.project}] Failed State. Artifact [${uploadResponse.artifactName}]. Failed Items (${uploadResponse.failedItems.length}): ${uploadResponse.failedItems}. ${uploadArtifactsMessage}` + ); + return Promise.reject(uploadResponse); + } else { + logger.info( + `Project [${node.project}]. Artifact [${uploadResponse.artifactName}]. ${uploadArtifactsMessage}` + ); + return Promise.resolve(uploadResponse); + } + } else { + logger.info(`Project [${node.project}]. No artifacts uploaded`); + return Promise.resolve(undefined); + } + }) + ).then(promises => { + logger.info("-------------- ARCHIVE ARTIFACTS SUMMARY --------------"); + const totalUploadResponses = promises + .map(promiseResult => promiseResult.value || promiseResult.reason) + .filter( + uploadResponse => + uploadResponse && + uploadResponse.artifactItems && + uploadResponse.artifactItems.length > 0 + ); + const uploadedFiles = totalUploadResponses.flatMap( + uploadResponse => uploadResponse.artifactItems + ); + const failureUploadResponses = promises + .filter(promiseResult => promiseResult.reason) + .map(promiseResult => promiseResult.reason) + .filter( + uploadResponse => + uploadResponse && + uploadResponse.failedItems && + uploadResponse.failedItems.length > 0 + ); + const failedFiles = failureUploadResponses.flatMap( + uploadResponse => uploadResponse.failedItems + ); + logger.info( + `Artifacts uploaded (${ + totalUploadResponses.length + }): ${totalUploadResponses.map( + uploadResponse => uploadResponse.artifactName + )}. Files (${uploadedFiles.length}): ${uploadedFiles}` + ); + logger.info( + `Artifacts failed (${ + failureUploadResponses.length + }): ${failureUploadResponses.map( + uploadResponse => uploadResponse.artifactName + )}. Files (${failedFiles.length}): ${failedFiles}` + ); + }); +} - const shebang = parsed.file && readShebang(parsed.file); +module.exports = { archiveArtifacts }; - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - return resolveCommand(parsed); - } +/***/ }), +/* 504 */, +/* 505 */, +/* 506 */, +/* 507 */, +/* 508 */, +/* 509 */, +/* 510 */ +/***/ (function(module) { - return parsed.file; -} +module.exports = addHook -function parseNonShell(parsed) { - if (!isWin) { - return parsed; - } +function addHook (state, kind, name, hook) { + var orig = hook + if (!state.registry[name]) { + state.registry[name] = [] + } - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); - - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + if (kind === 'before') { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)) + } + } - const shellCommand = [parsed.command].concat(parsed.args).join(' '); + 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 + }) + } + } - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + if (kind === 'error') { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options) + }) } + } - return parsed; + state.registry[name].push({ + hook: hook, + orig: orig + }) } -function parseShell(parsed) { - // If node supports the shell option, there's no need to mimic its behavior - if (supportsShellOption) { - return parsed; - } - // Mimic node shell option - // See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 - const shellCommand = [parsed.command].concat(parsed.args).join(' '); +/***/ }), +/* 511 */, +/* 512 */, +/* 513 */, +/* 514 */, +/* 515 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (isWin) { - parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } else { - if (typeof parsed.options.shell === 'string') { - parsed.command = parsed.options.shell; - } else if (process.platform === 'android') { - parsed.command = '/system/bin/sh'; - } else { - parsed.command = '/bin/sh'; - } +"use strict"; +/** + * class Namespace + * + * Simple object for storing attributes. Implements equality by attribute names + * and values, and provides a simple string representation. + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object + **/ - parsed.args = ['-c', shellCommand]; - } - return parsed; -} +var $$ = __webpack_require__(255); -function parse(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } +/** + * new Namespace(options) + * - options(object): predefined propertis for result object + * + **/ +var Namespace = module.exports = function Namespace(options) { + $$.extend(this, options); +}; - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original +/** + * Namespace#isset(key) -> Boolean + * - key (string|number): property name + * + * Tells whenever `namespace` contains given `key` or not. + **/ +Namespace.prototype.isset = function (key) { + return $$.has(this, key); +}; - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; +/** + * Namespace#set(key, value) -> self + * -key (string|number|object): propery name + * -value (mixed): new property value + * + * Set the property named key with value. + * If key object then set all key properties to namespace object + **/ +Namespace.prototype.set = function (key, value) { + if (typeof (key) === 'object') { + $$.extend(this, key); + } else { + this[key] = value; + } + return this; +}; - // Delegate further parsing to shell or non-shell - return options.shell ? parseShell(parsed) : parseNonShell(parsed); -} +/** + * Namespace#get(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return the property key or defaulValue if not set + **/ +Namespace.prototype.get = function (key, defaultValue) { + return !this[key] ? defaultValue : this[key]; +}; -module.exports = parse; +/** + * Namespace#unset(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return data[key](and delete it) or defaultValue + **/ +Namespace.prototype.unset = function (key, defaultValue) { + var value = this[key]; + if (value !== null) { + delete this[key]; + return value; + } + return defaultValue; +}; /***/ }), -/* 569 */ +/* 516 */, +/* 517 */ /***/ (function(module, __unusedexports, __webpack_require__) { -const assert = __webpack_require__(357) +"use strict"; + + +const u = __webpack_require__(676).fromCallback +const fs = __webpack_require__(598) const path = __webpack_require__(622) -const fs = __webpack_require__(747) -let glob = undefined -try { - glob = __webpack_require__(402) -} catch (_err) { - // treat glob as optional. -} +const mkdir = __webpack_require__(727) +const pathExists = __webpack_require__(322).pathExists -const defaultGlobOpts = { - nosort: true, - silent: true -} +function outputFile (file, data, encoding, callback) { + if (typeof encoding === 'function') { + callback = encoding + encoding = 'utf8' + } -// for EMFILE handling -let timeout = 0 + const dir = path.dirname(file) + pathExists(dir, (err, itDoes) => { + if (err) return callback(err) + if (itDoes) return fs.writeFile(file, data, encoding, callback) -const isWindows = (process.platform === "win32") + mkdir.mkdirs(dir, err => { + if (err) return callback(err) -const defaults = options => { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] + fs.writeFile(file, data, encoding, callback) + }) }) +} - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') +function outputFileSync (file, ...args) { + const dir = path.dirname(file) + if (fs.existsSync(dir)) { + return fs.writeFileSync(file, ...args) } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts + mkdir.mkdirsSync(dir) + fs.writeFileSync(file, ...args) } -const rimraf = (p, options, cb) => { - if (typeof options === 'function') { - cb = options - options = {} - } +module.exports = { + outputFile: u(outputFile), + outputFileSync +} - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - defaults(options) +/***/ }), +/* 518 */, +/* 519 */, +/* 520 */, +/* 521 */, +/* 522 */, +/* 523 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - let busyTries = 0 - let errState = null - let n = 0 +var register = __webpack_require__(363) +var addHook = __webpack_require__(510) +var removeHook = __webpack_require__(763) - const next = (er) => { - errState = errState || er - if (--n === 0) - cb(errState) - } +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) - const afterGlob = (er, results) => { - if (er) - return cb(er) +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef - n = results.length - if (n === 0) - return cb() + ;['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) + }) +} - results.forEach(p => { - const CB = (er) => { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) - } +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} + } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(() => rimraf_(p, options, CB), timeout ++) - } +function HookCollection () { + var state = { + registry: {} + } - // already gone - if (er.code === "ENOENT") er = null - } + var hook = register.bind(null, state) + bindApi(hook, state) - timeout = 0 - next(er) - } - rimraf_(p, options, CB) - }) + 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() +} - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() - options.lstat(p, (er, stat) => { - if (!er) - return afterGlob(null, [p]) +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 - glob(p, options.glob, afterGlob) - }) -} +/***/ }), +/* 524 */, +/* 525 */, +/* 526 */, +/* 527 */, +/* 528 */, +/* 529 */, +/* 530 */, +/* 531 */, +/* 532 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -const rimraf_ = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') +"use strict"; +/** + * class HelpFormatter + * + * Formatter for generating usage messages and argument help strings. Only the + * name of this class is considered a public API. All the methods provided by + * the class are considered an implementation detail. + * + * Do not call in your code, use this class only for inherits your own forvatter + * + * ToDo add [additonal formatters][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#formatter-class + **/ - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") - return cb(null) - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +var sprintf = __webpack_require__(552).sprintf; - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) +// Constants +var c = __webpack_require__(45); - options.unlink(p, er => { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) -} +var $$ = __webpack_require__(255); -const fixWinEPERM = (p, options, er, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - options.chmod(p, 0o666, er2 => { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, (er3, stats) => { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) +/*:nodoc:* internal + * new Support(parent, heding) + * - parent (object): parent section + * - heading (string): header string + * + **/ +function Section(parent, heading) { + this._parent = parent; + this._heading = heading; + this._items = []; } -const fixWinEPERMSync = (p, options, er) => { - assert(p) - assert(options) +/*:nodoc:* internal + * Section#addItem(callback) -> Void + * - callback (array): tuple with function and args + * + * Add function for single element + **/ +Section.prototype.addItem = function (callback) { + this._items.push(callback); +}; - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } +/*:nodoc:* internal + * Section#formatHelp(formatter) -> string + * - formatter (HelpFormatter): current formatter + * + * Form help section string + * + **/ +Section.prototype.formatHelp = function (formatter) { + var itemHelp, heading; - let stats - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er + // format the indented section + if (this._parent) { + formatter._indent(); } - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} - -const rmdir = (p, options, originalEr, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') + itemHelp = this._items.map(function (item) { + var obj, func, args; - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} + obj = formatter; + func = item[0]; + args = item[1]; + return func.apply(obj, args); + }); + itemHelp = formatter._joinParts(itemHelp); -const rmkids = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') + if (this._parent) { + formatter._dedent(); + } - options.readdir(p, (er, files) => { - if (er) - return cb(er) - let n = files.length - if (n === 0) - return options.rmdir(p, cb) - let errState - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} + // return nothing if the section was empty + if (!itemHelp) { + return ''; + } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -const rimrafSync = (p, options) => { - options = options || {} - defaults(options) + // add the heading if the section was non-empty + heading = ''; + if (this._heading && this._heading !== c.SUPPRESS) { + var currentIndent = formatter.currentIndent; + heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL; + } - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + // join the section-initialize newline, the heading and the help + return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]); +}; - let results +/** + * new HelpFormatter(options) + * + * #### Options: + * - `prog`: program name + * - `indentIncriment`: indent step, default value 2 + * - `maxHelpPosition`: max help position, default value = 24 + * - `width`: line width + * + **/ +var HelpFormatter = module.exports = function HelpFormatter(options) { + options = options || {}; - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } - } + this._prog = options.prog; - if (!results.length) - return + this._maxHelpPosition = options.maxHelpPosition || 24; + this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); - for (let i = 0; i < results.length; i++) { - const p = results[i] + this._currentIndent = 0; + this._indentIncriment = options.indentIncriment || 2; + this._level = 0; + this._actionMaxLength = 0; - let st - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + this._rootSection = new Section(null); + this._currentSection = this._rootSection; - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } + this._whitespaceMatcher = new RegExp('\\s+', 'g'); + this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g'); +}; - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er +HelpFormatter.prototype._indent = function () { + this._currentIndent += this._indentIncriment; + this._level += 1; +}; - rmdirSync(p, options, er) - } +HelpFormatter.prototype._dedent = function () { + this._currentIndent -= this._indentIncriment; + this._level -= 1; + if (this._currentIndent < 0) { + throw new Error('Indent decreased below 0.'); } -} +}; -const rmdirSync = (p, options, originalEr) => { - assert(p) - assert(options) +HelpFormatter.prototype._addItem = function (func, args) { + this._currentSection.addItem([ func, args ]); +}; - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } -} +// +// Message building methods +// -const rmkidsSync = (p, options) => { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) +/** + * HelpFormatter#startSection(heading) -> Void + * - heading (string): header string + * + * Start new help section + * + * See alse [code example][1] + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.startSection = function (heading) { + this._indent(); + var section = new Section(this._currentSection, heading); + var func = section.formatHelp.bind(section); + this._addItem(func, [ this ]); + this._currentSection = section; +}; - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const retries = isWindows ? 100 : 1 - let i = 0 - do { - let threw = true - try { - const ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) -} +/** + * HelpFormatter#endSection -> Void + * + * End help section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + **/ +HelpFormatter.prototype.endSection = function () { + this._currentSection = this._currentSection._parent; + this._dedent(); +}; -module.exports = rimraf -rimraf.sync = rimrafSync +/** + * HelpFormatter#addText(text) -> Void + * - text (string): plain text + * + * Add plain text into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addText = function (text) { + if (text && text !== c.SUPPRESS) { + this._addItem(this._formatText, [ text ]); + } +}; +/** + * HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void + * - usage (string): usage text + * - actions (array): actions list + * - groups (array): groups list + * - prefix (string): usage prefix + * + * Add usage data into current section + * + * ##### Example + * + * formatter.addUsage(this.usage, this._actions, []); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { + if (usage !== c.SUPPRESS) { + this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]); + } +}; -/***/ }), -/* 570 */, -/* 571 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/** + * HelpFormatter#addArgument(action) -> Void + * - action (object): action + * + * Add argument into current section + * + * Single variant of [[HelpFormatter#addArguments]] + **/ +HelpFormatter.prototype.addArgument = function (action) { + if (action.help !== c.SUPPRESS) { + var self = this; -module.exports = minimatch -minimatch.Minimatch = Minimatch + // find all invocations + var invocations = [ this._formatActionInvocation(action) ]; + var invocationLength = invocations[0].length; -var path = { sep: '/' } -try { - path = __webpack_require__(622) -} catch (er) {} + var actionLength; -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(306) - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + if (action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') + var invocationNew = self._formatActionInvocation(subaction); + invocations.push(invocationNew); + invocationLength = Math.max(invocationLength, invocationNew.length); -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} + }); + this._dedent(); + } -// normalizes slashes. -var slashSplit = /\/+/ + // update the maximum item length + actionLength = invocationLength + this._currentIndent; + this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) + // add the item to the list + this._addItem(this._formatAction, [ action ]); } -} - -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch +}; - var orig = minimatch +/** + * HelpFormatter#addArguments(actions) -> Void + * - actions (array): actions list + * + * Mass add arguments into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addArguments = function (actions) { + var self = this; + actions.forEach(function (action) { + self.addArgument(action); + }); +}; - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } +// +// Help-formatting methods +// - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) +/** + * HelpFormatter#formatHelp -> string + * + * Format help + * + * ##### Example + * + * formatter.addText(this.epilog); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.formatHelp = function () { + var help = this._rootSection.formatHelp(this); + if (help) { + help = help.replace(this._longBreakMatcher, c.EOL + c.EOL); + help = $$.trimChars(help, c.EOL) + c.EOL; } + return help; +}; - return m -} - -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} +HelpFormatter.prototype._joinParts = function (partStrings) { + return partStrings.filter(function (part) { + return (part && part !== c.SUPPRESS); + }).join(''); +}; -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') +HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { + if (!prefix && typeof prefix !== 'string') { + prefix = 'usage: '; } - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + actions = actions || []; + groups = groups || []; - // "" only matches "" - if (pattern.trim() === '') return p === '' - return new Minimatch(pattern, options).match(p) -} + // if usage is specified, use that + if (usage) { + usage = sprintf(usage, { prog: this._prog }); -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } + // if no optionals or positionals are available, usage is just prog + } else if (!usage && actions.length === 0) { + usage = this._prog; - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } + // if optionals and positionals are available, calculate usage + } else if (!usage) { + var prog = this._prog; + var optionals = []; + var positionals = []; + var actionUsage; + var textWidth; - if (!options) options = {} - pattern = pattern.trim() + // split optionals from positionals + actions.forEach(function (action) { + if (action.isOptional()) { + optionals.push(action); + } else { + positionals.push(action); + } + }); - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + // build full usage string + actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); + usage = [ prog, actionUsage ].join(' '); - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false + // wrap the usage parts if it's too long + textWidth = this._width - this._currentIndent; + if ((prefix.length + usage.length) > textWidth) { - // make the set of regexps etc. - this.make() -} + // break usage into wrappable parts + var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); + var optionalUsage = this._formatActionsUsage(optionals, groups); + var positionalUsage = this._formatActionsUsage(positionals, groups); -Minimatch.prototype.debug = function () {} -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return + var optionalParts = optionalUsage.match(regexpPart); + var positionalParts = positionalUsage.match(regexpPart) || []; - var pattern = this.pattern - var options = this.options + if (optionalParts.join(' ') !== optionalUsage) { + throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); + } + if (positionalParts.join(' ') !== positionalUsage) { + throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); + } - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } + // helper for wrapping lines + /*eslint-disable func-style*/ // node 0.10 compat + var _getLines = function (parts, indent, prefix) { + var lines = []; + var line = []; - // step 1: figure out negation, etc. - this.parseNegate() + var lineLength = prefix ? prefix.length - 1 : indent.length - 1; - // step 2: expand braces - var set = this.globSet = this.braceExpand() + parts.forEach(function (part) { + if (lineLength + 1 + part.length > textWidth) { + lines.push(indent + line.join(' ')); + line = []; + lineLength = indent.length - 1; + } + line.push(part); + lineLength += part.length + 1; + }); - if (options.debug) this.debug = console.error + if (line) { + lines.push(indent + line.join(' ')); + } + if (prefix) { + lines[0] = lines[0].substr(indent.length); + } + return lines; + }; - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) + var lines, indent, parts; + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * textWidth) { + indent = $$.repeat(' ', (prefix.length + prog.length + 1)); + if (optionalParts) { + lines = [].concat( + _getLines([ prog ].concat(optionalParts), indent, prefix), + _getLines(positionalParts, indent) + ); + } else if (positionalParts) { + lines = _getLines([ prog ].concat(positionalParts), indent, prefix); + } else { + lines = [ prog ]; + } - this.debug(this.pattern, set) + // if prog is long, put it on its own line + } else { + indent = $$.repeat(' ', prefix.length); + parts = optionalParts.concat(positionalParts); + lines = _getLines(parts, indent); + if (lines.length > 1) { + lines = [].concat( + _getLines(optionalParts, indent), + _getLines(positionalParts, indent) + ); + } + lines = [ prog ].concat(lines); + } + // join lines into usage + usage = lines.join(c.EOL); + } + } - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + // prefix with 'usage:' + return prefix + usage + c.EOL + c.EOL; +}; - this.debug(this.pattern, set) +HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { + // find group indices and identify actions in groups + var groupActions = []; + var inserts = []; + var self = this; - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + groups.forEach(function (group) { + var end; + var i; - this.debug(this.pattern, set) + var start = actions.indexOf(group._groupActions[0]); + if (start >= 0) { + end = start + group._groupActions.length; - this.set = set -} + //if (actions.slice(start, end) === group._groupActions) { + if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) { + group._groupActions.forEach(function (action) { + groupActions.push(action); + }); -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + if (!group.required) { + if (inserts[start]) { + inserts[start] += ' ['; + } else { + inserts[start] = '['; + } + inserts[end] = ']'; + } else { + if (inserts[start]) { + inserts[start] += ' ('; + } else { + inserts[start] = '('; + } + inserts[end] = ')'; + } + for (i = start + 1; i < end; i += 1) { + inserts[i] = '|'; + } + } + } + }); - if (options.nonegate) return + // collect all actions format strings + var parts = []; - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + actions.forEach(function (action, actionIndex) { + var part; + var optionString; + var argsDefault; + var argsString; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === c.SUPPRESS) { + parts.push(null); + if (inserts[actionIndex] === '|') { + inserts.splice(actionIndex, actionIndex); + } else if (inserts[actionIndex + 1] === '|') { + inserts.splice(actionIndex + 1, actionIndex + 1); + } -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + // produce all arg strings + } else if (!action.isOptional()) { + part = self._formatArgs(action, action.dest); -Minimatch.prototype.braceExpand = braceExpand + // if it's in a group, strip the outer [] + if (groupActions.indexOf(action) >= 0) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1); + } + } + // add the action string to the list + parts.push(part); -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options + // produce the first way to invoke the option in brackets } else { - options = {} - } - } + optionString = action.optionStrings[0]; - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + // if the Optional doesn't take a value, format is: -s or --long + if (action.nargs === 0) { + part = '' + optionString; - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } + // if the Optional takes a value, format is: -s ARGS or --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = self._formatArgs(action, argsDefault); + part = optionString + ' ' + argsString; + } + // make it look optional if it's not required or in a group + if (!action.required && groupActions.indexOf(action) < 0) { + part = '[' + part + ']'; + } + // add the action string to the list + parts.push(part); + } + }); - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] + // insert things at the necessary indices + for (var i = inserts.length - 1; i >= 0; --i) { + if (inserts[i] !== null) { + parts.splice(i, 0, inserts[i]); + } } - return expand(pattern) -} + // join all the action items with spaces + var text = parts.filter(function (part) { + return !!part; + }).join(' '); -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1'); // remove spaces + text = text.replace(/ ([\])])/g, '$1'); + text = text.replace(/\[ *\]/g, ''); // remove empty groups + text = text.replace(/\( *\)/g, ''); + text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups - var options = this.options + text = text.trim(); - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' + // return the text + return text; +}; - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this +HelpFormatter.prototype._formatText = function (text) { + text = sprintf(text, { prog: this._prog }); + var textWidth = this._width - this._currentIndent; + var indentIncriment = $$.repeat(' ', this._currentIndent); + return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL; +}; - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } +HelpFormatter.prototype._formatAction = function (action) { + var self = this; - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) + var helpText; + var helpLines; + var parts; + var indentFirst; - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } + // determine the required width and the entry label + var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); + var helpWidth = this._width - helpPosition; + var actionWidth = helpPosition - this._currentIndent - 2; + var actionHeader = this._formatActionInvocation(action); - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false + // no help; start on same line and add a final newline + if (!action.help) { + actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; - case '\\': - clearStateChar() - escaping = true - continue + // short action name; start on the same line and pad two spaces + } else if (actionHeader.length <= actionWidth) { + actionHeader = $$.repeat(' ', this._currentIndent) + + actionHeader + + ' ' + + $$.repeat(' ', actionWidth - actionHeader.length); + indentFirst = 0; - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + // long action name; start on the next line + } else { + actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; + indentFirst = helpPosition; + } - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } + // collect the pieces of the action help + parts = [ actionHeader ]; - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue + // if there was help for the action, add lines of help text + if (action.help) { + helpText = this._expandHelp(action); + helpLines = this._splitLines(helpText, helpWidth); + parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL); + helpLines.slice(1).forEach(function (line) { + parts.push($$.repeat(' ', helpPosition) + line + c.EOL); + }); - case '(': - if (inClass) { - re += '(' - continue - } + // or add a newline if the description doesn't end with one + } else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) { + parts.push(c.EOL); + } + // if there are any sub-actions, add their help as well + if (action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { + parts.push(self._formatAction(subaction)); + }); + this._dedent(); + } + // return a single string + return this._joinParts(parts); +}; - if (!stateChar) { - re += '\\(' - continue - } +HelpFormatter.prototype._formatActionInvocation = function (action) { + if (!action.isOptional()) { + var format_func = this._metavarFormatter(action, action.dest); + var metavars = format_func(1); + return metavars[0]; + } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue + var parts = []; + var argsDefault; + var argsString; - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + // if the Optional doesn't take a value, format is: -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.optionStrings); - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue + // if the Optional takes a value, format is: -s ARGS, --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = this._formatArgs(action, argsDefault); + action.optionStrings.forEach(function (optionString) { + parts.push(optionString + ' ' + argsString); + }); + } + return parts.join(', '); +}; - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } +HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { + var result; - clearStateChar() - re += '|' - continue + if (action.metavar || action.metavar === '') { + result = action.metavar; + } else if (action.choices) { + var choices = action.choices; - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + if (typeof choices === 'string') { + choices = choices.split('').join(', '); + } else if (Array.isArray(choices)) { + choices = choices.join(','); + } else { + choices = Object.keys(choices).join(','); + } + result = '{' + choices + '}'; + } else { + result = metavarDefault; + } - if (inClass) { - re += '\\' + c - continue - } + return function (size) { + if (Array.isArray(result)) { + return result; + } - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + var metavars = []; + for (var i = 0; i < size; i += 1) { + metavars.push(result); + } + return metavars; + }; +}; - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } +HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { + var result; + var metavars; - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for + var buildMetavar = this._metavarFormatter(action, metavarDefault); - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] + switch (action.nargs) { + /*eslint-disable no-undefined*/ + case undefined: + case null: + metavars = buildMetavar(1); + result = '' + metavars[0]; + break; + case c.OPTIONAL: + metavars = buildMetavar(1); + result = '[' + metavars[0] + ']'; + break; + case c.ZERO_OR_MORE: + metavars = buildMetavar(2); + result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; + break; + case c.ONE_OR_MORE: + metavars = buildMetavar(2); + result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; + break; + case c.REMAINDER: + result = '...'; + break; + case c.PARSER: + metavars = buildMetavar(1); + result = metavars[0] + ' ...'; + break; + default: + metavars = buildMetavar(action.nargs); + result = metavars.join(' '); } + return result; +}; - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +HelpFormatter.prototype._expandHelp = function (action) { + var params = { prog: this._prog }; - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + Object.keys(action).forEach(function (actionProperty) { + var actionValue = action[actionProperty]; - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } + if (actionValue !== c.SUPPRESS) { + params[actionProperty] = actionValue; + } + }); - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' + if (params.choices) { + if (typeof params.choices === 'string') { + params.choices = params.choices.split('').join(', '); + } else if (Array.isArray(params.choices)) { + params.choices = params.choices.join(', '); + } else { + params.choices = Object.keys(params.choices).join(', '); + } } - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } + return sprintf(this._getHelpString(action), params); +}; - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] +HelpFormatter.prototype._splitLines = function (text, width) { + var lines = []; + var delimiters = [ ' ', '.', ',', '!', '?' ]; + var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) + text = text.replace(/[\n\|\t]/g, ' '); - nlLast += nlAfter + text = text.trim(); + text = text.replace(this._whitespaceMatcher, ' '); - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + // Wraps the single paragraph in text (a string) so every line + // is at most width characters long. + text.split(c.EOL).forEach(function (line) { + if (width >= line.length) { + lines.push(line); + return; } - nlAfter = cleanAfter - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + var wrapStart = 0; + var wrapEnd = width; + var delimiterIndex = 0; + while (wrapEnd <= line.length) { + if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { + delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; + wrapEnd = wrapStart + delimiterIndex + 1; + } + lines.push(line.substring(wrapStart, wrapEnd)); + wrapStart = wrapEnd; + wrapEnd += width; } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } + if (wrapStart < line.length) { + lines.push(line.substring(wrapStart, wrapEnd)); + } + }); - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } + return lines; +}; - regExp._glob = pattern - regExp._src = re +HelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = this._splitLines(text, width); + lines = lines.map(function (line) { + return indent + line; + }); + return lines.join(c.EOL); +}; - return regExp -} +HelpFormatter.prototype._getHelpString = function (action) { + return action.help; +}; -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +/***/ }), +/* 533 */, +/* 534 */, +/* 535 */, +/* 536 */, +/* 537 */, +/* 538 */, +/* 539 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set +"use strict"; - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp +Object.defineProperty(exports, "__esModule", { value: true }); +const http = __webpack_require__(605); +const https = __webpack_require__(34); +const pm = __webpack_require__(950); +let tunnel; +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } } - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + readBody() { + return new Promise(async (resolve, reject) => { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + }); } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate } - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + let parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + options(requestUrl, additionalHeaders) { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - - -/***/ }), -/* 572 */, -/* 573 */, -/* 574 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var Type = __webpack_require__(945); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); - - -/***/ }), -/* 575 */, -/* 576 */, -/* 577 */, -/* 578 */, -/* 579 */, -/* 580 */, -/* 581 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - - - - -var Schema = __webpack_require__(733); - - -module.exports = new Schema({ - explicit: [ - __webpack_require__(574), - __webpack_require__(921), - __webpack_require__(988) - ] -}); - - -/***/ }), -/* 582 */, -/* 583 */, -/* 584 */, -/* 585 */, -/* 586 */, -/* 587 */, -/* 588 */, -/* 589 */, -/* 590 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __importStar(__webpack_require__(747)); -const core_1 = __webpack_require__(393); -const path_1 = __webpack_require__(622); -const utils_1 = __webpack_require__(870); -/** - * Creates a specification that describes how each file that is part of the artifact will be uploaded - * @param artifactName the name of the artifact being uploaded. Used during upload to denote where the artifact is stored on the server - * @param rootDirectory an absolute file path that denotes the path that should be removed from the beginning of each artifact file - * @param artifactFiles a list of absolute file paths that denote what should be uploaded as part of the artifact - */ -function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { - utils_1.checkArtifactName(artifactName); - const specifications = []; - if (!fs.existsSync(rootDirectory)) { - throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); - } - if (!fs.lstatSync(rootDirectory).isDirectory()) { - throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); - } - // Normalize and resolve, this allows for either absolute or relative paths to be used - rootDirectory = path_1.normalize(rootDirectory); - rootDirectory = path_1.resolve(rootDirectory); - /* - Example to demonstrate behavior - - Input: - artifactName: my-artifact - rootDirectory: '/home/user/files/plz-upload' - artifactFiles: [ - '/home/user/files/plz-upload/file1.txt', - '/home/user/files/plz-upload/file2.txt', - '/home/user/files/plz-upload/dir/file3.txt' - ] - - Output: - specifications: [ - ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file1.txt'], - ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'], - ['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt'] - ] - */ - for (let file of artifactFiles) { - if (!fs.existsSync(file)) { - throw new Error(`File ${file} does not exist`); - } - if (!fs.lstatSync(file).isDirectory()) { - // Normalize and resolve, this allows for either absolute or relative paths to be used - file = path_1.normalize(file); - file = path_1.resolve(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); - } - // Check for forbidden characters in file paths that will be rejected during upload - const uploadPath = file.replace(rootDirectory, ''); - utils_1.checkArtifactFilePath(uploadPath); - /* - uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all - be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts - - path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt - join('artifact-name/', 'file-to-upload.txt') - join('artifact-name/', '/file-to-upload.txt') - join('artifact-name', 'file-to-upload.txt') - join('artifact-name', '/file-to-upload.txt') - */ - specifications.push({ - absoluteFilePath: file, - uploadFilePath: path_1.join(artifactName, uploadPath) - }); - } - else { - // Directories are rejected by the server during upload - core_1.debug(`Removing ${file} from rawSearchResults because it is a directory`); - } - } - return specifications; -} -exports.getUploadSpecification = getUploadSpecification; -//# sourceMappingURL=upload-specification.js.map - -/***/ }), -/* 591 */, -/* 592 */, -/* 593 */, -/* 594 */, -/* 595 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const mkdirs = __webpack_require__(727).mkdirs -const pathExists = __webpack_require__(322).pathExists -const utimesMillis = __webpack_require__(916).utimesMillis -const stat = __webpack_require__(127) - -function copy (src, dest, opts, cb) { - if (typeof opts === 'function' && !cb) { - cb = opts - opts = {} - } else if (typeof opts === 'function') { - opts = { filter: opts } - } - - cb = cb || function () {} - opts = opts || {} - - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) - } - - stat.checkPaths(src, dest, 'copy', (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'copy', err => { - if (err) return cb(err) - if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) - return checkParentDir(destStat, src, dest, opts, cb) - }) - }) -} - -function checkParentDir (destStat, src, dest, opts, cb) { - const destParent = path.dirname(dest) - pathExists(destParent, (err, dirExists) => { - if (err) return cb(err) - if (dirExists) return startCopy(destStat, src, dest, opts, cb) - mkdirs(destParent, err => { - if (err) return cb(err) - return startCopy(destStat, src, dest, opts, cb) - }) - }) -} - -function handleFilter (onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then(include => { - if (include) return onInclude(destStat, src, dest, opts, cb) - return cb() - }, error => cb(error)) -} - -function startCopy (destStat, src, dest, opts, cb) { - if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) - return getStats(destStat, src, dest, opts, cb) -} - -function getStats (destStat, src, dest, opts, cb) { - const stat = opts.dereference ? fs.stat : fs.lstat - stat(src, (err, srcStat) => { - if (err) return cb(err) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) - }) -} - -function onFile (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return copyFile(srcStat, src, dest, opts, cb) - return mayCopyFile(srcStat, src, dest, opts, cb) -} - -function mayCopyFile (srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs.unlink(dest, err => { - if (err) return cb(err) - return copyFile(srcStat, src, dest, opts, cb) - }) - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)) - } else return cb() -} - -function copyFile (srcStat, src, dest, opts, cb) { - fs.copyFile(src, dest, err => { - if (err) return cb(err) - if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) - return setDestMode(dest, srcStat.mode, cb) - }) -} - -function handleTimestampsAndMode (srcMode, src, dest, cb) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) { - return makeFileWritable(dest, srcMode, err => { - if (err) return cb(err) - return setDestTimestampsAndMode(srcMode, src, dest, cb) - }) - } - return setDestTimestampsAndMode(srcMode, src, dest, cb) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode, cb) { - return setDestMode(dest, srcMode | 0o200, cb) -} - -function setDestTimestampsAndMode (srcMode, src, dest, cb) { - setDestTimestamps(src, dest, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) -} - -function setDestMode (dest, srcMode, cb) { - return fs.chmod(dest, srcMode, cb) -} - -function setDestTimestamps (src, dest, cb) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - fs.stat(src, (err, updatedSrcStat) => { - if (err) return cb(err) - return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) - }) -} - -function onDir (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) - if (destStat && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) - } - return copyDir(src, dest, opts, cb) -} - -function mkDirAndCopy (srcMode, src, dest, opts, cb) { - fs.mkdir(dest, err => { - if (err) return cb(err) - copyDir(src, dest, opts, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) - }) -} - -function copyDir (src, dest, opts, cb) { - fs.readdir(src, (err, items) => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) -} - -function copyDirItems (items, src, dest, opts, cb) { - const item = items.pop() - if (!item) return cb() - return copyDirItem(items, item, src, dest, opts, cb) -} - -function copyDirItem (items, item, src, dest, opts, cb) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => { - if (err) return cb(err) - const { destStat } = stats - startCopy(destStat, srcItem, destItem, opts, err => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) - }) -} - -function onLink (destStat, src, dest, opts, cb) { - fs.readlink(src, (err, resolvedSrc) => { - if (err) return cb(err) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + get(requestUrl, additionalHeaders) { + return this.request('GET', requestUrl, null, additionalHeaders || {}); } - - if (!destStat) { - return fs.symlink(resolvedSrc, dest, cb) - } else { - fs.readlink(dest, (err, resolvedDest) => { - if (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) - return cb(err) - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) - } - - // do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) - } - return copyLink(resolvedSrc, dest, cb) - }) + del(requestUrl, additionalHeaders) { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } - }) -} - -function copyLink (resolvedSrc, dest, cb) { - fs.unlink(dest, err => { - if (err) return cb(err) - return fs.symlink(resolvedSrc, dest, cb) - }) -} - -module.exports = copy - - -/***/ }), -/* 596 */, -/* 597 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const pathHelper = __webpack_require__(972); -const internal_match_kind_1 = __webpack_require__(36); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Given an array of patterns, returns an array of paths to search. - * Duplicates and paths under other included paths are filtered out. - */ -function getSearchPaths(patterns) { - // Ignore negate patterns - patterns = patterns.filter(x => !x.negate); - // Create a map of all search paths - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - searchPathMap[key] = 'candidate'; + post(requestUrl, data, additionalHeaders) { + return this.request('POST', requestUrl, data, additionalHeaders || {}); } - const result = []; - for (const pattern of patterns) { - // Check if already included - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - if (searchPathMap[key] === 'included') { - continue; + patch(requestUrl, data, additionalHeaders) { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + } + put(requestUrl, data, additionalHeaders) { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + } + head(requestUrl, additionalHeaders) { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return this.request(verb, requestUrl, stream, additionalHeaders); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + async getJson(requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + let res = await this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async postJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async putJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async patchJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + async request(verb, requestUrl, data, headers) { + if (this._disposed) { + throw new Error('Client has already been disposed.'); } - // Check for an ancestor search path - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; - break; + let parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + while (numTries < maxTries) { + response = await this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (let i = 0; i < this.handlers.length; i++) { + if (this.handlers[i].canHandleAuthentication(response)) { + authenticationHandler = this.handlers[i]; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + let parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol == 'https:' && + parsedUrl.protocol != parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + await response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (let header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = await this.requestRaw(info, data); + redirectsRemaining--; + } + if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + await response.readBody(); + await this._performExponentialBackoff(numTries); } - tempKey = parent; - parent = pathHelper.dirname(tempKey); } - // Include the search pattern in the result - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = 'included'; + return response; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; -} -exports.getSearchPaths = getSearchPaths; -/** - * Matches the patterns against the path - */ -function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return new Promise((resolve, reject) => { + let callbackForResult = function (err, res) { + if (err) { + reject(err); + } + resolve(res); + }; + this.requestRawWithCallback(info, data, callbackForResult); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + let socket; + if (typeof data === 'string') { + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } - else { - result |= pattern.match(itemPath); + let callbackCalled = false; + let handleResult = (err, res) => { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + }; + let req = info.httpModule.request(info.options, (msg) => { + let res = new HttpClientResponse(msg); + handleResult(null, res); + }); + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error('Request timeout: ' + info.options.path), null); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err, null); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); } - } - return result; -} -exports.match = match; -/** - * Checks whether to descend further into the directory - */ -function partialMatch(patterns, itemPath) { - return patterns.some(x => !x.negate && x.partialMatch(itemPath)); -} -exports.partialMatch = partialMatch; -//# sourceMappingURL=internal-pattern-helper.js.map - -/***/ }), -/* 598 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var fs = __webpack_require__(747) -var polyfills = __webpack_require__(250) -var legacy = __webpack_require__(93) -var clone = __webpack_require__(608) - -var util = __webpack_require__(669) - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} - -function noop () {} - -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - retry() + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); } - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) - - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - retry() - } - - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) - - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __webpack_require__(357).equal(fs[gracefulQueue].length, 0) - }) - } -} - -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} - -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} - -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$readFile(path, options, cb) - - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + req.end(); } - }) } - } - - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$writeFile(path, data, options, cb) - - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + let parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$appendFile(path, data, options, cb) - - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; } - }) + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + this.handlers.forEach(handler => { + handler.prepareRequest(info.options); + }); + } + return info; } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options + _mergeHeaders(headers) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + } + return lowercaseKeys(headers || {}); } - args.push(go$readdir$cb) - - return go$readdir(args) - - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() - - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) - - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; } - } - - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } + _getAgent(parsedUrl) { + let agent; + let proxyUrl = pm.getProxyUrl(parsedUrl); + let useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (!!agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (!!this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (useProxy) { + // If using proxy, need tunnel + if (!tunnel) { + tunnel = __webpack_require__(856); + } + const agentOptions = { + maxSockets: maxSockets, + keepAlive: this._keepAlive, + proxy: { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`, + host: proxyUrl.hostname, + port: proxyUrl.port + } + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets: 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 + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _performExponentialBackoff(retryNumber) { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + } + static dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + let a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + async _processResponse(res, options) { + return new Promise(async (resolve, reject) => { + const statusCode = res.message.statusCode; + const response = { + statusCode: statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode == HttpCodes.NotFound) { + resolve(response); + } + let obj; + let contents; + // get the result from the body + try { + contents = await res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = 'Failed request: (' + statusCode + ')'; + } + let err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + }); + } +} +exports.HttpClient = HttpClient; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } +/***/ }), +/* 540 */, +/* 541 */, +/* 542 */, +/* 543 */, +/* 544 */, +/* 545 */, +/* 546 */, +/* 547 */, +/* 548 */, +/* 549 */, +/* 550 */, +/* 551 */, +/* 552 */ +/***/ (function(__unusedmodule, exports) { - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) + } + return sprintf.format.call(null, cache[key], arguments) + } - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() - - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + if (get_type(arg) == "function") { + arg = arg() + } - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } + } + return output.join("") + } - return go$open(path, flags, mode, cb) + sprintf.cache = {} - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) } - }) + return parse_tree } - } - return fs -} + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) + } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) -} + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + } -function retry () { - var elem = fs[gracefulQueue].shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } -} + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (true) { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else {} +})(typeof window === "undefined" ? this : window); /***/ }), -/* 599 */, -/* 600 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 553 */, +/* 554 */, +/* 555 */, +/* 556 */ +/***/ (function(module) { "use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// -module.exports.ArgumentParser = __webpack_require__(452); -module.exports.Namespace = __webpack_require__(515); -module.exports.Action = __webpack_require__(380); -module.exports.HelpFormatter = __webpack_require__(532); -module.exports.Const = __webpack_require__(45); +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); -module.exports.ArgumentDefaultsHelpFormatter = - __webpack_require__(59).ArgumentDefaultsHelpFormatter; -module.exports.RawDescriptionHelpFormatter = - __webpack_require__(59).RawDescriptionHelpFormatter; -module.exports.RawTextHelpFormatter = - __webpack_require__(59).RawTextHelpFormatter; + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} -/***/ }), -/* 601 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { -"use strict"; +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __webpack_require__(393); -/** - * Returns a copy with defaults filled in. - */ -function getOptions(copy) { - const result = { - followSymbolicLinks: true, - implicitDescendants: true, - omitBrokenSymbolicLinks: true - }; - if (copy) { - if (typeof copy.followSymbolicLinks === 'boolean') { - result.followSymbolicLinks = copy.followSymbolicLinks; - core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); - } - if (typeof copy.implicitDescendants === 'boolean') { - result.implicitDescendants = copy.implicitDescendants; - core.debug(`implicitDescendants '${result.implicitDescendants}'`); - } - if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { - result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); - } - } - return result; -} -exports.getOptions = getOptions; -//# sourceMappingURL=internal-glob-options-helper.js.map - -/***/ }), -/* 602 */, -/* 603 */, -/* 604 */, -/* 605 */ -/***/ (function(module) { - -module.exports = require("http"); - -/***/ }), -/* 606 */, -/* 607 */, -/* 608 */ -/***/ (function(module) { - -"use strict"; +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; -module.exports = clone + result += this.reason || '(unknown reason)'; -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) + return result; +}; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - return copy -} +module.exports = YAMLException; /***/ }), -/* 609 */, -/* 610 */, -/* 611 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 557 */, +/* 558 */, +/* 559 */, +/* 560 */, +/* 561 */, +/* 562 */ +/***/ (function(__unusedmodule, exports) { "use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - +Object.defineProperty(exports, '__esModule', { value: true }); +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } -var Schema = __webpack_require__(733); + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; +} -module.exports = new Schema({ - include: [ - __webpack_require__(23) - ] -}); +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map /***/ }), -/* 612 */, -/* 613 */, -/* 614 */ +/* 563 */, +/* 564 */, +/* 565 */, +/* 566 */, +/* 567 */, +/* 568 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -/** internal - * class ActionContainer - * - * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] - **/ +const path = __webpack_require__(622); +const niceTry = __webpack_require__(948); +const resolveCommand = __webpack_require__(489); +const escape = __webpack_require__(462); +const readShebang = __webpack_require__(389); +const semver = __webpack_require__(280); -var format = __webpack_require__(669).format; - -// Constants -var c = __webpack_require__(45); +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; -var $$ = __webpack_require__(255); +// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0 +const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false; -//Actions -var ActionHelp = __webpack_require__(834); -var ActionAppend = __webpack_require__(378); -var ActionAppendConstant = __webpack_require__(288); -var ActionCount = __webpack_require__(927); -var ActionStore = __webpack_require__(352); -var ActionStoreConstant = __webpack_require__(267); -var ActionStoreTrue = __webpack_require__(211); -var ActionStoreFalse = __webpack_require__(963); -var ActionVersion = __webpack_require__(987); -var ActionSubparsers = __webpack_require__(983); +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); -// Errors -var argumentErrorHelper = __webpack_require__(287); + const shebang = parsed.file && readShebang(parsed.file); -/** - * new ActionContainer(options) - * - * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] - * - * ##### Options: - * - * - `description` -- A description of what the program does - * - `prefixChars` -- Characters that prefix optional arguments - * - `argumentDefault` -- The default value for all arguments - * - `conflictHandler` -- The conflict handler to use for duplicate arguments - **/ -var ActionContainer = module.exports = function ActionContainer(options) { - options = options || {}; + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; - this.description = options.description; - this.argumentDefault = options.argumentDefault; - this.prefixChars = options.prefixChars || ''; - this.conflictHandler = options.conflictHandler; + return resolveCommand(parsed); + } - // set up registries - this._registries = {}; + return parsed.file; +} - // register actions - this.register('action', null, ActionStore); - this.register('action', 'store', ActionStore); - this.register('action', 'storeConst', ActionStoreConstant); - this.register('action', 'storeTrue', ActionStoreTrue); - this.register('action', 'storeFalse', ActionStoreFalse); - this.register('action', 'append', ActionAppend); - this.register('action', 'appendConst', ActionAppendConstant); - this.register('action', 'count', ActionCount); - this.register('action', 'help', ActionHelp); - this.register('action', 'version', ActionVersion); - this.register('action', 'parsers', ActionSubparsers); +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } - // raise an exception if the conflict handler is invalid - this._getHandler(); + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); - // action storage - this._actions = []; - this._optionStringActions = {}; + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); - // groups - this._actionGroups = []; - this._mutuallyExclusiveGroups = []; + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - // defaults storage - this._defaults = {}; + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); - // determines whether an "option" looks like a negative number - // -1, -1.5 -5e+4 - this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); - // whether or not there are any optionals that look like negative - // numbers -- uses a list so it can be shared and edited - this._hasNegativeNumberOptionals = []; -}; + const shellCommand = [parsed.command].concat(parsed.args).join(' '); -// Groups must be required, then ActionContainer already defined -var ArgumentGroup = __webpack_require__(65); -var MutuallyExclusiveGroup = __webpack_require__(282); + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } -// -// Registration methods -// + return parsed; +} -/** - * ActionContainer#register(registryName, value, object) -> Void - * - registryName (String) : object type action|type - * - value (string) : keyword - * - object (Object|Function) : handler - * - * Register handlers - **/ -ActionContainer.prototype.register = function (registryName, value, object) { - this._registries[registryName] = this._registries[registryName] || {}; - this._registries[registryName][value] = object; -}; +function parseShell(parsed) { + // If node supports the shell option, there's no need to mimic its behavior + if (supportsShellOption) { + return parsed; + } -ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { - if (arguments.length < 3) { - defaultValue = null; - } - return this._registries[registryName][value] || defaultValue; -}; + // Mimic node shell option + // See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 + const shellCommand = [parsed.command].concat(parsed.args).join(' '); -// -// Namespace default accessor methods -// + if (isWin) { + parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } else { + if (typeof parsed.options.shell === 'string') { + parsed.command = parsed.options.shell; + } else if (process.platform === 'android') { + parsed.command = '/system/bin/sh'; + } else { + parsed.command = '/bin/sh'; + } -/** - * ActionContainer#setDefaults(options) -> Void - * - options (object):hash of options see [[Action.new]] - * - * Set defaults - **/ -ActionContainer.prototype.setDefaults = function (options) { - options = options || {}; - for (var property in options) { - if ($$.has(options, property)) { - this._defaults[property] = options[property]; + parsed.args = ['-c', shellCommand]; } - } - // if these defaults match any existing arguments, replace the previous - // default on the object with the new one - this._actions.forEach(function (action) { - if ($$.has(options, action.dest)) { - action.defaultValue = options[action.dest]; + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; } - }); -}; -/** - * ActionContainer#getDefault(dest) -> Mixed - * - dest (string): action destination - * - * Return action default value - **/ -ActionContainer.prototype.getDefault = function (dest) { - var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null; + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original - this._actions.forEach(function (action) { - if (action.dest === dest && $$.has(action, 'defaultValue')) { - result = action.defaultValue; - } - }); + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; - return result; -}; -// -// Adding argument actions -// + // Delegate further parsing to shell or non-shell + return options.shell ? parseShell(parsed) : parseNonShell(parsed); +} -/** - * ActionContainer#addArgument(args, options) -> Object - * - args (String|Array): argument key, or array of argument keys - * - options (Object): action objects see [[Action.new]] - * - * #### Examples - * - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... }) - * - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... }) - * - addArgument('--baz', { action: 'store', nargs: 1, ... }) - **/ -ActionContainer.prototype.addArgument = function (args, options) { - args = args; - options = options || {}; +module.exports = parse; - if (typeof args === 'string') { - args = [ args ]; - } - if (!Array.isArray(args)) { - throw new TypeError('addArgument first argument should be a string or an array'); - } - if (typeof options !== 'object' || Array.isArray(options)) { - throw new TypeError('addArgument second argument should be a hash'); - } - // if no positional args are supplied or only one is supplied and - // it doesn't look like an option string, parse a positional argument - if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { - if (args && !!options.dest) { - throw new Error('dest supplied twice for positional argument'); - } - options = this._getPositional(args, options); +/***/ }), +/* 569 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // otherwise, we're adding an optional argument - } else { - options = this._getOptional(args, options); - } +module.exports = rimraf +rimraf.sync = rimrafSync - // if no default was supplied, use the parser-level default - if (typeof options.defaultValue === 'undefined') { - var dest = options.dest; - if ($$.has(this._defaults, dest)) { - options.defaultValue = this._defaults[dest]; - } else if (typeof this.argumentDefault !== 'undefined') { - options.defaultValue = this.argumentDefault; - } - } +var assert = __webpack_require__(357) +var path = __webpack_require__(622) +var fs = __webpack_require__(747) +var glob = undefined +try { + glob = __webpack_require__(120) +} catch (_err) { + // treat glob as optional. +} +var _0666 = parseInt('666', 8) - // create the action object, and add it to the parser - var ActionClass = this._popActionClass(options); - if (typeof ActionClass !== 'function') { - throw new Error(format('Unknown action "%s".', ActionClass)); - } - var action = new ActionClass(options); +var defaultGlobOpts = { + nosort: true, + silent: true +} - // throw an error if the action type is not callable - var typeFunction = this._registryGet('type', action.type, action.type); - if (typeof typeFunction !== 'function') { - throw new Error(format('"%s" is not callable', typeFunction)); - } +// for EMFILE handling +var timeout = 0 - return this._addAction(action); -}; +var isWindows = (process.platform === "win32") -/** - * ActionContainer#addArgumentGroup(options) -> ArgumentGroup - * - options (Object): hash of options see [[ArgumentGroup.new]] - * - * Create new arguments groups - **/ -ActionContainer.prototype.addArgumentGroup = function (options) { - var group = new ArgumentGroup(this, options); - this._actionGroups.push(group); - return group; -}; +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) -/** - * ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup - * - options (Object): {required: false} - * - * Create new mutual exclusive groups - **/ -ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { - var group = new MutuallyExclusiveGroup(this, options); - this._mutuallyExclusiveGroups.push(group); - return group; -}; + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + if (options.disableGlob !== true && glob === undefined) { + throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts +} -ActionContainer.prototype._addAction = function (action) { - var self = this; +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } - // resolve any conflicts - this._checkConflict(action); + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') - // add to actions list - this._actions.push(action); - action.container = this; + defaults(options) - // index the action by any option strings it has - action.optionStrings.forEach(function (optionString) { - self._optionStringActions[optionString] = action; - }); + var busyTries = 0 + var errState = null + var n = 0 - // set the flag if any option strings look like negative numbers - action.optionStrings.forEach(function (optionString) { - if (optionString.match(self._regexpNegativeNumber)) { - if (!self._hasNegativeNumberOptionals.some(Boolean)) { - self._hasNegativeNumberOptionals.push(true); - } - } - }); + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) - // return the created action - return action; -}; + options.lstat(p, function (er, stat) { + if (!er) + return afterGlob(null, [p]) -ActionContainer.prototype._removeAction = function (action) { - var actionIndex = this._actions.indexOf(action); - if (actionIndex >= 0) { - this._actions.splice(actionIndex, 1); + glob(p, options.glob, afterGlob) + }) + + function next (er) { + errState = errState || er + if (--n === 0) + cb(errState) } -}; -ActionContainer.prototype._addContainerActions = function (container) { - // collect groups by titles - var titleGroupMap = {}; - this._actionGroups.forEach(function (group) { - if (titleGroupMap[group.title]) { - throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); - } - titleGroupMap[group.title] = group; - }); + function afterGlob (er, results) { + if (er) + return cb(er) - // map each action to its group - var groupMap = {}; - function actionHash(action) { - // unique (hopefully?) string suitable as dictionary key - return action.getName(); - } - container._actionGroups.forEach(function (group) { - // if a group with the title exists, use that, otherwise - // create a new group matching the container's group - if (!titleGroupMap[group.title]) { - titleGroupMap[group.title] = this.addArgumentGroup({ - title: group.title, - description: group.description - }); - } + n = results.length + if (n === 0) + return cb() - // map the actions to their new group - group._groupActions.forEach(function (action) { - groupMap[actionHash(action)] = titleGroupMap[group.title]; - }); - }, this); + results.forEach(function (p) { + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } - // add container's mutually exclusive groups - // NOTE: if add_mutually_exclusive_group ever gains title= and - // description= then this code will need to be expanded as above - var mutexGroup; - container._mutuallyExclusiveGroups.forEach(function (group) { - mutexGroup = this.addMutuallyExclusiveGroup({ - required: group.required - }); - // map the actions to their new mutex group - group._groupActions.forEach(function (action) { - groupMap[actionHash(action)] = mutexGroup; - }); - }, this); // forEach takes a 'this' argument + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } - // add all actions to this container or their group - container._actions.forEach(function (action) { - var key = actionHash(action); - if (groupMap[key]) { - groupMap[key]._addAction(action); - } else { - this._addAction(action); - } - }); -}; + // already gone + if (er.code === "ENOENT") er = null + } -ActionContainer.prototype._getPositional = function (dest, options) { - if (Array.isArray(dest)) { - dest = dest[0]; - } - // make sure required is not specified - if (options.required) { - throw new Error('"required" is an invalid argument for positionals.'); + timeout = 0 + next(er) + }) + }) } +} - // mark positional arguments as required if at least one is - // always required - if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) { - options.required = true; - } - if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') { - options.required = true; - } +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') - // return the keyword arguments with no option strings - options.dest = dest; - options.optionStrings = []; - return options; -}; + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, function (er, st) { + if (er && er.code === "ENOENT") + return cb(null) -ActionContainer.prototype._getOptional = function (args, options) { - var prefixChars = this.prefixChars; - var optionStrings = []; - var optionStringsLong = []; + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) - // determine short and long option strings - args.forEach(function (optionString) { - // error on strings that don't start with an appropriate prefix - if (prefixChars.indexOf(optionString[0]) < 0) { - throw new Error(format('Invalid option string "%s": must start with a "%s".', - optionString, - prefixChars - )); - } + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) - // strings starting with two prefix characters are long options - optionStrings.push(optionString); - if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { - optionStringsLong.push(optionString); - } - }); + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} - // infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' - var dest = options.dest || null; - delete options.dest; +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) - if (!dest) { - var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; - dest = $$.trimChars(optionStringDest, this.prefixChars); + options.chmod(p, _0666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} - if (dest.length === 0) { - throw new Error( - format('dest= is required for options like "%s"', optionStrings.join(', ')) - ); - } - dest = dest.replace(/-/g, '_'); +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) + + try { + options.chmodSync(p, _0666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er } - // return the updated keyword arguments - options.dest = dest; - options.optionStrings = optionStrings; + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } - return options; -}; + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} -ActionContainer.prototype._popActionClass = function (options, defaultValue) { - defaultValue = defaultValue || null; +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') - var action = (options.action || defaultValue); - delete options.action; + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} - var actionClass = this._registryGet('action', action, action); - return actionClass; -}; +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') -ActionContainer.prototype._getHandler = function () { - var handlerString = this.conflictHandler; - var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString); - var func = this[handlerFuncName]; - if (typeof func === 'undefined') { - var msg = 'invalid conflict resolution value: ' + handlerString; - throw new Error(msg); - } else { - return func; - } -}; - -ActionContainer.prototype._checkConflict = function (action) { - var optionStringActions = this._optionStringActions; - var conflictOptionals = []; + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} - // find all options that conflict with this option - // collect pairs, the string, and an existing action that it conflicts with - action.optionStrings.forEach(function (optionString) { - var conflOptional = optionStringActions[optionString]; - if (typeof conflOptional !== 'undefined') { - conflictOptionals.push([ optionString, conflOptional ]); - } - }); +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) - if (conflictOptionals.length > 0) { - var conflictHandler = this._getHandler(); - conflictHandler.call(this, action, conflictOptionals); - } -}; + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') -ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { - var conflicts = conflOptionals.map(function (pair) { return pair[0]; }); - conflicts = conflicts.join(', '); - throw argumentErrorHelper( - action, - format('Conflicting option string(s): %s', conflicts) - ); -}; + var results -ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { - // remove all conflicting options - var self = this; - conflOptionals.forEach(function (pair) { - var optionString = pair[0]; - var conflictingAction = pair[1]; - // remove the conflicting option string - var i = conflictingAction.optionStrings.indexOf(optionString); - if (i >= 0) { - conflictingAction.optionStrings.splice(i, 1); - } - delete self._optionStringActions[optionString]; - // if the option now has no option string, remove it from the - // container holding it - if (conflictingAction.optionStrings.length === 0) { - conflictingAction.container._removeAction(conflictingAction); + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) } - }); -}; - - -/***/ }), -/* 615 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; + } + if (!results.length) + return -const u = __webpack_require__(676).fromCallback -const fs = __webpack_require__(598) -const path = __webpack_require__(622) -const mkdir = __webpack_require__(727) -const remove = __webpack_require__(723) + for (var i = 0; i < results.length; i++) { + var p = results[i] -const emptyDir = u(function emptyDir (dir, callback) { - callback = callback || function () {} - fs.readdir(dir, (err, items) => { - if (err) return mkdir.mkdirs(dir, callback) + try { + var st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return - items = items.map(item => path.join(dir, item)) + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } - deleteItem() + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er - function deleteItem () { - const item = items.pop() - if (!item) return callback() - remove.remove(item, err => { - if (err) return callback(err) - deleteItem() - }) + rmdirSync(p, options, er) } - }) -}) + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) -function emptyDirSync (dir) { - let items try { - items = fs.readdirSync(dir) - } catch { - return mkdir.mkdirsSync(dir) + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) } +} - items.forEach(item => { - item = path.join(dir, item) - remove.removeSync(item) +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) }) -} -module.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + var retries = isWindows ? 100 : 1 + var i = 0 + do { + var threw = true + try { + var ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) } /***/ }), -/* 616 */, -/* 617 */, -/* 618 */, -/* 619 */ -/***/ (function(module) { - -module.exports = require("constants"); - -/***/ }), -/* 620 */, -/* 621 */ +/* 570 */, +/* 571 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +module.exports = minimatch +minimatch.Minimatch = Minimatch -const path = __webpack_require__(622); -const pathKey = __webpack_require__(39); +var path = { sep: '/' } +try { + path = __webpack_require__(622) +} catch (er) {} -module.exports = opts => { - opts = Object.assign({ - cwd: process.cwd(), - path: process.env[pathKey()] - }, opts); +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __webpack_require__(306) - let prev; - let pth = path.resolve(opts.cwd); - const ret = []; +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - while (prev !== pth) { - ret.push(path.join(pth, 'node_modules/.bin')); - prev = pth; - pth = path.resolve(pth, '..'); - } +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - // ensure the running `node` binary is used - ret.push(path.dirname(process.execPath)); +// * => any number of characters +var star = qmark + '*?' - return ret.concat(opts.path).join(path.delimiter); -}; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' -module.exports.env = opts => { - opts = Object.assign({ - env: process.env - }, opts); +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - const env = Object.assign({}, opts.env); - const path = pathKey({env}); +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - opts.path = env[path]; - env[path] = module.exports(opts); +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} - return env; -}; +// normalizes slashes. +var slashSplit = /\/+/ +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} -/***/ }), -/* 622 */ -/***/ (function(module) { +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} -module.exports = require("path"); +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch -/***/ }), -/* 623 */, -/* 624 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + var orig = minimatch -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = __webpack_require__(870); -/** - * Used for managing http clients during either upload or download - */ -class HttpManager { - constructor(clientCount, userAgent) { - if (clientCount < 1) { - throw new Error('There must be at least one client'); - } - this.userAgent = userAgent; - this.clients = new Array(clientCount).fill(utils_1.createHttpClient(userAgent)); - } - getClient(index) { - return this.clients[index]; - } - // client disposal is necessary if a keep-alive connection is used to properly close the connection - // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 - disposeAndReplaceClient(index) { - this.clients[index].dispose(); - this.clients[index] = utils_1.createHttpClient(this.userAgent); - } - disposeAndReplaceAllClients() { - for (const [index] of this.clients.entries()) { - this.disposeAndReplaceClient(index); - } - } -} -exports.HttpManager = HttpManager; -//# sourceMappingURL=http-manager.js.map + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } -/***/ }), -/* 625 */, -/* 626 */ -/***/ (function(module) { + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } -"use strict"; + return m +} +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} -/*! - * isobject - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } -function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false; -} + if (!options) options = {} -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } -function isObjectObject(o) { - return isObject(o) === true - && Object.prototype.toString.call(o) === '[object Object]'; -} + // "" only matches "" + if (pattern.trim() === '') return p === '' -function isPlainObject(o) { - var ctor,prot; + return new Minimatch(pattern, options).match(p) +} - if (isObjectObject(o) === false) return false; +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; + if (!options) options = {} + pattern = pattern.trim() - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') } - // Most likely a plain Object - return true; + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() } -module.exports = isPlainObject; +Minimatch.prototype.debug = function () {} +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return -/***/ }), -/* 627 */, -/* 628 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var pattern = this.pattern + var options = this.options -"use strict"; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + // step 1: figure out negation, etc. + this.parseNegate() -const { stringify } = __webpack_require__(356) -const { outputFileSync } = __webpack_require__(517) + // step 2: expand braces + var set = this.globSet = this.braceExpand() -function outputJsonSync (file, data, options) { - const str = stringify(data, options) + if (options.debug) this.debug = console.error - outputFileSync(file, str, options) -} + this.debug(this.pattern, set) -module.exports = outputJsonSync + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + this.debug(this.pattern, set) -/***/ }), -/* 629 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) -"use strict"; + this.debug(this.pattern, set) + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) -var Type = __webpack_require__(945); + this.debug(this.pattern, set) -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; + this.set = set +} - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; + if (options.nonegate) return - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ } - return true; + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate } -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } } - return new RegExp(regexp, modifiers); -} + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } - return result; + return expand(pattern) } -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); + var options = this.options + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' -/***/ }), -/* 630 */ -/***/ (function(module) { + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this -module.exports = require("perf_hooks"); + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } -/***/ }), -/* 631 */ -/***/ (function(module) { + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) -module.exports = require("net"); + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } -/***/ }), -/* 632 */, -/* 633 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false -"use strict"; + case '\\': + clearStateChar() + escaping = true + continue + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -var Type = __webpack_require__(945); + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); + case '(': + if (inClass) { + re += '(' + continue + } + if (!stateChar) { + re += '\\(' + continue + } -/***/ }), -/* 634 */, -/* 635 */, -/* 636 */, -/* 637 */, -/* 638 */, -/* 639 */, -/* 640 */, -/* 641 */, -/* 642 */, -/* 643 */, -/* 644 */, -/* 645 */, -/* 646 */, -/* 647 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __importStar(__webpack_require__(747)); -const zlib = __importStar(__webpack_require__(761)); -const util_1 = __webpack_require__(669); -const stat = util_1.promisify(fs.stat); -/** - * Creates a Gzip compressed file of an original file at the provided temporary filepath location - * @param {string} originalFilePath filepath of whatever will be compressed. The original file will be unmodified - * @param {string} tempFilePath the location of where the Gzip file will be created - * @returns the size of gzip file that gets created - */ -function createGZipFileOnDisk(originalFilePath, tempFilePath) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const inputStream = fs.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - const outputStream = fs.createWriteStream(tempFilePath); - inputStream.pipe(gzip).pipe(outputStream); - outputStream.on('finish', () => __awaiter(this, void 0, void 0, function* () { - // wait for stream to finish before calculating the size which is needed as part of the Content-Length header when starting an upload - const size = (yield stat(tempFilePath)).size; - resolve(size); - })); - outputStream.on('error', error => { - // eslint-disable-next-line no-console - console.log(error); - reject; - }); - }); - }); -} -exports.createGZipFileOnDisk = createGZipFileOnDisk; -/** - * Creates a GZip file in memory using a buffer. Should be used for smaller files to reduce disk I/O - * @param originalFilePath the path to the original file that is being GZipped - * @returns a buffer with the GZip file - */ -function createGZipFileInBuffer(originalFilePath) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - var e_1, _a; - const inputStream = fs.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - inputStream.pipe(gzip); - // read stream into buffer, using experimental async iterators see https://github.com/nodejs/readable-stream/issues/403#issuecomment-479069043 - const chunks = []; - try { - for (var gzip_1 = __asyncValues(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), !gzip_1_1.done;) { - const chunk = gzip_1_1.value; - chunks.push(chunk); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (gzip_1_1 && !gzip_1_1.done && (_a = gzip_1.return)) yield _a.call(gzip_1); - } - finally { if (e_1) throw e_1.error; } - } - resolve(Buffer.concat(chunks)); - })); - }); -} -exports.createGZipFileInBuffer = createGZipFileInBuffer; -//# sourceMappingURL=upload-gzip.js.map + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -/***/ }), -/* 648 */, -/* 649 */, -/* 650 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue -const buildChainFlow = __webpack_require__(653); + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -async function executeGitHubAction(context) { - await buildChainFlow.start(context); -} + clearStateChar() + re += '|' + continue -module.exports = { executeGitHubAction }; + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + if (inClass) { + re += '\\' + c + continue + } -/***/ }), -/* 651 */, -/* 652 */, -/* 653 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + inClass = true + classStart = i + reClassStart = re.length + re += c + continue -const { checkoutProject, getDir } = __webpack_require__(57); -const { printCheckoutInformation } = __webpack_require__(656); -const { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation -} = __webpack_require__(165); -const { logger } = __webpack_require__(79); -const { execute } = __webpack_require__(703); -const { treatCommand } = __webpack_require__(52); -const core = __webpack_require__(393); -const uploadArtifacts = __webpack_require__(395); -const { getCheckoutInfo } = __webpack_require__(195); + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } -async function start(context) { - core.startGroup( - `Checkout ${context.config.github.group}/${context.config.github.project}.` - ); - const projectFolder = getDir( - context.config.rootFolder, - context.config.github.project - ); - await checkoutProject( - context, - context.config.github.project, - { - group: context.config.github.group - }, - context.config.github.targetBranch - ); - const workflowInformation = readWorkflowInformation( - context.config.github.project, - context.config.github.jobId, - `.github/workflows/${context.config.github.flowFile}`, - context.config.github.group, - context.config.matrixVariables, - projectFolder - ); - core.endGroup(); + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } - const parentWorkflowInformationArray = ( - await checkoutParentsAndGetWorkflowInformation( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ) - ).reverse(); + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - core.startGroup(`Checkout Summary...`); - printCheckoutInformation(getCheckoutInfo(context)); - core.endGroup(); + default: + // swallow any state char that wasn't consumed + clearStateChar() - const executionResult = await executeBuildCommandsWorkflowInformation( - context.config.rootFolder, - workflowInformation, - parentWorkflowInformationArray - ) - .then(() => true) - .catch(e => e); + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } - core.startGroup(`Archiving artifacts...`); - await archiveArtifacts( - workflowInformation, - parentWorkflowInformationArray.concat(workflowInformation), - executionResult === true ? ["success", "always"] : ["failure", "always"] - ); - core.endGroup(); - if (executionResult !== true) { - logger.error(executionResult); - throw new Error( - "Command executions have failed, please review latest execution" - ); - } -} + re += c -async function executeBuildCommandsWorkflowInformation( - rootFolder, - workflowInformation, - parentWorkflowInformationArray -) { - for await (const wi of parentWorkflowInformationArray) { - await executeBuildCommands( - getDir(rootFolder, wi.project), - wi["buildCommandsUpstream"] || wi["buildCommands"], - wi.project - ); - } - await executeBuildCommands( - getDir(rootFolder, workflowInformation.project), - workflowInformation["buildCommands"], - workflowInformation.project - ); -} + } // switch + } // for -async function archiveArtifacts( - workflowInformationTriggering, - workflowInformationArray, - on -) { - const archiveDependencies = - workflowInformationTriggering.archiveArtifacts.dependencies; - logger.info( - `${archiveDependencies} parent artifact(s) will be treated to be uploaded. Events ${on}` - ); - const wiArrayWithArtifacts = - archiveDependencies === "none" - ? [workflowInformationTriggering].filter(wi => wi.archiveArtifacts.paths) - : workflowInformationArray.filter( - wi => - wi.archiveArtifacts.paths && - (archiveDependencies === "all" || - archiveDependencies.includes(wi.project) || - wi.project === workflowInformationTriggering.project) - ); - logger.info( - wiArrayWithArtifacts.length > 0 - ? `Archiving artifacts for ${wiArrayWithArtifacts.map(wi => wi.project)}` - : "No artifacts to archive" - ); + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } - await Promise.allSettled( - wiArrayWithArtifacts.map(async wi => { - logger.info(`Project [${wi.project}]. Uploading artifacts...`); - const uploadResponse = await uploadArtifacts.run(wi.archiveArtifacts, on); - if (uploadResponse) { - const uploadArtifactsMessage = - uploadResponse.artifactItems && - uploadResponse.artifactItems.length > 0 - ? `Uploaded Items (${uploadResponse.artifactItems.length}): ${uploadResponse.artifactItems}.` - : ""; - if ( - uploadResponse.failedItems && - uploadResponse.failedItems.length > 0 - ) { - logger.error( - `Project [${wi.project}] Failed State. Artifact [${uploadResponse.artifactName}]. Failed Items (${uploadResponse.failedItems.length}): ${uploadResponse.failedItems}. ${uploadArtifactsMessage}` - ); - return Promise.reject(uploadResponse); - } else { - logger.info( - `Project [${wi.project}]. Artifact [${uploadResponse.artifactName}]. ${uploadArtifactsMessage}` - ); - return Promise.resolve(uploadResponse); - } - } else { - logger.info(`Project [${wi.project}]. No artifacts uploaded`); - return Promise.resolve(undefined); + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' }) - ).then(promises => { - logger.info("-------------- ARCHIVE ARTIFACTS SUMMARY --------------"); - const totalUploadResponses = promises - .map(promiseResult => promiseResult.value || promiseResult.reason) - .filter( - uploadResponse => - uploadResponse && - uploadResponse.artifactItems && - uploadResponse.artifactItems.length > 0 - ); - const uploadedFiles = totalUploadResponses.flatMap( - uploadResponse => uploadResponse.artifactItems - ); - const failureUploadResponses = promises - .filter(promiseResult => promiseResult.reason) - .map(promiseResult => promiseResult.reason) - .filter( - uploadResponse => - uploadResponse && - uploadResponse.failedItems && - uploadResponse.failedItems.length > 0 - ); - const failedFiles = failureUploadResponses.flatMap( - uploadResponse => uploadResponse.failedItems - ); - logger.info( - `Artifacts uploaded (${ - totalUploadResponses.length - }): ${totalUploadResponses.map( - uploadResponse => uploadResponse.artifactName - )}. Files (${uploadedFiles.length}): ${uploadedFiles}` - ); - logger.info( - `Artifacts failed (${ - failureUploadResponses.length - }): ${failureUploadResponses.map( - uploadResponse => uploadResponse.artifactName - )}. Files (${failedFiles.length}): ${failedFiles}` - ); - }); -} -async function executeBuildCommands(cwd, buildCommands, project) { - for (const command of buildCommands) { - await execute(cwd, treatCommand(command), project); - } -} + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -module.exports = { - start -}; + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -/***/ }), -/* 654 */ -/***/ (function(module) { + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } -// This is not the set of all possible signals. -// -// It IS, however, the set of all signals that trigger -// an exit on either Linux or BSD systems. Linux is a -// superset of the signal names supported on BSD, and -// the unknown signals just fail to register, so we can -// catch that easily enough. -// -// Don't bother with SIGKILL. It's uncatchable, which -// means that we can't fire any callbacks anyway. -// -// If a user does happen to register a handler on a non- -// fatal signal like SIGWINCH or something, and then -// exit, it'll end up firing `process.emit('exit')`, so -// the handler will be fired anyway. -// -// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised -// artificially, inherently leave the process in a -// state from which it is not safe to try and enter JS -// listeners. -module.exports = [ - 'SIGABRT', - 'SIGALRM', - 'SIGHUP', - 'SIGINT', - 'SIGTERM' -] + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] -if (process.platform !== 'win32') { - module.exports.push( - 'SIGVTALRM', - 'SIGXCPU', - 'SIGXFSZ', - 'SIGUSR2', - 'SIGTRAP', - 'SIGSYS', - 'SIGQUIT', - 'SIGIOT' - // should detect profiler and enable/disable accordingly. - // see #21 - // 'SIGPROF' - ) -} + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) -if (process.platform === 'linux') { - module.exports.push( - 'SIGIO', - 'SIGPOLL', - 'SIGPWR', - 'SIGSTKFLT', - 'SIGUNUSED' - ) -} + nlLast += nlAfter + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter -/***/ }), -/* 655 */, -/* 656 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } -const { logger } = __webpack_require__(79); + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } -const groupBy = (checkoutInfo, key) => { - return Object.values(checkoutInfo).reduce((acc, checkInfo) => { - (acc[checkInfo[key]] = acc[checkInfo[key]] || []).push(checkInfo); - return acc; - }, {}); -}; + if (addPatternStart) { + re = patternStart + re + } -function printCheckoutInformation(checkoutInfo) { - if (checkoutInfo && Object.keys(checkoutInfo).length) { - logger.info("----------------------------------------------"); - Object.values(checkoutInfo).forEach(checkInfo => - logger.info( - `${checkInfo.group}/${checkInfo.project}:${checkInfo.branch}.${ - checkInfo.merge - ? ` It has Been merged with ${checkInfo.targetGroup}/${checkInfo.project}:${checkInfo.targetBranch}` - : "" - }` - ) - ); - logger.info("----------------------------------------------"); - Object.entries(groupBy(checkoutInfo, "branch")).forEach( - ([branch, checkoutInfoList]) => { - logger.info( - `Projects taken from branch "${branch}":${checkoutInfoList.map( - checkInfo => ` - ${checkInfo.group}/${checkInfo.project}${ - checkInfo.merge - ? `. Merged with ${checkInfo.targetGroup}/${checkInfo.project}:${checkInfo.targetBranch}` - : "" - }` - )}` - ); - } - ); - logger.info("----------------------------------------------"); + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] } -} -module.exports = { - printCheckoutInformation -}; + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } -/***/ }), -/* 657 */, -/* 658 */, -/* 659 */, -/* 660 */, -/* 661 */, -/* 662 */, -/* 663 */, -/* 664 */, -/* 665 */, -/* 666 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + regExp._glob = pattern + regExp._src = re -let _fs -try { - _fs = __webpack_require__(598) -} catch (_) { - _fs = __webpack_require__(747) + return regExp } -const universalify = __webpack_require__(676) -const { stringify, stripBom } = __webpack_require__(356) - -async function _readFile (file, options = {}) { - if (typeof options === 'string') { - options = { encoding: options } - } - const fs = options.fs || _fs +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} - const shouldThrow = 'throws' in options ? options.throws : true +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - let data = await universalify.fromCallback(fs.readFile)(file, options) + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set - data = stripBom(data) + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' - let obj try { - obj = JSON.parse(data, options ? options.reviver : null) - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}` - throw err - } else { - return null - } + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false } + return this.regexp +} - return obj +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list } -const readFile = universalify.fromPromise(_readFile) +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -function readFileSync (file, options = {}) { - if (typeof options === 'string') { - options = { encoding: options } + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') } - const fs = options.fs || _fs + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - const shouldThrow = 'throws' in options ? options.throws : true + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - try { - let content = fs.readFileSync(file, options) - content = stripBom(content) - return JSON.parse(content, options.reviver) - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}` - throw err - } else { - return null + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate } -async function _writeFile (file, obj, options = {}) { - const fs = options.fs || _fs +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options - const str = stringify(obj, options) + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - await universalify.fromCallback(fs.writeFile)(file, str, options) -} + this.debug('matchOne', file.length, pattern.length) -const writeFile = universalify.fromPromise(_writeFile) + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] -function writeFileSync (file, obj, options = {}) { - const fs = options.fs || _fs + this.debug(pattern, p, f) - const str = stringify(obj, options) - // not sure if fs.writeFileSync returns anything, but just in case - return fs.writeFileSync(file, str, options) -} + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false -const jsonfile = { - readFile, - readFileSync, - writeFile, - writeFileSync -} + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -module.exports = jsonfile + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -/***/ }), -/* 667 */, -/* 668 */, -/* 669 */ -/***/ (function(module) { + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) -module.exports = require("util"); + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -/***/ }), -/* 670 */, -/* 671 */, -/* 672 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } -"use strict"; + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } -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 }); -const assert_1 = __webpack_require__(357); -const fs = __webpack_require__(747); -const path = __webpack_require__(622); -_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; -exports.IS_WINDOWS = process.platform === 'win32'; -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 + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) } - return p.startsWith('/'); -} -exports.isRooted = isRooted; -/** - * Recursively create a directory at `fsPath`. - * - * This implementation is optimistic, meaning it attempts to create the full - * path first, and backs up the path stack from there. - * - * @param fsPath The path to create - * @param maxDepth The maximum recursion depth - * @param depth The current recursion depth - */ -function mkdirP(fsPath, maxDepth = 1000, depth = 1) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(fsPath, 'a path argument must be provided'); - fsPath = path.resolve(fsPath); - if (depth >= maxDepth) - return exports.mkdir(fsPath); - try { - yield exports.mkdir(fsPath); - return; - } - catch (err) { - switch (err.code) { - case 'ENOENT': { - yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); - yield exports.mkdir(fsPath); - return; - } - default: { - let stats; - try { - stats = yield exports.stat(fsPath); - } - catch (err2) { - throw err; - } - if (!stats.isDirectory()) - throw err; - } - } - } - }); -} -exports.mkdirP = mkdirP; -/** - * 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 ''; - }); + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') } -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, '/'); + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') } -// 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())); + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } -//# sourceMappingURL=io-util.js.map + /***/ }), -/* 673 */, -/* 674 */ +/* 572 */, +/* 573 */, +/* 574 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var wrappy = __webpack_require__(11) -var reqs = Object.create(null) -var once = __webpack_require__(969) +"use strict"; -module.exports = wrappy(inflight) -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} - -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) - - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} - -function slice (args) { - var length = args.length - var array = [] +var Type = __webpack_require__(945); - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); /***/ }), -/* 675 */, -/* 676 */ -/***/ (function(__unusedmodule, exports) { +/* 575 */, +/* 576 */, +/* 577 */, +/* 578 */, +/* 579 */, +/* 580 */, +/* 581 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 -exports.fromCallback = function (fn) { - return Object.defineProperty(function (...args) { - if (typeof args[args.length - 1] === 'function') fn.apply(this, args) - else { - return new Promise((resolve, reject) => { - fn.apply( - this, - args.concat([(err, res) => err ? reject(err) : resolve(res)]) - ) - }) - } - }, 'name', { value: fn.name }) -} - -exports.fromPromise = function (fn) { - return Object.defineProperty(function (...args) { - const cb = args[args.length - 1] - if (typeof cb !== 'function') return fn.apply(this, args) - else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb) - }, 'name', { value: fn.name }) -} - - -/***/ }), -/* 677 */, -/* 678 */, -/* 679 */, -/* 680 */, -/* 681 */ -/***/ (function(module) { - -"use strict"; -function posix(path) { - return path.charAt(0) === '/'; -} -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); +var Schema = __webpack_require__(733); - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +module.exports = new Schema({ + explicit: [ + __webpack_require__(574), + __webpack_require__(921), + __webpack_require__(988) + ] +}); /***/ }), -/* 682 */, -/* 683 */, -/* 684 */, -/* 685 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 582 */, +/* 583 */, +/* 584 */, +/* 585 */, +/* 586 */, +/* 587 */, +/* 588 */ +/***/ (function(__unusedmodule, exports) { "use strict"; -/*eslint-disable no-use-before-define*/ - -var common = __webpack_require__(740); -var YAMLException = __webpack_require__(556); -var DEFAULT_FULL_SCHEMA = __webpack_require__(910); -var DEFAULT_SAFE_SCHEMA = __webpack_require__(830); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; +Object.defineProperty(exports, '__esModule', { value: true }); -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - if (map === null) return {}; +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} - result = {}; - keys = Object.keys(map); +function isPlainObject(o) { + var ctor,prot; - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); + if (isObject(o) === false) return false; - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; - result[tag] = style; + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; } - return result; + // Most likely a plain Object + return true; } -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} +exports.isPlainObject = isPlainObject; -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; +/***/ }), +/* 589 */, +/* 590 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - this.tag = null; - this.result = ''; +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __importStar(__webpack_require__(747)); +const core_1 = __webpack_require__(393); +const path_1 = __webpack_require__(622); +const utils_1 = __webpack_require__(870); +/** + * Creates a specification that describes how each file that is part of the artifact will be uploaded + * @param artifactName the name of the artifact being uploaded. Used during upload to denote where the artifact is stored on the server + * @param rootDirectory an absolute file path that denotes the path that should be removed from the beginning of each artifact file + * @param artifactFiles a list of absolute file paths that denote what should be uploaded as part of the artifact + */ +function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { + utils_1.checkArtifactName(artifactName); + const specifications = []; + if (!fs.existsSync(rootDirectory)) { + throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); + } + if (!fs.lstatSync(rootDirectory).isDirectory()) { + throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); + } + // Normalize and resolve, this allows for either absolute or relative paths to be used + rootDirectory = path_1.normalize(rootDirectory); + rootDirectory = path_1.resolve(rootDirectory); + /* + Example to demonstrate behavior + + Input: + artifactName: my-artifact + rootDirectory: '/home/user/files/plz-upload' + artifactFiles: [ + '/home/user/files/plz-upload/file1.txt', + '/home/user/files/plz-upload/file2.txt', + '/home/user/files/plz-upload/dir/file3.txt' + ] + + Output: + specifications: [ + ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file1.txt'], + ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'], + ['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt'] + ] + */ + for (let file of artifactFiles) { + if (!fs.existsSync(file)) { + throw new Error(`File ${file} does not exist`); + } + if (!fs.lstatSync(file).isDirectory()) { + // Normalize and resolve, this allows for either absolute or relative paths to be used + file = path_1.normalize(file); + file = path_1.resolve(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + // Check for forbidden characters in file paths that will be rejected during upload + const uploadPath = file.replace(rootDirectory, ''); + utils_1.checkArtifactFilePath(uploadPath); + /* + uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all + be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts + + path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt + join('artifact-name/', 'file-to-upload.txt') + join('artifact-name/', '/file-to-upload.txt') + join('artifact-name', 'file-to-upload.txt') + join('artifact-name', '/file-to-upload.txt') + */ + specifications.push({ + absoluteFilePath: file, + uploadFilePath: path_1.join(artifactName, uploadPath) + }); + } + else { + // Directories are rejected by the server during upload + core_1.debug(`Removing ${file} from rawSearchResults because it is a directory`); + } + } + return specifications; +} +exports.getUploadSpecification = getUploadSpecification; +//# sourceMappingURL=upload-specification.js.map - this.duplicates = []; - this.usedDuplicates = null; +/***/ }), +/* 591 */, +/* 592 */, +/* 593 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const http = __webpack_require__(605); +const https = __webpack_require__(34); + +function requestUrl(url) { + return new Promise((resolve, reject) => { + (url.startsWith("https://") ? https : http).get(url, response => { + let chunks_of_data = []; + response.on("data", fragments => chunks_of_data.push(fragments)); + response.on("end", () => + resolve(Buffer.concat(chunks_of_data).toString()) + ); + response.on("error", error => reject(error)); + }); + }); } -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; +async function getUrlContent(url) { + try { + return await requestUrl(url); + } catch (error) { + throw new Error(`Error getting ${url}. Error: ${error}`); + } +} - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } +module.exports = { + getUrlContent +}; - if (line.length && line !== '\n') result += ind; - result += line; - } +/***/ }), +/* 594 */, +/* 595 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - return result; -} +"use strict"; -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} -function testImplicitResolving(state, str) { - var index, length, type; +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const mkdirs = __webpack_require__(727).mkdirs +const pathExists = __webpack_require__(322).pathExists +const utimesMillis = __webpack_require__(916).utimesMillis +const stat = __webpack_require__(127) - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; +function copy (src, dest, opts, cb) { + if (typeof opts === 'function' && !cb) { + cb = opts + opts = {} + } else if (typeof opts === 'function') { + opts = { filter: opts } + } - if (type.resolve(str)) { - return true; - } + cb = cb || function () {} + opts = opts || {} + + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) } - return false; + stat.checkPaths(src, dest, 'copy', (err, stats) => { + if (err) return cb(err) + const { srcStat, destStat } = stats + stat.checkParentPaths(src, srcStat, dest, 'copy', err => { + if (err) return cb(err) + if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) + return checkParentDir(destStat, src, dest, opts, cb) + }) + }) } -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; +function checkParentDir (destStat, src, dest, opts, cb) { + const destParent = path.dirname(dest) + pathExists(destParent, (err, dirExists) => { + if (err) return cb(err) + if (dirExists) return startCopy(destStat, src, dest, opts, cb) + mkdirs(destParent, err => { + if (err) return cb(err) + return startCopy(destStat, src, dest, opts, cb) + }) + }) } -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); +function handleFilter (onInclude, destStat, src, dest, opts, cb) { + Promise.resolve(opts.filter(src, dest)).then(include => { + if (include) return onInclude(destStat, src, dest, opts, cb) + return cb() + }, error => cb(error)) } -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// [24] b-line-feed ::= #xA /* LF */ -// [25] b-carriage-return ::= #xD /* CR */ -// [3] c-byte-order-mark ::= #xFEFF -function isNsChar(c) { - return isPrintable(c) && !isWhitespace(c) - // byte-order-mark - && c !== 0xFEFF - // b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; +function startCopy (destStat, src, dest, opts, cb) { + if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) + return getStats(destStat, src, dest, opts, cb) } -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c, prev) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - // /* An ns-char preceding */ "#" - && c !== CHAR_COLON - && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +function getStats (destStat, src, dest, opts, cb) { + const stat = opts.dereference ? fs.stat : fs.lstat + stat(src, (err, srcStat) => { + if (err) return cb(err) + + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) + }) } -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; +function onFile (srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return copyFile(srcStat, src, dest, opts, cb) + return mayCopyFile(srcStat, src, dest, opts, cb) } -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); +function mayCopyFile (srcStat, src, dest, opts, cb) { + if (opts.overwrite) { + fs.unlink(dest, err => { + if (err) return cb(err) + return copyFile(srcStat, src, dest, opts, cb) + }) + } else if (opts.errorOnExist) { + return cb(new Error(`'${dest}' already exists`)) + } else return cb() } -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char, prev_char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); +function copyFile (srcStat, src, dest, opts, cb) { + fs.copyFile(src, dest, err => { + if (err) return cb(err) + if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) + return setDestMode(dest, srcStat.mode, cb) + }) +} - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; +function handleTimestampsAndMode (srcMode, src, dest, cb) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) { + return makeFileWritable(dest, srcMode, err => { + if (err) return cb(err) + return setDestTimestampsAndMode(srcMode, src, dest, cb) + }) } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + return setDestTimestampsAndMode(srcMode, src, dest, cb) } -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); +function makeFileWritable (dest, srcMode, cb) { + return setDestMode(dest, srcMode | 0o200, cb) +} - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } +function setDestTimestampsAndMode (srcMode, src, dest, cb) { + setDestTimestamps(src, dest, err => { + if (err) return cb(err) + return setDestMode(dest, srcMode, cb) + }) +} - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); +function setDestMode (dest, srcMode, cb) { + return fs.chmod(dest, srcMode, cb) } -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; +function setDestTimestamps (src, dest, cb) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + fs.stat(src, (err, updatedSrcStat) => { + if (err) return cb(err) + return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) + }) +} - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); +function onDir (srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) + if (destStat && !destStat.isDirectory()) { + return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) + } + return copyDir(src, dest, opts, cb) +} - return indentIndicator + chomp + '\n'; +function mkDirAndCopy (srcMode, src, dest, opts, cb) { + fs.mkdir(dest, err => { + if (err) return cb(err) + copyDir(src, dest, opts, err => { + if (err) return cb(err) + return setDestMode(dest, srcMode, cb) + }) + }) } -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +function copyDir (src, dest, opts, cb) { + fs.readdir(src, (err, items) => { + if (err) return cb(err) + return copyDirItems(items, src, dest, opts, cb) + }) } -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; +function copyDirItems (items, src, dest, opts, cb) { + const item = items.pop() + if (!item) return cb() + return copyDirItem(items, item, src, dest, opts, cb) +} - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; +function copyDirItem (items, item, src, dest, opts, cb) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => { + if (err) return cb(err) + const { destStat } = stats + startCopy(destStat, srcItem, destItem, opts, err => { + if (err) return cb(err) + return copyDirItems(items, src, dest, opts, cb) + }) + }) } -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; +function onLink (destStat, src, dest, opts, cb) { + fs.readlink(src, (err, resolvedSrc) => { + if (err) return cb(err) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; + if (!destStat) { + return fs.symlink(resolvedSrc, dest, cb) + } else { + fs.readlink(dest, (err, resolvedDest) => { + if (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) + return cb(err) + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) + } - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 + // do not copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) + } + return copyLink(resolvedSrc, dest, cb) + }) } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } + }) +} - return result.slice(1); // drop extra \n joiner +function copyLink (resolvedSrc, dest, cb) { + fs.unlink(dest, err => { + if (err) return cb(err) + return fs.symlink(resolvedSrc, dest, cb) + }) } -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; +module.exports = copy - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } - } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - return result; -} +/***/ }), +/* 596 */, +/* 597 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; +"use strict"; - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; +Object.defineProperty(exports, "__esModule", { value: true }); +const pathHelper = __webpack_require__(972); +const internal_match_kind_1 = __webpack_require__(36); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; + } + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; + } + } + return result; +} +exports.getSearchPaths = getSearchPaths; +/** + * Matches the patterns against the path + */ +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); + } + } + return result; +} +exports.match = match; +/** + * Checks whether to descend further into the directory + */ +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); } +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; +/***/ }), +/* 598 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } +var fs = __webpack_require__(747) +var polyfills = __webpack_require__(250) +var legacy = __webpack_require__(93) +var clone = __webpack_require__(608) - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } +var util = __webpack_require__(669) - _result += state.dump; - } - } +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' } -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; +function noop () {} - for (index = 0, length = objectKeyList.length; index < length; index += 1) { +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} - pairBuffer = ''; - if (index !== 0) pairBuffer += ', '; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } - if (state.condenseFlow) pairBuffer += '"'; +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + retry() + } - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; + if (typeof cb === 'function') + cb.apply(this, arguments) + }) } - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + retry() } - pairBuffer += state.dump; + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) - // Both key and value are valid. - _result += pairBuffer; + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __webpack_require__(357).equal(fs[gracefulQueue].length, 0) + }) } - - state.tag = _tag; - state.dump = '{' + _result + '}'; } -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; + return go$readFile(path, options, cb) - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) } + } - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) } + } - pairBuffer += state.dump; + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } + return go$appendFile(path, data, options, cb) - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) } + } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) } else { - pairBuffer += ': '; + cb = options } + args.push(go$readdir$cb) - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - state.tag = explicit ? type.tag : '?'; + return go$readdir(args) - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) - state.dump = _result; + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } - - return true; } } - return false; -} + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream } - var type = _toString.call(state.dump); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open } - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, arrayLevel, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) } else { - writeFlowSequence(state, arrayLevel, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); + that.fd = fd + that.emit('open', fd) + that.read() } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; - } + }) } - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - inspectNode(object, objects, duplicatesIndexes); + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); + function createReadStream (path, options) { + return new fs.ReadStream(path, options) } - state.usedDuplicates = new Array(length); -} -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); + return go$open(path, flags, mode, cb) - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } - } + }) } } + + return fs } -function dump(input, options) { - options = options || {}; +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) +} - var state = new State(options); +function retry () { + var elem = fs[gracefulQueue].shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} - if (!state.noRefs) getDuplicateReferences(input, state); - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; +/***/ }), +/* 599 */, +/* 600 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - return ''; -} +"use strict"; -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} -module.exports.dump = dump; -module.exports.safeDump = safeDump; +module.exports.ArgumentParser = __webpack_require__(452); +module.exports.Namespace = __webpack_require__(515); +module.exports.Action = __webpack_require__(380); +module.exports.HelpFormatter = __webpack_require__(532); +module.exports.Const = __webpack_require__(45); + +module.exports.ArgumentDefaultsHelpFormatter = + __webpack_require__(59).ArgumentDefaultsHelpFormatter; +module.exports.RawDescriptionHelpFormatter = + __webpack_require__(59).RawDescriptionHelpFormatter; +module.exports.RawTextHelpFormatter = + __webpack_require__(59).RawTextHelpFormatter; /***/ }), -/* 686 */ +/* 601 */ /***/ (function(__unusedmodule, exports, __webpack_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()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const os = __importStar(__webpack_require__(87)); -const events = __importStar(__webpack_require__(759)); -const child = __importStar(__webpack_require__(129)); -const path = __importStar(__webpack_require__(622)); -const io = __importStar(__webpack_require__(1)); -const ioUtil = __importStar(__webpack_require__(672)); -/* 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. +const core = __webpack_require__(393); +/** + * Returns a copy with defaults filled in. */ -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); - } - strBuffer = s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); } - 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]; - } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } - 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) => { - 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); - }); - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - const 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); - } - this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - const 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); - } - 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); - } - }); - }); } + return result; } -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 = 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 +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), -/* 687 */, -/* 688 */, -/* 689 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -try { - var util = __webpack_require__(669); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __webpack_require__(315); -} +/* 602 */, +/* 603 */, +/* 604 */, +/* 605 */ +/***/ (function(module) { +module.exports = require("http"); /***/ }), -/* 690 */, -/* 691 */, -/* 692 */ -/***/ (function(__unusedmodule, exports) { +/* 606 */, +/* 607 */, +/* 608 */ +/***/ (function(module) { "use strict"; -Object.defineProperty(exports, '__esModule', { value: true }); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +module.exports = clone - /* istanbul ignore next */ +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) - this.name = 'Deprecation'; - } + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + return copy } -exports.Deprecation = Deprecation; - /***/ }), -/* 693 */, -/* 694 */, -/* 695 */ +/* 609 */, +/* 610 */, +/* 611 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. -const { stringify } = __webpack_require__(356) -const { outputFile } = __webpack_require__(517) -async function outputJson (file, data, options = {}) { - const str = stringify(data, options) - await outputFile(file, str, options) -} -module.exports = outputJson +var Schema = __webpack_require__(733); + + +module.exports = new Schema({ + include: [ + __webpack_require__(23) + ] +}); /***/ }), -/* 696 */, -/* 697 */ -/***/ (function(module) { +/* 612 */, +/* 613 */, +/* 614 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/** internal + * class ActionContainer + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + **/ -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; +var format = __webpack_require__(669).format; -/***/ }), -/* 698 */, -/* 699 */, -/* 700 */, -/* 701 */, -/* 702 */, -/* 703 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// Constants +var c = __webpack_require__(45); -const { logger } = __webpack_require__(79); -const exec = __webpack_require__(986); -const core = __webpack_require__(393); +var $$ = __webpack_require__(255); -class ExitError extends Error { - constructor(message, code) { - super(message); - this.code = code; - } -} +//Actions +var ActionHelp = __webpack_require__(834); +var ActionAppend = __webpack_require__(378); +var ActionAppendConstant = __webpack_require__(288); +var ActionCount = __webpack_require__(927); +var ActionStore = __webpack_require__(352); +var ActionStoreConstant = __webpack_require__(267); +var ActionStoreTrue = __webpack_require__(211); +var ActionStoreFalse = __webpack_require__(963); +var ActionVersion = __webpack_require__(987); +var ActionSubparsers = __webpack_require__(983); -async function execute(cwd, command, project) { - core.startGroup(`[${project}]. Command: '${command}' in dir ${cwd}`); - logger.info(`Execute command '${command}' in dir '${cwd}'`); - const options = {}; - options.cwd = cwd; - await exec.exec(command, [], options); - core.endGroup(); -} +// Errors +var argumentErrorHelper = __webpack_require__(287); -module.exports = { - ExitError, - execute -}; +/** + * new ActionContainer(options) + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + * + * ##### Options: + * + * - `description` -- A description of what the program does + * - `prefixChars` -- Characters that prefix optional arguments + * - `argumentDefault` -- The default value for all arguments + * - `conflictHandler` -- The conflict handler to use for duplicate arguments + **/ +var ActionContainer = module.exports = function ActionContainer(options) { + options = options || {}; + this.description = options.description; + this.argumentDefault = options.argumentDefault; + this.prefixChars = options.prefixChars || ''; + this.conflictHandler = options.conflictHandler; -/***/ }), -/* 704 */, -/* 705 */, -/* 706 */, -/* 707 */, -/* 708 */, -/* 709 */, -/* 710 */, -/* 711 */, -/* 712 */, -/* 713 */, -/* 714 */, -/* 715 */, -/* 716 */, -/* 717 */, -/* 718 */, -/* 719 */, -/* 720 */, -/* 721 */, -/* 722 */, -/* 723 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // set up registries + this._registries = {}; -"use strict"; + // register actions + this.register('action', null, ActionStore); + this.register('action', 'store', ActionStore); + this.register('action', 'storeConst', ActionStoreConstant); + this.register('action', 'storeTrue', ActionStoreTrue); + this.register('action', 'storeFalse', ActionStoreFalse); + this.register('action', 'append', ActionAppend); + this.register('action', 'appendConst', ActionAppendConstant); + this.register('action', 'count', ActionCount); + this.register('action', 'help', ActionHelp); + this.register('action', 'version', ActionVersion); + this.register('action', 'parsers', ActionSubparsers); + // raise an exception if the conflict handler is invalid + this._getHandler(); -const u = __webpack_require__(676).fromCallback -const rimraf = __webpack_require__(474) + // action storage + this._actions = []; + this._optionStringActions = {}; -module.exports = { - remove: u(rimraf), - removeSync: rimraf.sync -} + // groups + this._actionGroups = []; + this._mutuallyExclusiveGroups = []; + // defaults storage + this._defaults = {}; -/***/ }), -/* 724 */, -/* 725 */, -/* 726 */, -/* 727 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // determines whether an "option" looks like a negative number + // -1, -1.5 -5e+4 + this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); -"use strict"; + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._hasNegativeNumberOptionals = []; +}; -const u = __webpack_require__(676).fromPromise -const { makeDir: _makeDir, makeDirSync } = __webpack_require__(54) -const makeDir = u(_makeDir) +// Groups must be required, then ActionContainer already defined +var ArgumentGroup = __webpack_require__(65); +var MutuallyExclusiveGroup = __webpack_require__(282); -module.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync -} +// +// Registration methods +// +/** + * ActionContainer#register(registryName, value, object) -> Void + * - registryName (String) : object type action|type + * - value (string) : keyword + * - object (Object|Function) : handler + * + * Register handlers + **/ +ActionContainer.prototype.register = function (registryName, value, object) { + this._registries[registryName] = this._registries[registryName] || {}; + this._registries[registryName][value] = object; +}; -/***/ }), -/* 728 */ -/***/ (function(__unusedmodule, exports) { +ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { + if (arguments.length < 3) { + defaultValue = null; + } + return this._registries[registryName][value] || defaultValue; +}; -"use strict"; +// +// Namespace default accessor methods +// -Object.defineProperty(exports, "__esModule", { value: true }); -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; +/** + * ActionContainer#setDefaults(options) -> Void + * - options (object):hash of options see [[Action.new]] + * + * Set defaults + **/ +ActionContainer.prototype.setDefaults = function (options) { + options = options || {}; + for (var property in options) { + if ($$.has(options, property)) { + this._defaults[property] = options[property]; } -} -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map - -/***/ }), -/* 729 */, -/* 730 */, -/* 731 */ -/***/ (function(module) { - -module.exports = {"name":"build-chain-action","version":"0.0.1","description":"GitHub action to define action chains","main":"src/lib/api.js","author":"Enrique Mingorance Cano ","license":"SEE LICENSE IN LICENSE","private":true,"bin":{"build-chain-action":"./bin/build-chain.js"},"scripts":{"test":"jest","it":"node it/it.js","locktt":"locktt","lint":"eslint .","prettier":"prettier -l src/** test/**/*.js","prettier-write":"prettier --write .","lint-final":"npm run prettier && npm run lint","prepublish":"npm run lint && npm run test","ncc-build":"ncc build bin/build-chain.js"},"git-pre-hooks":{"pre-commit":"npm run prettier && npm run ncc-build && git add dist/index.js","pre-push":"npm ci"},"dependencies":{"@actions/artifact":"^0.3.5","@actions/core":"^1.1.3","@actions/exec":"^1.0.4","@actions/glob":"^0.1.0","@octokit/rest":"^17.6.0","argparse":"^1.0.7","fs-extra":"^9.0.0","js-yaml":"^3.14.0","tmp":"^0.2.1"},"devDependencies":{"@zeit/ncc":"^0.22.3","dotenv":"^8.2.0","eslint":"^7.5.0","eslint-config-google":"^0.14.0","eslint-config-prettier":"^6.11.0","eslint-config-standard":"^14.1.1","eslint-plugin-import":"^2.22.0","eslint-plugin-jest":"^23.19.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.1.4","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1","git-pre-hooks":"^1.2.1","jest":"^25.5.1","prettier":"^2.0.5"},"jest":{"testEnvironment":"node","modulePathIgnorePatterns":["locally_execution/"]},"prettier":{"trailingComma":"none","arrowParens":"avoid"},"engines":{"node":">= 12.18.0"}}; - -/***/ }), -/* 732 */, -/* 733 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -/*eslint-disable max-len*/ - -var common = __webpack_require__(740); -var YAMLException = __webpack_require__(556); -var Type = __webpack_require__(945); - - -function compileList(schema, name, result) { - var exclude = []; + } - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); + // if these defaults match any existing arguments, replace the previous + // default on the object with the new one + this._actions.forEach(function (action) { + if ($$.has(options, action.dest)) { + action.defaultValue = options[action.dest]; + } }); +}; - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); - } - }); - - result.push(currentType); - }); +/** + * ActionContainer#getDefault(dest) -> Mixed + * - dest (string): action destination + * + * Return action default value + **/ +ActionContainer.prototype.getDefault = function (dest) { + var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null; - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; + this._actions.forEach(function (action) { + if (action.dest === dest && $$.has(action, 'defaultValue')) { + result = action.defaultValue; + } }); -} + return result; +}; +// +// Adding argument actions +// -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; +/** + * ActionContainer#addArgument(args, options) -> Object + * - args (String|Array): argument key, or array of argument keys + * - options (Object): action objects see [[Action.new]] + * + * #### Examples + * - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... }) + * - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... }) + * - addArgument('--baz', { action: 'store', nargs: 1, ... }) + **/ +ActionContainer.prototype.addArgument = function (args, options) { + args = args; + options = options || {}; - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; + if (typeof args === 'string') { + args = [ args ]; } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); + if (!Array.isArray(args)) { + throw new TypeError('addArgument first argument should be a string or an array'); + } + if (typeof options !== 'object' || Array.isArray(options)) { + throw new TypeError('addArgument second argument should be a hash'); } - return result; -} - - -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional argument + if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { + if (args && !!options.dest) { + throw new Error('dest supplied twice for positional argument'); } - }); - - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} + options = this._getPositional(args, options); + // otherwise, we're adding an optional argument + } else { + options = this._getOptional(args, options); + } -Schema.DEFAULT = null; - - -Schema.create = function createSchema() { - var schemas, types; - - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; - - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); + // if no default was supplied, use the parser-level default + if (typeof options.defaultValue === 'undefined') { + var dest = options.dest; + if ($$.has(this._defaults, dest)) { + options.defaultValue = this._defaults[dest]; + } else if (typeof this.argumentDefault !== 'undefined') { + options.defaultValue = this.argumentDefault; + } } - schemas = common.toArray(schemas); - types = common.toArray(types); - - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + // create the action object, and add it to the parser + var ActionClass = this._popActionClass(options); + if (typeof ActionClass !== 'function') { + throw new Error(format('Unknown action "%s".', ActionClass)); } + var action = new ActionClass(options); - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + // throw an error if the action type is not callable + var typeFunction = this._registryGet('type', action.type, action.type); + if (typeof typeFunction !== 'function') { + throw new Error(format('"%s" is not callable', typeFunction)); } - return new Schema({ - include: schemas, - explicit: types - }); + return this._addAction(action); }; +/** + * ActionContainer#addArgumentGroup(options) -> ArgumentGroup + * - options (Object): hash of options see [[ArgumentGroup.new]] + * + * Create new arguments groups + **/ +ActionContainer.prototype.addArgumentGroup = function (options) { + var group = new ArgumentGroup(this, options); + this._actionGroups.push(group); + return group; +}; -module.exports = Schema; +/** + * ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup + * - options (Object): {required: false} + * + * Create new mutual exclusive groups + **/ +ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { + var group = new MutuallyExclusiveGroup(this, options); + this._mutuallyExclusiveGroups.push(group); + return group; +}; +ActionContainer.prototype._addAction = function (action) { + var self = this; -/***/ }), -/* 734 */, -/* 735 */, -/* 736 */, -/* 737 */, -/* 738 */, -/* 739 */, -/* 740 */ -/***/ (function(module) { + // resolve any conflicts + this._checkConflict(action); -"use strict"; + // add to actions list + this._actions.push(action); + action.container = this; + // index the action by any option strings it has + action.optionStrings.forEach(function (optionString) { + self._optionStringActions[optionString] = action; + }); + + // set the flag if any option strings look like negative numbers + action.optionStrings.forEach(function (optionString) { + if (optionString.match(self._regexpNegativeNumber)) { + if (!self._hasNegativeNumberOptionals.some(Boolean)) { + self._hasNegativeNumberOptionals.push(true); + } + } + }); + // return the created action + return action; +}; -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} +ActionContainer.prototype._removeAction = function (action) { + var actionIndex = this._actions.indexOf(action); + if (actionIndex >= 0) { + this._actions.splice(actionIndex, 1); + } +}; +ActionContainer.prototype._addContainerActions = function (container) { + // collect groups by titles + var titleGroupMap = {}; + this._actionGroups.forEach(function (group) { + if (titleGroupMap[group.title]) { + throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); + } + titleGroupMap[group.title] = group; + }); -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} + // map each action to its group + var groupMap = {}; + function actionHash(action) { + // unique (hopefully?) string suitable as dictionary key + return action.getName(); + } + container._actionGroups.forEach(function (group) { + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!titleGroupMap[group.title]) { + titleGroupMap[group.title] = this.addArgumentGroup({ + title: group.title, + description: group.description + }); + } + // map the actions to their new group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = titleGroupMap[group.title]; + }); + }, this); -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + var mutexGroup; + container._mutuallyExclusiveGroups.forEach(function (group) { + mutexGroup = this.addMutuallyExclusiveGroup({ + required: group.required + }); + // map the actions to their new mutex group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = mutexGroup; + }); + }, this); // forEach takes a 'this' argument - return [ sequence ]; -} + // add all actions to this container or their group + container._actions.forEach(function (action) { + var key = actionHash(action); + if (groupMap[key]) { + groupMap[key]._addAction(action); + } else { + this._addAction(action); + } + }); +}; +ActionContainer.prototype._getPositional = function (dest, options) { + if (Array.isArray(dest)) { + dest = dest[0]; + } + // make sure required is not specified + if (options.required) { + throw new Error('"required" is an invalid argument for positionals.'); + } -function extend(target, source) { - var index, length, key, sourceKeys; + // mark positional arguments as required if at least one is + // always required + if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) { + options.required = true; + } + if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') { + options.required = true; + } - if (source) { - sourceKeys = Object.keys(source); + // return the keyword arguments with no option strings + options.dest = dest; + options.optionStrings = []; + return options; +}; - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; +ActionContainer.prototype._getOptional = function (args, options) { + var prefixChars = this.prefixChars; + var optionStrings = []; + var optionStringsLong = []; + + // determine short and long option strings + args.forEach(function (optionString) { + // error on strings that don't start with an appropriate prefix + if (prefixChars.indexOf(optionString[0]) < 0) { + throw new Error(format('Invalid option string "%s": must start with a "%s".', + optionString, + prefixChars + )); } - } - return target; -} + // strings starting with two prefix characters are long options + optionStrings.push(optionString); + if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { + optionStringsLong.push(optionString); + } + }); + // infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + var dest = options.dest || null; + delete options.dest; -function repeat(string, count) { - var result = '', cycle; + if (!dest) { + var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; + dest = $$.trimChars(optionStringDest, this.prefixChars); - for (cycle = 0; cycle < count; cycle += 1) { - result += string; + if (dest.length === 0) { + throw new Error( + format('dest= is required for options like "%s"', optionStrings.join(', ')) + ); + } + dest = dest.replace(/-/g, '_'); } - return result; -} + // return the updated keyword arguments + options.dest = dest; + options.optionStrings = optionStrings; + return options; +}; -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} +ActionContainer.prototype._popActionClass = function (options, defaultValue) { + defaultValue = defaultValue || null; + var action = (options.action || defaultValue); + delete options.action; -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; + var actionClass = this._registryGet('action', action, action); + return actionClass; +}; + +ActionContainer.prototype._getHandler = function () { + var handlerString = this.conflictHandler; + var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString); + var func = this[handlerFuncName]; + if (typeof func === 'undefined') { + var msg = 'invalid conflict resolution value: ' + handlerString; + throw new Error(msg); + } else { + return func; + } +}; + +ActionContainer.prototype._checkConflict = function (action) { + var optionStringActions = this._optionStringActions; + var conflictOptionals = []; + + // find all options that conflict with this option + // collect pairs, the string, and an existing action that it conflicts with + action.optionStrings.forEach(function (optionString) { + var conflOptional = optionStringActions[optionString]; + if (typeof conflOptional !== 'undefined') { + conflictOptionals.push([ optionString, conflOptional ]); + } + }); + + if (conflictOptionals.length > 0) { + var conflictHandler = this._getHandler(); + conflictHandler.call(this, action, conflictOptionals); + } +}; + +ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { + var conflicts = conflOptionals.map(function (pair) { return pair[0]; }); + conflicts = conflicts.join(', '); + throw argumentErrorHelper( + action, + format('Conflicting option string(s): %s', conflicts) + ); +}; + +ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { + // remove all conflicting options + var self = this; + conflOptionals.forEach(function (pair) { + var optionString = pair[0]; + var conflictingAction = pair[1]; + // remove the conflicting option string + var i = conflictingAction.optionStrings.indexOf(optionString); + if (i >= 0) { + conflictingAction.optionStrings.splice(i, 1); + } + delete self._optionStringActions[optionString]; + // if the option now has no option string, remove it from the + // container holding it + if (conflictingAction.optionStrings.length === 0) { + conflictingAction.container._removeAction(conflictingAction); + } + }); +}; /***/ }), -/* 741 */, -/* 742 */ +/* 615 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var fs = __webpack_require__(747) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(818) -} else { - core = __webpack_require__(197) -} +"use strict"; -module.exports = isexe -isexe.sync = sync -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } +const u = __webpack_require__(676).fromCallback +const fs = __webpack_require__(598) +const path = __webpack_require__(622) +const mkdir = __webpack_require__(727) +const remove = __webpack_require__(723) - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } +const emptyDir = u(function emptyDir (dir, callback) { + callback = callback || function () {} + fs.readdir(dir, (err, items) => { + if (err) return mkdir.mkdirs(dir, callback) - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } + items = items.map(item => path.join(dir, item)) - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } + deleteItem() + + function deleteItem () { + const item = items.pop() + if (!item) return callback() + remove.remove(item, err => { + if (err) return callback(err) + deleteItem() + }) } - cb(er, is) }) -} +}) -function sync (path, options) { - // my kingdom for a filtered catch +function emptyDirSync (dir) { + let items try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } + items = fs.readdirSync(dir) + } catch { + return mkdir.mkdirsSync(dir) } + + items.forEach(item => { + item = path.join(dir, item) + remove.removeSync(item) + }) +} + +module.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir } /***/ }), -/* 743 */, -/* 744 */, -/* 745 */, -/* 746 */, -/* 747 */ +/* 616 */, +/* 617 */, +/* 618 */, +/* 619 */ /***/ (function(module) { -module.exports = require("fs"); +module.exports = require("constants"); /***/ }), -/* 748 */, -/* 749 */, -/* 750 */, -/* 751 */, -/* 752 */, -/* 753 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 620 */, +/* 621 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +const path = __webpack_require__(622); +const pathKey = __webpack_require__(39); -Object.defineProperty(exports, '__esModule', { value: true }); +module.exports = opts => { + opts = Object.assign({ + cwd: process.cwd(), + path: process.env[pathKey()] + }, opts); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + let prev; + let pth = path.resolve(opts.cwd); + const ret = []; -var endpoint = __webpack_require__(385); -var universalUserAgent = __webpack_require__(796); -var isPlainObject = _interopDefault(__webpack_require__(548)); -var nodeFetch = _interopDefault(__webpack_require__(454)); -var requestError = __webpack_require__(463); + while (prev !== pth) { + ret.push(path.join(pth, 'node_modules/.bin')); + prev = pth; + pth = path.resolve(pth, '..'); + } -const VERSION = "5.4.5"; + // ensure the running `node` binary is used + ret.push(path.dirname(process.execPath)); -function getBufferResponse(response) { - return response.arrayBuffer(); -} + return ret.concat(opts.path).join(path.delimiter); +}; -function fetchWrapper(requestOptions) { - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } +module.exports.env = opts => { + opts = Object.assign({ + env: process.env + }, opts); - let headers = {}; - let status; - let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - redirect: requestOptions.redirect - }, requestOptions.request)).then(response => { - url = response.url; - status = response.status; + const env = Object.assign({}, opts.env); + const path = pathKey({env}); - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } + opts.path = env[path]; + env[path] = module.exports(opts); - if (status === 204 || status === 205) { - return; - } // GitHub API returns 200 for HEAD requests + return env; +}; - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } +/***/ }), +/* 622 */ +/***/ (function(module) { - throw new requestError.RequestError(response.statusText, status, { - headers, - request: requestOptions - }); - } +module.exports = require("path"); - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - headers, - request: requestOptions - }); - } +/***/ }), +/* 623 */, +/* 624 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (status >= 400) { - return response.text().then(message => { - const error = new requestError.RequestError(message, status, { - headers, - request: requestOptions - }); - - try { - let responseBody = JSON.parse(error.message); - Object.assign(error, responseBody); - let errors = responseBody.errors; // Assumption `errors` would always be in Array format - - error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); - } catch (e) {// ignore, see octokit/rest.js#684 - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = __webpack_require__(870); +/** + * Used for managing http clients during either upload or download + */ +class HttpManager { + constructor(clientCount, userAgent) { + if (clientCount < 1) { + throw new Error('There must be at least one client'); + } + this.userAgent = userAgent; + this.clients = new Array(clientCount).fill(utils_1.createHttpClient(userAgent)); + } + getClient(index) { + return this.clients[index]; + } + // client disposal is necessary if a keep-alive connection is used to properly close the connection + // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 + disposeAndReplaceClient(index) { + this.clients[index].dispose(); + this.clients[index] = utils_1.createHttpClient(this.userAgent); + } + disposeAndReplaceAllClients() { + for (const [index] of this.clients.entries()) { + this.disposeAndReplaceClient(index); + } + } +} +exports.HttpManager = HttpManager; +//# sourceMappingURL=http-manager.js.map - throw error; - }); - } +/***/ }), +/* 625 */, +/* 626 */, +/* 627 */, +/* 628 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - const contentType = response.headers.get("content-type"); +"use strict"; - if (/application\/json/.test(contentType)) { - return response.json(); - } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } +const { stringify } = __webpack_require__(356) +const { outputFileSync } = __webpack_require__(517) - return getBufferResponse(response); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) { - throw error; - } +function outputJsonSync (file, data, options) { + const str = stringify(data, options) - throw new requestError.RequestError(error.message, 500, { - headers, - request: requestOptions - }); - }); + outputFileSync(file, str, options) } -function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); +module.exports = outputJsonSync - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); - } - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); - }; +/***/ }), +/* 629 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); - return endpointOptions.request.hook(request, endpointOptions); - }; +"use strict"; - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); -} -const request = withDefaults(endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } -}); +var Type = __webpack_require__(945); -exports.request = request; -//# sourceMappingURL=index.js.map +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; -/***/ }), -/* 754 */, -/* 755 */, -/* 756 */, -/* 757 */, -/* 758 */, -/* 759 */ -/***/ (function(module) { + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; -module.exports = require("events"); + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } -/***/ }), -/* 760 */, -/* 761 */ -/***/ (function(module) { + return true; +} -module.exports = require("zlib"); +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; -/***/ }), -/* 762 */, -/* 763 */ -/***/ (function(module) { + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } -module.exports = removeHook + return new RegExp(regexp, modifiers); +} -function removeHook (state, name, method) { - if (!state.registry[name]) { - return - } +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; - var index = state.registry[name] - .map(function (registered) { return registered.orig }) - .indexOf(method) + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; - if (index === -1) { - return - } + return result; +} - state.registry[name].splice(index, 1) +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; } +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + /***/ }), -/* 764 */, -/* 765 */ +/* 630 */ /***/ (function(module) { -module.exports = require("process"); +module.exports = require("perf_hooks"); /***/ }), -/* 766 */, -/* 767 */, -/* 768 */ +/* 631 */ /***/ (function(module) { +module.exports = require("net"); + +/***/ }), +/* 632 */, +/* 633 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + "use strict"; -module.exports = function (x) { - var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); - var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); - if (x[x.length - 1] === lf) { - x = x.slice(0, x.length - 1); - } +var Type = __webpack_require__(945); - if (x[x.length - 1] === cr) { - x = x.slice(0, x.length - 1); - } +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} - return x; -}; +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); /***/ }), -/* 769 */, -/* 770 */, -/* 771 */, -/* 772 */, -/* 773 */, -/* 774 */ +/* 634 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +var wrappy = __webpack_require__(11) +var reqs = Object.create(null) +var once = __webpack_require__(969) +module.exports = wrappy(inflight) -const u = __webpack_require__(676).fromCallback -module.exports = { - copy: u(__webpack_require__(595)) +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } } +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) -/***/ }), -/* 775 */, -/* 776 */, -/* 777 */, -/* 778 */, -/* 779 */, -/* 780 */, -/* 781 */, -/* 782 */, -/* 783 */, -/* 784 */, -/* 785 */, -/* 786 */, -/* 787 */ -/***/ (function(module) { - -module.exports = { - warn: "warn", - error: "error", - ignore: "ignore" -}; - - -/***/ }), -/* 788 */, -/* 789 */, -/* 790 */, -/* 791 */, -/* 792 */, -/* 793 */, -/* 794 */, -/* 795 */, -/* 796 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var osName = _interopDefault(__webpack_require__(2)); - -function getUserAgent() { - try { - return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`; - } catch (error) { - if (/wmic os get Caption/.test(error.message)) { - return "Windows "; + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } } - - return ""; - } + }) } -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} /***/ }), -/* 797 */, -/* 798 */, -/* 799 */, -/* 800 */, -/* 801 */, -/* 802 */, -/* 803 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 635 */, +/* 636 */ +/***/ (function(module) { -/*! - * Tmp - * - * Copyright (c) 2011-2017 KARASZI Istvan +/** * - * MIT Licensed - */ - -/* - * Module dependencies. + * @param {object} the tree node with its parents and children + * @param {Set} the set to interate */ -const fs = __webpack_require__(747); -const os = __webpack_require__(87); -const path = __webpack_require__(622); -const crypto = __webpack_require__(417); -const _c = fs.constants && os.constants ? - { fs: fs.constants, os: os.constants } : - process.binding('constants'); -const rimraf = __webpack_require__(301); +function parentChainFromNode(node, nodeList = []) { + if (!nodeList.map(n => n.project).includes(node.project)) { + node.parents.forEach(parent => parentChainFromNode(parent, nodeList)); + nodeList.push(node); + } + return nodeList; +} -/* - * The working inner variables. +/** + * + * @param {String} key the JSON.stringify key + * @param {Object} value the JSON.stringify value + * @param {Array} cache an empty array instance */ -const - // the random characters to choose from - RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', - - TEMPLATE_PATTERN = /XXXXXX/, +function jsonStringFunction(key, value, cache) { + { + return ["parents", "children"].includes(key) + ? value.map(node => { + if (!cache.includes(node.project)) { + cache.push(node.project); + return node; + } + return { + project: node.project, + warning: + "rest of the node information removed to avoid circular dependency problem. The node information is already defined in the json." + }; + }) + : value; + } +} - DEFAULT_TRIES = 3, +module.exports = { parentChainFromNode, jsonStringFunction }; - CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), - EBADF = _c.EBADF || _c.os.errno.EBADF, - ENOENT = _c.ENOENT || _c.os.errno.ENOENT, +/***/ }), +/* 637 */, +/* 638 */, +/* 639 */, +/* 640 */, +/* 641 */, +/* 642 */, +/* 643 */, +/* 644 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - DIR_MODE = 448 /* 0o700 */, - FILE_MODE = 384 /* 0o600 */, +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored - EXIT = 'exit', +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} - SIGINT = 'SIGINT', +var path = __webpack_require__(622) +var minimatch = __webpack_require__(571) +var isAbsolute = __webpack_require__(681) +var Minimatch = minimatch.Minimatch - // this will hold the objects need to be removed on exit - _removeObjects = []; +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} -var - _gracefulCleanup = false; +function alphasort (a, b) { + return a.localeCompare(b) +} -/** - * Random name generator based on crypto. - * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript - * - * @param {number} howMany - * @returns {string} the generated random name - * @private - */ -function _randomChars(howMany) { - var - value = [], - rnd = null; +function setupIgnores (self, options) { + self.ignore = options.ignore || [] - // make sure that we do not fail because we ran out of entropy - try { - rnd = crypto.randomBytes(howMany); - } catch (e) { - rnd = crypto.pseudoRandomBytes(howMany); - } + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] - for (var i = 0; i < howMany; i++) { - value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) } - - return value.join(''); -} - -/** - * Checks whether the `obj` parameter is defined or not. - * - * @param {Object} obj - * @returns {boolean} true if the object is undefined - * @private - */ -function _isUndefined(obj) { - return typeof obj === 'undefined'; } -/** - * Parses the function arguments. - * - * This function helps to have optional arguments. - * - * @param {(Options|Function)} options - * @param {Function} callback - * @returns {Array} parsed arguments - * @private - */ -function _parseArguments(options, callback) { - /* istanbul ignore else */ - if (typeof options === 'function') { - return [{}, options]; +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) } - /* istanbul ignore else */ - if (_isUndefined(options)) { - return [{}, callback]; + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher } - - return [options, callback]; } -/** - * Generates a new temporary name. - * - * @param {Object} opts - * @returns {string} the new random name according to opts - * @private - */ -function _generateTmpName(opts) { +function setopts (self, pattern, options) { + if (!options) + options = {} - const tmpDir = _getTmpDir(); + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } - // fail early on missing tmp dir - if (isBlank(opts.dir) && isBlank(tmpDir)) { - throw new Error('No tmp dir specified'); - } + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute - /* istanbul ignore else */ - if (!isBlank(opts.name)) { - return path.join(opts.dir || tmpDir, opts.name); - } + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) - // mkstemps like template - // opts.template has already been guarded in tmpName() below - /* istanbul ignore else */ - if (opts.template) { - var template = opts.template; - // make sure that we prepend the tmp path if none was given - /* istanbul ignore else */ - if (path.basename(template) === template) - template = path.join(opts.dir || tmpDir, template); - return template.replace(TEMPLATE_PATTERN, _randomChars(6)); + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd } - // prefix and postfix - const name = [ - (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), - process.pid, - _randomChars(12), - (opts.postfix ? opts.postfix : '') - ].join(''); + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") - return path.join(opts.dir || tmpDir, name); -} + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount -/** - * Gets a temporary file name. - * - * @param {(Options|tmpNameCallback)} options options or callback - * @param {?tmpNameCallback} callback the callback function - */ -function tmpName(options, callback) { - var - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1], - tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true - /* istanbul ignore else */ - if (isNaN(tries) || tries < 0) - return cb(new Error('Invalid tries')); + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} - /* istanbul ignore else */ - if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) - return cb(new Error('Invalid template provided')); +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) - (function _getUniqueName() { - try { - const name = _generateTmpName(opts); + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } - // check whether the path exists then retry if needed - fs.stat(name, function (err) { - /* istanbul ignore else */ - if (!err) { - /* istanbul ignore else */ - if (tries-- > 0) return _getUniqueName(); + if (!nou) + all = Object.keys(all) - return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); - } + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) - cb(null, name); - }); - } catch (err) { - cb(err); + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) } - }()); -} + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } -/** - * Synchronous version of tmpName. - * - * @param {Object} options - * @returns {string} the generated random name - * @throws {Error} if the options are invalid or could not generate a filename - */ -function tmpNameSync(options) { - var - args = _parseArguments(options), - opts = args[0], - tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) - /* istanbul ignore else */ - if (isNaN(tries) || tries < 0) - throw new Error('Invalid tries'); + self.found = all +} - /* istanbul ignore else */ - if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) - throw new Error('Invalid template provided'); +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' - do { - const name = _generateTmpName(opts); - try { - fs.statSync(name); - } catch (e) { - return name; + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] } - } while (tries-- > 0); + } - throw new Error('Could not get a unique tmp filename, max tries reached'); + return m } -/** - * Creates and opens a temporary file. - * - * @param {(Options|fileCallback)} options the config options or the callback function - * @param {?fileCallback} callback - */ -function file(options, callback) { - var - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1]; +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } - // gets a temporary filename - tmpName(opts, function _tmpNameCreated(err, name) { - /* istanbul ignore else */ - if (err) return cb(err); + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') - // create and open the file - fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { - /* istanbul ignore else */ - if (err) return cb(err); + return abs +} - if (opts.discardDescriptor) { - return fs.close(fd, function _discardCallback(err) { - /* istanbul ignore else */ - if (err) { - // Low probability, and the file exists, so this could be - // ignored. If it isn't we certainly need to unlink the - // file, and if that fails too its error is more - // important. - try { - fs.unlinkSync(name); - } catch (e) { - if (!isENOENT(e)) { - err = e; - } - } - return cb(err); - } - cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); - }); - } - /* istanbul ignore else */ - if (opts.detachDescriptor) { - return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); - } - cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); - }); - }); -} - -/** - * Synchronous version of file. - * - * @param {Options} options - * @returns {FileSyncObject} object consists of name, fd and removeCallback - * @throws {Error} if cannot create a file - */ -function fileSync(options) { - var - args = _parseArguments(options), - opts = args[0]; - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - const name = tmpNameSync(opts); - var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); - /* istanbul ignore else */ - if (opts.discardDescriptor) { - fs.closeSync(fd); - fd = undefined; - } +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false - return { - name: name, - fd: fd, - removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) - }; + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) } -/** - * Creates a temporary directory. - * - * @param {(Options|dirCallback)} options the options or the callback function - * @param {?dirCallback} callback - */ -function dir(options, callback) { - var - args = _parseArguments(options, callback), - opts = args[0], - cb = args[1]; - - // gets a temporary filename - tmpName(opts, function _tmpNameCreated(err, name) { - /* istanbul ignore else */ - if (err) return cb(err); - - // create the directory - fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { - /* istanbul ignore else */ - if (err) return cb(err); +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false - cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); - }); - }); + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) } -/** - * Synchronous version of dir. - * - * @param {Options} options - * @returns {DirSyncObject} object consists of name and removeCallback - * @throws {Error} if it cannot create a directory - */ -function dirSync(options) { - var - args = _parseArguments(options), - opts = args[0]; - const name = tmpNameSync(opts); - fs.mkdirSync(name, opts.mode || DIR_MODE); +/***/ }), +/* 645 */, +/* 646 */, +/* 647 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return { - name: name, - removeCallback: _prepareTmpDirRemoveCallback(name, opts) - }; -} +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __importStar(__webpack_require__(747)); +const zlib = __importStar(__webpack_require__(761)); +const util_1 = __webpack_require__(669); +const stat = util_1.promisify(fs.stat); +/** + * Creates a Gzip compressed file of an original file at the provided temporary filepath location + * @param {string} originalFilePath filepath of whatever will be compressed. The original file will be unmodified + * @param {string} tempFilePath the location of where the Gzip file will be created + * @returns the size of gzip file that gets created + */ +function createGZipFileOnDisk(originalFilePath, tempFilePath) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + const inputStream = fs.createReadStream(originalFilePath); + const gzip = zlib.createGzip(); + const outputStream = fs.createWriteStream(tempFilePath); + inputStream.pipe(gzip).pipe(outputStream); + outputStream.on('finish', () => __awaiter(this, void 0, void 0, function* () { + // wait for stream to finish before calculating the size which is needed as part of the Content-Length header when starting an upload + const size = (yield stat(tempFilePath)).size; + resolve(size); + })); + outputStream.on('error', error => { + // eslint-disable-next-line no-console + console.log(error); + reject; + }); + }); + }); +} +exports.createGZipFileOnDisk = createGZipFileOnDisk; +/** + * Creates a GZip file in memory using a buffer. Should be used for smaller files to reduce disk I/O + * @param originalFilePath the path to the original file that is being GZipped + * @returns a buffer with the GZip file + */ +function createGZipFileInBuffer(originalFilePath) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + var e_1, _a; + const inputStream = fs.createReadStream(originalFilePath); + const gzip = zlib.createGzip(); + inputStream.pipe(gzip); + // read stream into buffer, using experimental async iterators see https://github.com/nodejs/readable-stream/issues/403#issuecomment-479069043 + const chunks = []; + try { + for (var gzip_1 = __asyncValues(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), !gzip_1_1.done;) { + const chunk = gzip_1_1.value; + chunks.push(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (gzip_1_1 && !gzip_1_1.done && (_a = gzip_1.return)) yield _a.call(gzip_1); + } + finally { if (e_1) throw e_1.error; } + } + resolve(Buffer.concat(chunks)); + })); + }); +} +exports.createGZipFileInBuffer = createGZipFileInBuffer; +//# sourceMappingURL=upload-gzip.js.map -/** - * Removes files asynchronously. - * - * @param {Object} fdPath - * @param {Function} next - * @private - */ -function _removeFileAsync(fdPath, next) { - const _handler = function (err) { - if (err && !isENOENT(err)) { - // reraise any unanticipated error - return next(err); - } - next(); - } +/***/ }), +/* 648 */, +/* 649 */, +/* 650 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (0 <= fdPath[0]) - fs.close(fdPath[0], function (err) { - fs.unlink(fdPath[1], _handler); - }); - else fs.unlink(fdPath[1], _handler); -} +const buildChainFlow = __webpack_require__(653); -/** - * Removes files synchronously. - * - * @param {Object} fdPath - * @private - */ -function _removeFileSync(fdPath) { - try { - if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); - } catch (e) { - // reraise any unanticipated error - if (!isEBADF(e) && !isENOENT(e)) throw e; - } finally { - try { - fs.unlinkSync(fdPath[1]); - } - catch (e) { - // reraise any unanticipated error - if (!isENOENT(e)) throw e; - } - } +async function executeGitHubAction(context) { + await buildChainFlow.start(context); } -/** - * Prepares the callback for removal of the temporary file. - * - * @param {string} name the path of the file - * @param {number} fd file descriptor - * @param {Object} opts - * @returns {fileCallback} - * @private - */ -function _prepareTmpFileRemoveCallback(name, fd, opts) { - const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); - const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); +module.exports = { executeGitHubAction }; - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return removeCallback; -} +/***/ }), +/* 651 */, +/* 652 */, +/* 653 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Simple wrapper for rimraf. - * - * @param {string} dirPath - * @param {Function} next - * @private - */ -function _rimrafRemoveDirWrapper(dirPath, next) { - rimraf(dirPath, next); -} +const { + checkoutDefinitionTree, + getDir, + getFinalDefinitionFilePath +} = __webpack_require__(57); +const { getTreeForProject } = __webpack_require__(702); -/** - * Simple wrapper for rimraf.sync. - * - * @param {string} dirPath - * @private - */ -function _rimrafRemoveDirSyncWrapper(dirPath, next) { - try { - return next(null, rimraf.sync(dirPath)); - } catch (err) { - return next(err); - } -} +const { printCheckoutInformation } = __webpack_require__(656); +const { logger } = __webpack_require__(79); +const { execute } = __webpack_require__(81); +const { treatCommand } = __webpack_require__(52); +const core = __webpack_require__(393); +const { + archiveArtifacts +} = __webpack_require__(503); -/** - * Prepares the callback for removal of the temporary directory. - * - * @param {string} name - * @param {Object} opts - * @returns {Function} the callback - * @private - */ -function _prepareTmpDirRemoveCallback(name, opts) { - const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); - const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); - const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); - const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); +async function start(context) { + core.startGroup( + `Checking out ${context.config.github.groupProject} and its dependencies` + ); + const definitionFile = await getFinalDefinitionFilePath( + context, + context.config.github.inputs.definitionFile + ); + const definitionTree = await getTreeForProject( + definitionFile, + context.config.github.repository + ); + logger.info( + `Tree for project ${ + context.config.github.repository + } loaded from ${definitionFile}. Dependencies: ${ + definitionTree.dependencies + ? definitionTree.dependencies.map(node => node.project) + : "no dependencies" + }` + ); + const nodeChain = await checkoutDefinitionTree(context, definitionTree); + core.endGroup(); - return removeCallback; -} + core.startGroup(`Checkout Summary...`); + printCheckoutInformation( + nodeChain.reduce((acc, curr) => { + acc[curr.project] = curr.checkoutInfo; + return acc; + }, {}) + ); + core.endGroup(); -/** - * Creates a guarded function wrapping the removeFunction call. - * - * @param {Function} removeFunction - * @param {Object} arg - * @returns {Function} - * @private - */ -function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { - var called = false; + const executionResult = await executeBuild( + context.config.rootFolder, + nodeChain, + context.config.github.repository + ) + .then(() => true) + .catch(e => e); - return function _cleanupCallback(next) { - next = next || function () {}; - if (!called) { - const toRemove = cleanupCallbackSync || _cleanupCallback; - const index = _removeObjects.indexOf(toRemove); - /* istanbul ignore else */ - if (index >= 0) _removeObjects.splice(index, 1); + core.startGroup(`Archiving artifacts...`); + await archiveArtifacts( + nodeChain.find(node => node.project === context.config.github.repository), + nodeChain, + executionResult === true ? ["success", "always"] : ["failure", "always"] + ); + core.endGroup(); - called = true; - // sync? - if (removeFunction.length === 1) { - try { - removeFunction(arg); - return next(null); - } - catch (err) { - // if no next is provided and since we are - // in silent cleanup mode on process exit, - // we will ignore the error - return next(err); - } - } else return removeFunction(arg, next); - } else return next(new Error('cleanup callback has already been called')); - }; + if (executionResult !== true) { + logger.error(executionResult); + throw new Error( + `Command executions have failed, please review latest execution ${executionResult}` + ); + } } -/** - * The garbage collector. - * - * @private - */ -function _garbageCollector() { - /* istanbul ignore else */ - if (!_gracefulCleanup) return; - - // the function being called removes itself from _removeObjects, - // loop until _removeObjects is empty - while (_removeObjects.length) { - try { - _removeObjects[0](); - } catch (e) { - // already removed? - } +async function executeBuild(rootFolder, nodeChain, projectTriggeringJob) { + for await (const node of nodeChain) { + await executeNodeBuildCommands( + rootFolder, + node, + projectTriggeringJob === node.project + ); } } -/** - * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. - */ -function isEBADF(error) { - return isExpectedError(error, -EBADF, 'EBADF'); +async function executeNodeBuildCommands( + rootFolder, + node, + isProjectTriggeringJob +) { + const dir = getDir(rootFolder, node.project); + if (node.build["build-command"].before) { + await executeBuildCommands( + dir, + getCommand(node.build["build-command"].before, isProjectTriggeringJob), + node.project + ); + } + await executeBuildCommands( + dir, + getCommand(node.build["build-command"], isProjectTriggeringJob), + node.project + ); + if (node.build["build-command"].after) { + await executeBuildCommands( + dir, + getCommand(node.build["build-command"].after, isProjectTriggeringJob), + node.project + ); + } } -/** - * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. - */ -function isENOENT(error) { - return isExpectedError(error, -ENOENT, 'ENOENT'); +function getCommand(buildCommand, isProjectTriggeringJob) { + return isProjectTriggeringJob + ? buildCommand.current + : buildCommand.upstream || buildCommand.current; } -/** - * Helper to determine whether the expected error code matches the actual code and errno, - * which will differ between the supported node versions. - * - * - Node >= 7.0: - * error.code {string} - * error.errno {string|number} any numerical value will be negated - * - * - Node >= 6.0 < 7.0: - * error.code {string} - * error.errno {number} negated - * - * - Node >= 4.0 < 6.0: introduces SystemError - * error.code {string} - * error.errno {number} negated - * - * - Node >= 0.10 < 4.0: - * error.code {number} negated - * error.errno n/a - */ -function isExpectedError(error, code, errno) { - return error.code === code || error.code === errno; +async function executeBuildCommands(cwd, buildCommands, project) { + if (buildCommands) { + for (const command of Array.isArray(buildCommands) + ? buildCommands.filter(c => c) + : [buildCommands]) { + core.startGroup(`[${project}]. Command: '${command}' in dir ${cwd}`); + await execute(cwd, treatCommand(command)); + core.endGroup(); + } + } } -/** - * Helper which determines whether a string s is blank, that is undefined, or empty or null. - * - * @private - * @param {string} s - * @returns {Boolean} true whether the string s is blank, false otherwise - */ -function isBlank(s) { - return s === null || s === undefined || !s.trim(); -} +module.exports = { + start +}; -/** - * Sets the graceful cleanup. - */ -function setGracefulCleanup() { - _gracefulCleanup = true; -} -/** - * Returns the currently configured tmp dir from os.tmpdir(). - * - * @private - * @returns {string} the currently configured tmp dir - */ -function _getTmpDir() { - return os.tmpdir(); -} +/***/ }), +/* 654 */ +/***/ (function(module) { -/** - * If there are multiple different versions of tmp in place, make sure that - * we recognize the old listeners. - * - * @param {Function} listener - * @private - * @returns {Boolean} true whether listener is a legacy listener - */ -function _is_legacy_listener(listener) { - return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') - && listener.toString().indexOf('_garbageCollector();') > -1; +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) } -/** - * Safely install SIGINT listener. - * - * NOTE: this will only work on OSX and Linux. - * - * @private - */ -function _safely_install_sigint_listener() { - - const listeners = process.listeners(SIGINT); - const existingListeners = []; - for (let i = 0, length = listeners.length; i < length; i++) { - const lstnr = listeners[i]; - /* istanbul ignore else */ - if (lstnr.name === '_tmp$sigint_listener') { - existingListeners.push(lstnr); - process.removeListener(SIGINT, lstnr); - } - } - process.on(SIGINT, function _tmp$sigint_listener(doExit) { - for (let i = 0, length = existingListeners.length; i < length; i++) { - // let the existing listener do the garbage collection (e.g. jest sandbox) - try { - existingListeners[i](false); - } catch (err) { - // ignore - } - } - try { - // force the garbage collector even it is called again in the exit listener - _garbageCollector(); - } finally { - if (!!doExit) { - process.exit(0); - } - } - }); +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) } -/** - * Safely install process exit listener. - * - * @private - */ -function _safely_install_exit_listener() { - const listeners = process.listeners(EXIT); - // collect any existing listeners - const existingListeners = []; - for (let i = 0, length = listeners.length; i < length; i++) { - const lstnr = listeners[i]; - /* istanbul ignore else */ - // TODO: remove support for legacy listeners once release 1.0.0 is out - if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { - // we must forget about the uncaughtException listener, hopefully it is ours - if (lstnr.name !== '_uncaughtExceptionThrown') { - existingListeners.push(lstnr); +/***/ }), +/* 655 */, +/* 656 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const { logger } = __webpack_require__(79); + +const groupBy = (checkoutInfo, key) => { + return Object.values(checkoutInfo).reduce((acc, checkInfo) => { + (acc[checkInfo[key]] = acc[checkInfo[key]] || []).push(checkInfo); + return acc; + }, {}); +}; + +function printCheckoutInformation(checkoutInfo) { + if (checkoutInfo && Object.keys(checkoutInfo).length) { + logger.info("----------------------------------------------"); + Object.values(checkoutInfo).forEach(checkInfo => + logger.info( + `${checkInfo.group}/${checkInfo.project}:${checkInfo.branch}.${ + checkInfo.merge + ? ` It has Been merged with ${checkInfo.targetGroup}/${checkInfo.project}:${checkInfo.targetBranch}` + : "" + }` + ) + ); + logger.info("----------------------------------------------"); + Object.entries(groupBy(checkoutInfo, "branch")).forEach( + ([branch, checkoutInfoList]) => { + logger.info( + `Projects taken from branch "${branch}":${checkoutInfoList.map( + checkInfo => ` + ${checkInfo.group}/${checkInfo.project}${ + checkInfo.merge + ? `. Merged with ${checkInfo.targetGroup}/${checkInfo.project}:${checkInfo.targetBranch}` + : "" + }` + )}` + ); } - process.removeListener(EXIT, lstnr); - } + ); + logger.info("----------------------------------------------"); } - // TODO: what was the data parameter good for? - process.addListener(EXIT, function _tmp$safe_listener(data) { - for (let i = 0, length = existingListeners.length; i < length; i++) { - // let the existing listener do the garbage collection (e.g. jest sandbox) - try { - existingListeners[i](data); - } catch (err) { - // ignore - } - } - _garbageCollector(); - }); } -_safely_install_exit_listener(); -_safely_install_sigint_listener(); +module.exports = { + printCheckoutInformation +}; -/** - * Configuration options. - * - * @typedef {Object} Options - * @property {?number} tries the number of tries before give up the name generation - * @property {?string} template the "mkstemp" like filename template - * @property {?string} name fix name - * @property {?string} dir the tmp directory to use - * @property {?string} prefix prefix for the generated name - * @property {?string} postfix postfix for the generated name - * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty - */ -/** - * @typedef {Object} FileSyncObject - * @property {string} name the name of the file - * @property {string} fd the file descriptor - * @property {fileCallback} removeCallback the callback function to remove the file - */ +/***/ }), +/* 657 */, +/* 658 */, +/* 659 */, +/* 660 */, +/* 661 */, +/* 662 */, +/* 663 */, +/* 664 */, +/* 665 */, +/* 666 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * @typedef {Object} DirSyncObject - * @property {string} name the name of the directory - * @property {fileCallback} removeCallback the callback function to remove the directory - */ +let _fs +try { + _fs = __webpack_require__(598) +} catch (_) { + _fs = __webpack_require__(747) +} +const universalify = __webpack_require__(676) +const { stringify, stripBom } = __webpack_require__(356) -/** - * @callback tmpNameCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - */ +async function _readFile (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } -/** - * @callback fileCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {number} fd the file descriptor - * @param {cleanupCallback} fn the cleanup callback function - */ + const fs = options.fs || _fs -/** - * @callback dirCallback - * @param {?Error} err the error object if anything goes wrong - * @param {string} name the temporary file name - * @param {cleanupCallback} fn the cleanup callback function - */ + const shouldThrow = 'throws' in options ? options.throws : true -/** - * Removes the temporary created file or directory. - * - * @callback cleanupCallback - * @param {simpleCallback} [next] function to call after entry was removed - */ + let data = await universalify.fromCallback(fs.readFile)(file, options) -/** - * Callback function for function composition. - * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} - * - * @callback simpleCallback - */ + data = stripBom(data) -// exporting all the needed methods + let obj + try { + obj = JSON.parse(data, options ? options.reviver : null) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } -// evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will -// allow users to reconfigure the temporary directory -Object.defineProperty(module.exports, 'tmpdir', { - enumerable: true, - configurable: false, - get: function () { - return _getTmpDir(); + return obj +} + +const readFile = universalify.fromPromise(_readFile) + +function readFileSync (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } } -}); -module.exports.dir = dir; -module.exports.dirSync = dirSync; + const fs = options.fs || _fs -module.exports.file = file; -module.exports.fileSync = fileSync; + const shouldThrow = 'throws' in options ? options.throws : true -module.exports.tmpName = tmpName; -module.exports.tmpNameSync = tmpNameSync; + try { + let content = fs.readFileSync(file, options) + content = stripBom(content) + return JSON.parse(content, options.reviver) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } +} -module.exports.setGracefulCleanup = setGracefulCleanup; +async function _writeFile (file, obj, options = {}) { + const fs = options.fs || _fs + const str = stringify(obj, options) -/***/ }), -/* 804 */, -/* 805 */, -/* 806 */, -/* 807 */, -/* 808 */, -/* 809 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var Type = __webpack_require__(945); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; + await universalify.fromCallback(fs.writeFile)(file, str, options) } -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), -/* 810 */, -/* 811 */, -/* 812 */, -/* 813 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -async function auth(token) { - const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; -} +const writeFile = universalify.fromPromise(_writeFile) -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } +function writeFileSync (file, obj, options = {}) { + const fs = options.fs || _fs - return `token ${token}`; + const str = stringify(obj, options) + // not sure if fs.writeFileSync returns anything, but just in case + return fs.writeFileSync(file, str, options) } -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); +const jsonfile = { + readFile, + readFileSync, + writeFile, + writeFileSync } -const createTokenAuth = function createTokenAuth(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) - }); -}; - -exports.createTokenAuth = createTokenAuth; -//# sourceMappingURL=index.js.map +module.exports = jsonfile /***/ }), -/* 814 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = which -which.sync = whichSync +/* 667 */, +/* 668 */, +/* 669 */ +/***/ (function(module) { -var isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' +module.exports = require("util"); -var path = __webpack_require__(622) -var COLON = isWindows ? ';' : ':' -var isexe = __webpack_require__(742) +/***/ }), +/* 670 */, +/* 671 */, +/* 672 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -function getNotFoundError (cmd) { - var er = new Error('not found: ' + cmd) - er.code = 'ENOENT' +"use strict"; - return er +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 }); +const assert_1 = __webpack_require__(357); +const fs = __webpack_require__(747); +const path = __webpack_require__(622); +_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +exports.IS_WINDOWS = process.platform === 'win32'; +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; + }); } - -function getPathInfo (cmd, opt) { - var colon = opt.colon || COLON - var pathEnv = opt.path || process.env.PATH || '' - var pathExt = [''] - - pathEnv = pathEnv.split(colon) - - var pathExtExe = '' - if (isWindows) { - pathEnv.unshift(process.cwd()) - pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM') - pathExt = pathExtExe.split(colon) - - - // Always test the cmd itself first. isexe will check to make sure - // it's found in the pathExt set. - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') - } - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - if (cmd.match(/\//) || isWindows && cmd.match(/\\/)) - pathEnv = [''] - - return { - env: pathEnv, - ext: pathExt, - extExe: pathExtExe - } +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(); + }); } - -function which (cmd, opt, cb) { - if (typeof opt === 'function') { - cb = opt - opt = {} - } - - var info = getPathInfo(cmd, opt) - var pathEnv = info.env - var pathExt = info.ext - var pathExtExe = info.extExe - var found = [] - - ;(function F (i, l) { - if (i === l) { - if (opt.all && found.length) - return cb(null, found) - else - return cb(getNotFoundError(cmd)) +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'); } - - var pathPart = pathEnv[i] - if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') - pathPart = pathPart.slice(1, -1) - - var p = path.join(pathPart, cmd) - if (!pathPart && (/^\.[\\\/]/).test(cmd)) { - p = cmd.slice(0, 2) + p + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello } - ;(function E (ii, ll) { - if (ii === ll) return F(i + 1, l) - var ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, function (er, is) { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return cb(null, p + ext) - } - return E(ii + 1, ll) - }) - })(0, pathExt.length) - })(0, pathEnv.length) + return p.startsWith('/'); } +exports.isRooted = isRooted; +/** + * Recursively create a directory at `fsPath`. + * + * This implementation is optimistic, meaning it attempts to create the full + * path first, and backs up the path stack from there. + * + * @param fsPath The path to create + * @param maxDepth The maximum recursion depth + * @param depth The current recursion depth + */ +function mkdirP(fsPath, maxDepth = 1000, depth = 1) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + fsPath = path.resolve(fsPath); + if (depth >= maxDepth) + return exports.mkdir(fsPath); + try { + yield exports.mkdir(fsPath); + return; + } + catch (err) { + switch (err.code) { + case 'ENOENT': { + yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); + yield exports.mkdir(fsPath); + return; + } + default: { + let stats; + try { + stats = yield exports.stat(fsPath); + } + catch (err2) { + throw err; + } + if (!stats.isDirectory()) + throw err; + } + } + } + }); +} +exports.mkdirP = mkdirP; +/** + * 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())); +} +//# sourceMappingURL=io-util.js.map -function whichSync (cmd, opt) { - opt = opt || {} - - var info = getPathInfo(cmd, opt) - var pathEnv = info.env - var pathExt = info.ext - var pathExtExe = info.extExe - var found = [] +/***/ }), +/* 673 */, +/* 674 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - for (var i = 0, l = pathEnv.length; i < l; i ++) { - var pathPart = pathEnv[i] - if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') - pathPart = pathPart.slice(1, -1) +const { ReadYamlException } = __webpack_require__(844); +const yaml = __webpack_require__(414); - var p = path.join(pathPart, cmd) - if (!pathPart && /^\.[\\\/]/.test(cmd)) { - p = cmd.slice(0, 2) + p - } - for (var j = 0, ll = pathExt.length; j < ll; j ++) { - var cur = p + pathExt[j] - var is - try { - is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur - } - } catch (ex) {} - } +function read(fileContent) { + try { + return yaml.safeLoad(fileContent); + } catch (e) { + throw new ReadYamlException( + `error reading yaml file content. Error: ${e.message}` + ); } +} - if (opt.all && found.length) - return found +module.exports = { read }; - if (opt.nothrow) - return null - throw getNotFoundError(cmd) +/***/ }), +/* 675 */, +/* 676 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +exports.fromCallback = function (fn) { + return Object.defineProperty(function (...args) { + if (typeof args[args.length - 1] === 'function') fn.apply(this, args) + else { + return new Promise((resolve, reject) => { + fn.apply( + this, + args.concat([(err, res) => err ? reject(err) : resolve(res)]) + ) + }) + } + }, 'name', { value: fn.name }) +} + +exports.fromPromise = function (fn) { + return Object.defineProperty(function (...args) { + const cb = args[args.length - 1] + if (typeof cb !== 'function') return fn.apply(this, args) + else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb) + }, 'name', { value: fn.name }) } /***/ }), -/* 815 */, -/* 816 */ +/* 677 */, +/* 678 */, +/* 679 */, +/* 680 */, +/* 681 */ /***/ (function(module) { "use strict"; -module.exports = /^#!.*/; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; /***/ }), -/* 817 */, -/* 818 */ +/* 682 */, +/* 683 */, +/* 684 */, +/* 685 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync - -var fs = __webpack_require__(747) +"use strict"; -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT - if (!pathext) { - return true - } +/*eslint-disable no-use-before-define*/ - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true +var common = __webpack_require__(740); +var YAMLException = __webpack_require__(556); +var DEFAULT_FULL_SCHEMA = __webpack_require__(910); +var DEFAULT_SAFE_SCHEMA = __webpack_require__(830); + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; } + + result[tag] = style; } - return false + + return result; } -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } - return checkPathExt(path, options) -} -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) + return '\\' + handle + common.repeat('0', length - string.length) + string; } -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; -/***/ }), -/* 819 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + this.tag = null; + this.result = ''; -"use strict"; + this.duplicates = []; + this.usedDuplicates = null; +} +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } -var loader = __webpack_require__(457); -var dumper = __webpack_require__(685); + if (line.length && line !== '\n') result += ind; + result += line; + } -function deprecated(name) { - return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); - }; + return result; } +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} -module.exports.Type = __webpack_require__(945); -module.exports.Schema = __webpack_require__(733); -module.exports.FAILSAFE_SCHEMA = __webpack_require__(581); -module.exports.JSON_SCHEMA = __webpack_require__(23); -module.exports.CORE_SCHEMA = __webpack_require__(611); -module.exports.DEFAULT_SAFE_SCHEMA = __webpack_require__(830); -module.exports.DEFAULT_FULL_SCHEMA = __webpack_require__(910); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.safeLoad = loader.safeLoad; -module.exports.safeLoadAll = loader.safeLoadAll; -module.exports.dump = dumper.dump; -module.exports.safeDump = dumper.safeDump; -module.exports.YAMLException = __webpack_require__(556); +function testImplicitResolving(state, str) { + var index, length, type; -// Deprecated schema names from JS-YAML 2.0.x -module.exports.MINIMAL_SCHEMA = __webpack_require__(581); -module.exports.SAFE_SCHEMA = __webpack_require__(830); -module.exports.DEFAULT_SCHEMA = __webpack_require__(910); + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; -// Deprecated functions from JS-YAML 1.x.x -module.exports.scan = deprecated('scan'); -module.exports.parse = deprecated('parse'); -module.exports.compose = deprecated('compose'); -module.exports.addConstructor = deprecated('addConstructor'); + if (type.resolve(str)) { + return true; + } + } + return false; +} -/***/ }), -/* 820 */, -/* 821 */, -/* 822 */, -/* 823 */, -/* 824 */, -/* 825 */, -/* 826 */, -/* 827 */, -/* 828 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __importStar(__webpack_require__(622)); -/** - * Creates a specification for a set of files that will be downloaded - * @param artifactName the name of the artifact - * @param artifactEntries a set of container entries that describe that files that make up an artifact - * @param downloadPath the path where the artifact will be downloaded to - * @param includeRootDirectory specifies if there should be an extra directory (denoted by the artifact name) where the artifact files should be downloaded to - */ -function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { - // use a set for the directory paths so that there are no duplicates - const directories = new Set(); - const specifications = { - rootDownloadLocation: includeRootDirectory - ? path.join(downloadPath, artifactName) - : downloadPath, - directoryStructure: [], - emptyFilesToCreate: [], - filesToDownload: [] - }; - for (const entry of artifactEntries) { - // Ignore artifacts in the container that don't begin with the same name - if (entry.path.startsWith(`${artifactName}/`) || - entry.path.startsWith(`${artifactName}\\`)) { - // normalize all separators to the local OS - const normalizedPathEntry = path.normalize(entry.path); - // entry.path always starts with the artifact name, if includeRootDirectory is false, remove the name from the beginning of the path - const filePath = path.join(downloadPath, includeRootDirectory - ? normalizedPathEntry - : normalizedPathEntry.replace(artifactName, '')); - // Case insensitive folder structure maintained in the backend, not every folder is created so the 'folder' - // itemType cannot be relied upon. The file must be used to determine the directory structure - if (entry.itemType === 'file') { - // Get the directories that we need to create from the filePath for each individual file - directories.add(path.dirname(filePath)); - if (entry.fileLength === 0) { - // An empty file was uploaded, create the empty files locally so that no extra http calls are made - specifications.emptyFilesToCreate.push(filePath); - } - else { - specifications.filesToDownload.push({ - sourceLocation: entry.contentLocation, - targetPath: filePath - }); - } - } - } - } - specifications.directoryStructure = Array.from(directories); - return specifications; -} -exports.getDownloadSpecification = getDownloadSpecification; -//# sourceMappingURL=download-specification.js.map +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} -/***/ }), -/* 829 */, -/* 830 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} -"use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); -var Schema = __webpack_require__(733); + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } -module.exports = new Schema({ - include: [ - __webpack_require__(611) - ], - implicit: [ - __webpack_require__(82), - __webpack_require__(633) - ], - explicit: [ - __webpack_require__(913), - __webpack_require__(181), - __webpack_require__(947), - __webpack_require__(100) - ] -}); + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } -/***/ }), -/* 831 */, -/* 832 */, -/* 833 */, -/* 834 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} -"use strict"; -/*:nodoc:* - * class ActionHelp - * - * Support action for printing help - * This class inherided from [[Action]] - **/ +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); -var util = __webpack_require__(669); + return indentIndicator + chomp + '\n'; +} -var Action = __webpack_require__(380); +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} -// Constants -var c = __webpack_require__(45); +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; -/*:nodoc:* - * new ActionHelp(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionHelp = module.exports = function ActionHelp(options) { - options = options || {}; - if (options.defaultValue !== null) { - options.defaultValue = options.defaultValue; - } else { - options.defaultValue = c.SUPPRESS; + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; } - options.dest = (options.dest !== null ? options.dest : c.SUPPRESS); - options.nargs = 0; - Action.call(this, options); -}; -util.inherits(ActionHelp, Action); + return result; +} -/*:nodoc:* - * ActionHelp#call(parser, namespace, values, optionString) - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Print help and exit - **/ -ActionHelp.prototype.call = function (parser) { - parser.printHelp(); - parser.exit(); -}; +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; -/***/ }), -/* 835 */ -/***/ (function(module) { + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } -module.exports = require("url"); + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } -/***/ }), -/* 836 */, -/* 837 */, -/* 838 */, -/* 839 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + return result.slice(1); // drop extra \n joiner +} -"use strict"; +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } -var esprima; + return result; +} -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /* eslint-disable no-redeclare */ - /* global window */ - if (typeof window !== 'undefined') esprima = window.esprima; +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; } -var Type = __webpack_require__(945); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; -function resolveJavascriptFunction(data) { - if (data === null) return false; + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; + _result += state.dump; } - - return true; - } catch (err) { - return false; } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. } -function constructJavascriptFunction(data) { - /*jslint evil:true*/ +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); - } + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); + if (state.condenseFlow) pairBuffer += '"'; - body = ast.body[0].expression.body.range; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - if (ast.body[0].expression.body.type === 'BlockStatement') { - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; } - // ES6 arrow functions can omit the BlockStatement. In that case, just return - // the body. - /*eslint-disable no-new-func*/ - return new Function(params, 'return ' + source.slice(body[0], body[1])); -} -function representJavascriptFunction(object /*, style*/) { - return object.toString(); + state.tag = _tag; + state.dump = '{' + _result + '}'; } -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. } -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + typeList = explicit ? state.explicitTypes : state.implicitTypes; -/***/ }), -/* 840 */, -/* 841 */, -/* 842 */ -/***/ (function(__unusedmodule, exports) { + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; -"use strict"; + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + state.tag = explicit ? type.tag : '?'; -Object.defineProperty(exports, '__esModule', { value: true }); + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; -const Endpoints = { - actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamedParameters: { - name: "secret_name" + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; } - }], - createOrUpdateSecretForRepo: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamed: ["actions", "createOrUpdateRepoSecret"], - renamedParameters: { - name: "secret_name" + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } } - }], - createRegistrationToken: ["POST /repos/{owner}/{repo}/actions/runners/registration-token", {}, { - renamed: ["actions", "createRegistrationTokenForRepo"] - }], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], - createRemoveToken: ["POST /repos/{owner}/{repo}/actions/runners/remove-token", {}, { - renamed: ["actions", "createRemoveTokenForRepo"] - }], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamedParameters: { - name: "secret_name" + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } } - }], - deleteSecretFromRepo: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamed: ["actions", "deleteRepoSecret"], - renamedParameters: { - name: "secret_name" + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); } - }], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], - deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], - downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], - downloadWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { - renamed: ["actions", "downloadJobLogsForWorkflowRun"] - }], - downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - 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}"], - getPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key", {}, { - renamed: ["actions", "getRepoPublicKey"] - }], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamedParameters: { - name: "secret_name" - } - }], - getSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { - renamed: ["actions", "getRepoSecret"], - renamedParameters: { - name: "secret_name" - } - }], - getSelfHostedRunner: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { - renamed: ["actions", "getSelfHostedRunnerForRepo"] - }], - 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}"], - getWorkflowJob: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}", {}, { - renamed: ["actions", "getJobForWorkflowRun"] - }], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - 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"], - listDownloadsForSelfHostedRunnerApplication: ["GET /repos/{owner}/{repo}/actions/runners/downloads", {}, { - renamed: ["actions", "listRunnerApplicationsForRepo"] - }], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/runs", {}, { - renamed: ["actions", "listWorkflowRunsForRepo"] - }], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], - listSecretsForRepo: ["GET /repos/{owner}/{repo}/actions/secrets", {}, { - renamed: ["actions", "listRepoSecrets"] - }], - listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { - renamed: ["actions", "downloadWorkflowJobLogs"] - }], - listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], - listWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs", {}, { - renamed: ["actions", "downloadWorkflowRunLogs"] - }], - listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - removeSelfHostedRunner: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { - renamed: ["actions", "deleteSelfHostedRunnerFromRepo"] - }], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - checkStarringRepo: ["GET /user/starred/{owner}/{repo}", {}, { - renamed: ["activity", "checkRepoIsStarredByAuthenticatedUser"] - }], - 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}"], - getThreadSubscription: ["PUT /notifications", {}, { - renamed: ["activity", "getThreadSubscriptionForAuthenticatedUser"] - }], - getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listEventsForOrg: ["GET /users/{username}/events/orgs/{org}", {}, { - renamed: ["activity", "listOrgEventsForAuthenticatedUser"] - }], - listEventsForUser: ["GET /users/{username}/events", {}, { - renamed: ["activity", "listEventsForAuthenticatedUser"] - }], - listFeeds: ["GET /feeds", {}, { - renamed: ["activity", "getFeeds"] - }], - listNotifications: ["GET /notifications", {}, { - renamed: ["activity", "listNotificationsForAuthenticatedUser"] - }], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listNotificationsForRepo: ["GET /repos/{owner}/{repo}/notifications", {}, { - renamed: ["activity", "listRepoNotificationsForAuthenticatedUser"] - }], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], - listPublicEvents: ["GET /events"], - listPublicEventsForOrg: ["GET /orgs/{org}/events", {}, { - renamed: ["activity", "listPublicOrgEvents"] - }], - 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"], - markAsRead: ["PUT /notifications", {}, { - renamed: ["activity", "markNotificationsAsRead"] - }], - markNotificationsAsRead: ["PUT /notifications"], - markNotificationsAsReadForRepo: ["PUT /repos/{owner}/{repo}/notifications", {}, { - renamed: ["activity", "markRepoNotificationsAsRead"] - }], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], - starRepo: ["PUT /user/starred/{owner}/{repo}", {}, { - renamed: ["activity", "starRepoForAuthenticatedUser"] - }], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepo: ["DELETE /user/starred/{owner}/{repo}", {}, { - renamed: ["activity", "unstarRepoForAuthenticatedUser"] - }], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", { - mediaType: { - previews: ["machine-man"] - } - }], - checkAccountIsAssociatedWithAny: ["GET /marketplace_listing/accounts/{account_id}", {}, { - renamed: ["apps", "getSubscriptionPlanForAccount"] - }], - checkAccountIsAssociatedWithAnyStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}", {}, { - renamed: ["apps", "getSubscriptionPlanForAccountStubbed"] - }], - checkToken: ["POST /applications/{client_id}/token"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens", { - mediaType: { - previews: ["machine-man"] - } - }], - createInstallationToken: ["POST /app/installations/{installation_id}/access_tokens", { - mediaType: { - previews: ["machine-man"] - } - }, { - renamed: ["apps", "createInstallationAccessToken"] - }], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}", { - mediaType: { - previews: ["machine-man"] - } - }], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app", { - mediaType: { - previews: ["machine-man"] - } - }], - getBySlug: ["GET /apps/{app_slug}", { - mediaType: { - previews: ["machine-man"] - } - }], - getInstallation: ["GET /app/installations/{installation_id}", { - mediaType: { - previews: ["machine-man"] - } - }], - getOrgInstallation: ["GET /orgs/{org}/installation", { - mediaType: { - previews: ["machine-man"] - } - }], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation", { - mediaType: { - previews: ["machine-man"] + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); } - }], - getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], - getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], - getUserInstallation: ["GET /users/{username}/installation", { - mediaType: { - previews: ["machine-man"] + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } } - }], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], - listAccountsUserOrOrgOnPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts", {}, { - renamed: ["apps", "listAccountsForPlan"] - }], - listAccountsUserOrOrgOnPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", {}, { - renamed: ["apps", "listAccountsForPlanStubbed"] - }], - listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories", { - mediaType: { - previews: ["machine-man"] - } - }], - listInstallations: ["GET /app/installations", { - mediaType: { - previews: ["machine-man"] - } - }], - listInstallationsForAuthenticatedUser: ["GET /user/installations", { - mediaType: { - previews: ["machine-man"] - } - }], - listMarketplacePurchasesForAuthenticatedUser: ["GET /user/marketplace_purchases", {}, { - renamed: ["apps", "listSubscriptionsForAuthenticatedUser"] - }], - listMarketplacePurchasesForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed", {}, { - renamed: ["apps", "listSubscriptionsForAuthenticatedUserStubbed"] - }], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listRepos: ["GET /installation/repositories", { - mediaType: { - previews: ["machine-man"] - } - }, { - renamed: ["apps", "listReposAccessibleToInstallation"] - }], - listReposAccessibleToInstallation: ["GET /installation/repositories", { - mediaType: { - previews: ["machine-man"] - } - }], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", { - mediaType: { - previews: ["machine-man"] - } - }], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - revokeInstallationToken: ["DELETE /installation/token", {}, { - renamed: ["apps", "revokeInstallationAccessToken"] - }], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs", { - mediaType: { - previews: ["antiope"] - } - }], - createSuite: ["POST /repos/{owner}/{repo}/check-suites", { - mediaType: { - previews: ["antiope"] - } - }], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}", { - mediaType: { - previews: ["antiope"] - } - }], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}", { - mediaType: { - previews: ["antiope"] - } - }], - listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", { - mediaType: { - previews: ["antiope"] - } - }], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs", { - mediaType: { - previews: ["antiope"] - } - }], - listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", { - mediaType: { - previews: ["antiope"] - } - }], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites", { - mediaType: { - previews: ["antiope"] - } - }], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest", { - mediaType: { - previews: ["antiope"] - } - }], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences", { - mediaType: { - previews: ["antiope"] - } - }], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", { - mediaType: { - previews: ["antiope"] - } - }] - }, - codeScanning: { - getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] - } - }], - getConductCode: ["GET /codes_of_conduct/{key}", { - mediaType: { - previews: ["scarlet-witch"] - } - }], - getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] - } - }], - listConductCodes: ["GET /codes_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] - } - }, { - renamed: ["codesOfConduct", "getAllCodesOfConduct"] - }] - }, - 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"], - listPublicForUser: ["GET /users/{username}/gists", {}, { - renamed: ["gists", "listForUser"] - }], - 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}"], - listTemplates: ["GET /gitignore/templates", {}, { - renamed: ["gitignore", "getAllTemplates"] - }] - }, - interactions: { - addOrUpdateRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }, { - renamed: ["interactions", "setRestrictionsForOrg"] - }], - addOrUpdateRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }, { - renamed: ["interactions", "setRestrictionsForRepo"] - }], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }], - removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { - mediaType: { - previews: ["sombra"] - } - }] - }, - issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkAssignee: ["GET /repos/{owner}/{repo}/assignees/{assignee}", {}, { - renamed: ["issues", "checkUserCanBeAssigned"] - }], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/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", { - mediaType: { - previews: ["mockingbird"] - } - }], - 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"], - listMilestonesForRepo: ["GET /repos/{owner}/{repo}/milestones", {}, { - renamed: ["issues", "listMilestones"] - }], - 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}"], - removeLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { - renamed: ["issues", "removeAllLabels"] - }], - replaceAllLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { - renamed: ["issues", "setLabels"] - }], - replaceLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { - renamed: ["issues", "replaceAllLabels"] - }], - 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"], - listCommonlyUsed: ["GET /licenses", {}, { - renamed: ["licenses", "getAllCommonlyUsed"] - }] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" - } - }] - }, - meta: { - get: ["GET /meta"] - }, - migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportProgress: ["GET /repos/{owner}/{repo}/import", {}, { - renamed: ["migrations", "getImportStatus"] - }], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForAuthenticatedUser: ["GET /user/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForOrg: ["GET /orgs/{org}/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForUser: ["GET /user/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] - }, - orgs: { - addOrUpdateMembership: ["PUT /orgs/{org}/memberships/{username}", {}, { - renamed: ["orgs", "setMembershipForUser"] - }], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembership: ["GET /orgs/{org}/members/{username}", {}, { - renamed: ["orgs", "checkMembershipForUser"] - }], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembership: ["GET /orgs/{org}/public_members/{username}", {}, { - renamed: ["orgs", "checkPublicMembershipForUser"] - }], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - concealMembership: ["DELETE /orgs/{org}/public_members/{username}", {}, { - renamed: ["orgs", "removePublicMembershipForAuthenticatedUser"] - }], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], - createHook: ["POST /orgs/{org}/hooks", {}, { - renamed: ["orgs", "createWebhook"] - }], - createInvitation: ["POST /orgs/{org}/invitations"], - createWebhook: ["POST /orgs/{org}/hooks"], - deleteHook: ["DELETE /orgs/{org}/hooks/{hook_id}", {}, { - renamed: ["orgs", "deleteWebhook"] - }], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getHook: ["GET /orgs/{org}/hooks/{hook_id}", {}, { - renamed: ["orgs", "getWebhook"] - }], - getMembership: ["GET /orgs/{org}/memberships/{username}", {}, { - renamed: ["orgs", "getMembershipForUser"] - }], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations", { - mediaType: { - previews: ["machine-man"] - } - }], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listHooks: ["GET /orgs/{org}/hooks", {}, { - renamed: ["orgs", "listWebhooks"] - }], - listInstallations: ["GET /orgs/{org}/installations", { - mediaType: { - previews: ["machine-man"] - } - }, { - renamed: ["orgs", "listAppInstallations"] - }], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMemberships: ["GET /user/memberships/orgs", {}, { - renamed: ["orgs", "listMembershipsForAuthenticatedUser"] - }], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingHook: ["POST /orgs/{org}/hooks/{hook_id}/pings", {}, { - renamed: ["orgs", "pingWebhook"] - }], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - publicizeMembership: ["PUT /orgs/{org}/public_members/{username}", {}, { - renamed: ["orgs", "setPublicMembershipForAuthenticatedUser"] - }], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembership: ["DELETE /orgs/{org}/memberships/{username}", {}, { - renamed: ["orgs", "removeMembershipForUser"] - }], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateHook: ["PATCH /orgs/{org}/hooks/{hook_id}", {}, { - renamed: ["orgs", "updateWebhook"] - }], - updateMembership: ["PATCH /user/memberships/orgs/{org}", {}, { - renamed: ["orgs", "updateMembershipForAuthenticatedUser"] - }], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - createCard: ["POST /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - createColumn: ["POST /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - createForAuthenticatedUser: ["POST /user/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForOrg: ["POST /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForRepo: ["POST /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - delete: ["DELETE /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteCard: ["DELETE /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteColumn: ["DELETE /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - get: ["GET /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getCard: ["GET /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getColumn: ["GET /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { - mediaType: { - previews: ["inertia"] - } - }], - listCards: ["GET /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - listCollaborators: ["GET /projects/{project_id}/collaborators", { - mediaType: { - previews: ["inertia"] - } - }], - listColumns: ["GET /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - listForOrg: ["GET /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForRepo: ["GET /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForUser: ["GET /users/{username}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - moveCard: ["POST /projects/columns/cards/{card_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - moveColumn: ["POST /projects/columns/{column_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - reviewUserPermissionLevel: ["GET /projects/{project_id}/collaborators/{username}/permission", { - mediaType: { - previews: ["inertia"] - } - }, { - renamed: ["projects", "getPermissionForUser"] - }], - update: ["PATCH /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateCard: ["PATCH /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateColumn: ["PATCH /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { - renamed: ["pulls", "createReviewComment"] - }], - 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"], - createReviewCommentReply: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", {}, { - renamed: ["pulls", "createReplyForReviewComment"] - }], - createReviewRequest: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { - renamed: ["pulls", "requestReviewers"] - }], - deleteComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { - renamed: ["pulls", "deleteReviewComment"] - }], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - deleteReviewRequest: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { - renamed: ["pulls", "removeRequestedReviewers"] - }], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { - renamed: ["pulls", "getReviewComment"] - }], - getCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", {}, { - renamed: ["pulls", "listCommentsForReview"] - }], - 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"], - listComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { - renamed: ["pulls", "listReviewComments"] - }], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments", {}, { - renamed: ["pulls", "listReviewCommentsForRepo"] - }], - 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"], - listReviewRequests: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { - renamed: ["pulls", "listRequestedReviewers"] - }], - 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", { - mediaType: { - previews: ["lydian"] - } - }], - updateComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { - renamed: ["pulls", "updateReviewComment"] - }], - 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", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - delete: ["DELETE /reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }, { - renamed: ["reactions", "deleteLegacy"] - }], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteLegacy: ["DELETE /reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }, { - deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy" - }], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }] - }, - repos: { - acceptInvitation: ["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}"], - addDeployKey: ["POST /repos/{owner}/{repo}/keys", {}, { - renamed: ["repos", "createDeployKey"] - }], - addProtectedBranchAdminEnforcement: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { - renamed: ["repos", "setAdminBranchProtection"] - }], - addProtectedBranchAppRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps", - renamed: ["repos", "addAppAccessRestrictions"] - }], - addProtectedBranchRequiredSignatures: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }, { - renamed: ["repos", "createCommitSignatureProtection"] - }], - addProtectedBranchRequiredStatusChecksContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts", - renamed: ["repos", "addStatusCheckContexts"] - }], - addProtectedBranchTeamRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams", - renamed: ["repos", "addTeamAccessRestrictions"] - }], - addProtectedBranchUserRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users", - renamed: ["repos", "addUserAccessRestrictions"] - }], - 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" - }], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - 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"], - createHook: ["POST /repos/{owner}/{repo}/hooks", {}, { - renamed: ["repos", "createWebhook"] - }], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateFile: ["PUT /repos/{owner}/{repo}/contents/{path}", {}, { - renamed: ["repos", "createOrUpdateFileContents"] - }], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}", {}, { - renamed: ["repos", "createCommitStatus"] - }], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { - mediaType: { - previews: ["baptiste"] - } - }], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["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"], - 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", { - mediaType: { - previews: ["zzzax"] - } - }], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], - deleteDownload: ["DELETE /repos/{owner}/{repo}/downloads/{download_id}"], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteHook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}", {}, { - renamed: ["repos", "deleteWebhook"] - }], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - 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}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - disablePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }, { - renamed: ["repos", "deletePagesSite"] - }], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - downloadArchive: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - enablePagesSite: ["POST /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }, { - renamed: ["repos", "createPagesSite"] - }], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], - getArchiveLink: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}", {}, { - renamed: ["repos", "downloadArchive"] - }], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], - 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", { - mediaType: { - previews: ["zzzax"] - } - }], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContents: ["GET /repos/{owner}/{repo}/contents/{path}", {}, { - renamed: ["repos", "getContent"] - }], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], - getDownload: ["GET /repos/{owner}/{repo}/downloads/{download_id}"], - getHook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}", {}, { - renamed: ["repos", "getWebhook"] - }], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getProtectedBranchAdminEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { - renamed: ["repos", "getAdminBranchProtection"] - }], - getProtectedBranchPullRequestReviewEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { - renamed: ["repos", "getPullRequestReviewProtection"] - }], - getProtectedBranchRequiredSignatures: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }, { - renamed: ["repos", "getCommitSignatureProtection"] - }], - getProtectedBranchRequiredStatusChecks: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "getStatusChecksProtection"] - }], - getProtectedBranchRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { - renamed: ["repos", "getAccessRestrictions"] - }], - 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"], - 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}"], - 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}"], - list: ["GET /user/repos", {}, { - renamed: ["repos", "listForAuthenticatedUser"] - }], - listAssetsForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets", {}, { - renamed: ["repos", "listReleaseAssets"] - }], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { - mediaType: { - previews: ["groot"] - } - }], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - listCommitComments: ["GET /repos/{owner}/{repo}/comments", {}, { - renamed: ["repos", "listCommitCommentsForRepo"] - }], - 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"], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listDownloads: ["GET /repos/{owner}/{repo}/downloads"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listHooks: ["GET /repos/{owner}/{repo}/hooks", {}, { - renamed: ["repos", "listWebhooks"] - }], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listProtectedBranchRequiredStatusChecksContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - renamed: ["repos", "getAllStatusCheckContexts"] - }], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { - mediaType: { - previews: ["groot"] - } - }], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses", {}, { - renamed: ["repos", "listCommitStatusesForRef"] - }], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }, { - renamed: ["repos", "getAllTopics"] - }], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - pingHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings", {}, { - renamed: ["repos", "pingWebhook"] - }], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection", {}, { - renamed: ["repos", "deleteBranchProtection"] - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}", {}, { - renamed: ["repos", "deleteDeployKey"] - }], - removeProtectedBranchAdminEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { - renamed: ["repos", "deleteAdminBranchProtection"] - }], - removeProtectedBranchAppRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps", - renamed: ["repos", "removeAppAccessRestrictions"] - }], - removeProtectedBranchPullRequestReviewEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { - renamed: ["repos", "deletePullRequestReviewProtection"] - }], - removeProtectedBranchRequiredSignatures: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }, { - renamed: ["repos", "deleteCommitSignatureProtection"] - }], - removeProtectedBranchRequiredStatusChecks: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "removeStatusChecksProtection"] - }], - removeProtectedBranchRequiredStatusChecksContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts", - renamed: ["repos", "removeStatusCheckContexts"] - }], - removeProtectedBranchRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { - renamed: ["repos", "deleteAccessRestrictions"] - }], - removeProtectedBranchTeamRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams", - renamed: ["repos", "removeTeamAccessRestrictions"] - }], - removeProtectedBranchUserRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users", - renamed: ["repos", "removeUserAccessRestrictions"] - }], - 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" - }], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - replaceProtectedBranchAppRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps", - renamed: ["repos", "setAppAccessRestrictions"] - }], - replaceProtectedBranchRequiredStatusChecksContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts", - renamed: ["repos", "setStatusCheckContexts"] - }], - replaceProtectedBranchTeamRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams", - renamed: ["repos", "setTeamAccessRestrictions"] - }], - replaceProtectedBranchUserRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users", - renamed: ["repos", "setUserAccessRestrictions"] - }], - replaceTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }, { - renamed: ["repos", "replaceAllTopics"] - }], - requestPageBuild: ["POST /repos/{owner}/{repo}/pages/builds", {}, { - renamed: ["repos", "requestPagesBuild"] - }], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - retrieveCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile", {}, { - renamed: ["repos", "getCommunityProfileMetrics"] - }], - 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" - }], - testPushHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests", {}, { - renamed: ["repos", "testPushWebhook"] - }], - 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}"], - updateHook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}", {}, { - renamed: ["repos", "updateWebhook"] - }], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updateProtectedBranchPullRequestReviewEnforcement: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { - renamed: ["repos", "updatePullRequestReviewProtection"] - }], - updateProtectedBranchRequiredStatusChecks: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusChecksProtection"] - }], - 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}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - 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", { - mediaType: { - previews: ["cloak"] - } - }], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateMembershipInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { - renamed: ["teams", "addOrUpdateMembershipForUserInOrg"] - }], - addOrUpdateProjectInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }, { - renamed: ["teams", "addOrUpdateProjectPermissionsInOrg"] - }], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - addOrUpdateRepoInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { - renamed: ["teams", "addOrUpdateRepoPermissionsInOrg"] - }], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkManagesRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { - renamed: ["teams", "checkPermissionsForRepoInOrg"] - }], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - 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}"], - getMembershipInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { - renamed: ["teams", "getMembershipForUserInOrg"] - }], - 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", { - mediaType: { - previews: ["inertia"] + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; + + +/***/ }), +/* 686 */ +/***/ (function(__unusedmodule, exports, __webpack_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()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(__webpack_require__(87)); +const events = __importStar(__webpack_require__(759)); +const child = __importStar(__webpack_require__(129)); +const path = __importStar(__webpack_require__(622)); +const io = __importStar(__webpack_require__(1)); +const ioUtil = __importStar(__webpack_require__(672)); +/* 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); + } + strBuffer = s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + } + } + _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) => { + 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); + }); + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + const 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); + } + this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + const 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); + } + 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 = 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 + +/***/ }), +/* 687 */, +/* 688 */, +/* 689 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +try { + var util = __webpack_require__(669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(315); +} + + +/***/ }), +/* 690 */, +/* 691 */, +/* 692 */ +/***/ (function(__unusedmodule, 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; + + +/***/ }), +/* 693 */, +/* 694 */, +/* 695 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const { stringify } = __webpack_require__(356) +const { outputFile } = __webpack_require__(517) + +async function outputJson (file, data, options = {}) { + const str = stringify(data, options) + + await outputFile(file, str, options) +} + +module.exports = outputJson + + +/***/ }), +/* 696 */, +/* 697 */ +/***/ (function(module) { + +"use strict"; + +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); + + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; + + +/***/ }), +/* 698 */, +/* 699 */, +/* 700 */, +/* 701 */, +/* 702 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const { getTree, getTreeForProject } = __webpack_require__(101); +const { readDefinitionFile } = __webpack_require__(799); +const { parentChainFromNode } = __webpack_require__(636); +const { treatUrl } = __webpack_require__(824); + +module.exports = { + getTree, + getTreeForProject, + readDefinitionFile, + parentChainFromNode, + treatUrl +}; + + +/***/ }), +/* 703 */, +/* 704 */, +/* 705 */, +/* 706 */, +/* 707 */, +/* 708 */, +/* 709 */, +/* 710 */, +/* 711 */, +/* 712 */, +/* 713 */, +/* 714 */, +/* 715 */, +/* 716 */, +/* 717 */, +/* 718 */, +/* 719 */, +/* 720 */, +/* 721 */, +/* 722 */, +/* 723 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const u = __webpack_require__(676).fromCallback +const rimraf = __webpack_require__(474) + +module.exports = { + remove: u(rimraf), + removeSync: rimraf.sync +} + + +/***/ }), +/* 724 */, +/* 725 */, +/* 726 */, +/* 727 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +const u = __webpack_require__(676).fromPromise +const { makeDir: _makeDir, makeDirSync } = __webpack_require__(54) +const makeDir = u(_makeDir) + +module.exports = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync +} + + +/***/ }), +/* 728 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), +/* 729 */, +/* 730 */, +/* 731 */ +/***/ (function(module) { + +module.exports = {"name":"build-chain-action","version":"2.0.0","description":"GitHub action to define action chains","main":"src/lib/api.js","author":"Enrique Mingorance Cano ","license":"SEE LICENSE IN LICENSE","private":true,"bin":{"build-chain-action":"./bin/build-chain.js"},"scripts":{"test":"jest","it":"node it/it.js","locktt":"locktt","lint":"eslint .","prettier":"prettier -l src/** test/**/*.js","prettier-write":"prettier --write .","lint-final":"npm run prettier && npm run lint","prepublish":"npm run lint && npm run test","ncc-build":"ncc build bin/build-chain.js"},"git-pre-hooks":{"pre-commit":"npm run prettier && npm run ncc-build && git add dist/index.js","pre-push":"npm ci"},"dependencies":{"@actions/artifact":"^0.3.5","@actions/core":"^1.1.3","@actions/exec":"^1.0.4","@actions/glob":"^0.1.0","@kie/build-chain-configuration-reader":"^0.0.4","@octokit/rest":"^17.6.0","argparse":"^1.0.7","fs-extra":"^9.0.0","js-yaml":"^3.14.0","tmp":"^0.2.1"},"devDependencies":{"@zeit/ncc":"^0.22.3","dotenv":"^8.2.0","eslint":"^7.10.0","eslint-config-google":"^0.14.0","eslint-config-prettier":"^6.11.0","eslint-config-standard":"^14.1.1","eslint-plugin-import":"^2.22.0","eslint-plugin-jest":"^23.19.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^3.1.4","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1","git-pre-hooks":"^1.2.1","jest":"^25.5.1","prettier":"^2.0.5"},"jest":{"testEnvironment":"node","modulePathIgnorePatterns":["locally_execution/"]},"prettier":{"trailingComma":"none","arrowParens":"avoid"},"engines":{"node":">= 12.18.0"}}; + +/***/ }), +/* 732 */, +/* 733 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +/*eslint-disable max-len*/ + +var common = __webpack_require__(740); +var YAMLException = __webpack_require__(556); +var Type = __webpack_require__(945); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); } - }], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeMembershipInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { - renamed: ["teams", "removeMembershipForUserInOrg"] - }], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - reviewProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; + + +/***/ }), +/* 734 */, +/* 735 */, +/* 736 */, +/* 737 */, +/* 738 */, +/* 739 */, +/* 740 */ +/***/ (function(module) { + +"use strict"; + + + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; + + +/***/ }), +/* 741 */, +/* 742 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var fs = __webpack_require__(747) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __webpack_require__(818) +} else { + core = __webpack_require__(197) +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false } - }, { - renamed: ["teams", "checkPermissionsForProjectInOrg"] - }], - 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"], - addEmails: ["POST /user/emails", {}, { - renamed: ["users", "addEmailsForAuthenticated"] - }], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowing: ["GET /user/following/{username}", {}, { - renamed: ["users", "checkPersonIsFollowedByAuthenticated"] - }], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKey: ["POST /user/gpg_keys", {}, { - renamed: ["users", "createGpgKeyForAuthenticated"] - }], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], - createPublicKey: ["POST /user/keys", {}, { - renamed: ["users", "createPublicSshKeyForAuthenticated"] - }], - createPublicSshKeyForAuthenticated: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails"], - deleteEmails: ["DELETE /user/emails", {}, { - renamed: ["users", "deleteEmailsForAuthenticated"] - }], - deleteGpgKey: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "deleteGpgKeyForAuthenticated"] - }], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicKey: ["DELETE /user/keys/{key_id}", {}, { - renamed: ["users", "deletePublicSshKeyForAuthenticated"] - }], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKey: ["GET /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "getGpgKeyForAuthenticated"] - }], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicKey: ["GET /user/keys/{key_id}", {}, { - renamed: ["users", "getPublicSshKeyForAuthenticated"] - }], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], - list: ["GET /users"], - listBlocked: ["GET /user/blocks", {}, { - renamed: ["users", "listBlockedByAuthenticated"] - }], - listBlockedByAuthenticated: ["GET /user/blocks"], - listEmails: ["GET /user/emails", {}, { - renamed: ["users", "listEmailsForAuthenticated"] - }], - listEmailsForAuthenticated: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForAuthenticatedUser: ["GET /user/following", {}, { - renamed: ["users", "listFollowedByAuthenticated"] - }], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeys: ["GET /user/gpg_keys", {}, { - renamed: ["users", "listGpgKeysForAuthenticated"] - }], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmails: ["GET /user/public_emails", {}, { - renamed: ["users", "listPublicEmailsForAuthenticatedUser"] - }], - listPublicEmailsForAuthenticated: ["GET /user/public_emails"], - listPublicKeys: ["GET /user/keys", {}, { - renamed: ["users", "listPublicSshKeysForAuthenticated"] - }], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], - togglePrimaryEmailVisibility: ["PATCH /user/email/visibility", {}, { - renamed: ["users", "setPrimaryEmailVisibilityForAuthenticated"] - }], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + + +/***/ }), +/* 743 */, +/* 744 */, +/* 745 */, +/* 746 */, +/* 747 */ +/***/ (function(module) { + +module.exports = require("fs"); + +/***/ }), +/* 748 */, +/* 749 */, +/* 750 */, +/* 751 */, +/* 752 */, +/* 753 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var endpoint = __webpack_require__(385); +var universalUserAgent = __webpack_require__(392); +var isPlainObject = __webpack_require__(588); +var nodeFetch = _interopDefault(__webpack_require__(454)); +var requestError = __webpack_require__(463); + +const VERSION = "5.4.9"; + +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +function fetchWrapper(requestOptions) { + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + + let headers = {}; + let status; + let url; + const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; + return fetch(requestOptions.url, Object.assign({ + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + redirect: requestOptions.redirect + }, requestOptions.request)).then(response => { + url = response.url; + status = response.status; + + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + + if (status === 204 || status === 205) { + return; + } // GitHub API returns 200 for HEAD requests + + + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + + throw new requestError.RequestError(response.statusText, status, { + headers, + request: requestOptions + }); + } + + if (status === 304) { + throw new requestError.RequestError("Not modified", status, { + headers, + request: requestOptions + }); + } + + if (status >= 400) { + return response.text().then(message => { + const error = new requestError.RequestError(message, status, { + headers, + request: requestOptions + }); + + try { + let responseBody = JSON.parse(error.message); + Object.assign(error, responseBody); + let errors = responseBody.errors; // Assumption `errors` would always be in Array format + + error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); + } catch (e) {// ignore, see octokit/rest.js#684 + } + + throw error; + }); + } + + const contentType = response.headers.get("content-type"); + + if (/application\/json/.test(contentType)) { + return response.json(); + } + + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + + return getBufferResponse(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) { + throw error; + } + + throw new requestError.RequestError(error.message, 500, { + headers, + request: requestOptions + }); + }); +} + +function withDefaults(oldEndpoint, newDefaults) { + const endpoint = oldEndpoint.defaults(newDefaults); + + const newApi = function (route, parameters) { + const endpointOptions = endpoint.merge(route, parameters); + + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint.parse(endpointOptions)); + } + + const request = (route, parameters) => { + return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + }; + + Object.assign(request, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); + return endpointOptions.request.hook(request, endpointOptions); + }; + + return Object.assign(newApi, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); +} + +const request = withDefaults(endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } +}); + +exports.request = request; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 754 */, +/* 755 */, +/* 756 */, +/* 757 */, +/* 758 */, +/* 759 */ +/***/ (function(module) { + +module.exports = require("events"); + +/***/ }), +/* 760 */, +/* 761 */ +/***/ (function(module) { + +module.exports = require("zlib"); + +/***/ }), +/* 762 */, +/* 763 */ +/***/ (function(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) +} + + +/***/ }), +/* 764 */, +/* 765 */ +/***/ (function(module) { + +module.exports = require("process"); + +/***/ }), +/* 766 */, +/* 767 */, +/* 768 */ +/***/ (function(module) { + +"use strict"; + +module.exports = function (x) { + var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); + var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); + + if (x[x.length - 1] === lf) { + x = x.slice(0, x.length - 1); + } + + if (x[x.length - 1] === cr) { + x = x.slice(0, x.length - 1); + } + + return x; +}; + + +/***/ }), +/* 769 */, +/* 770 */, +/* 771 */, +/* 772 */, +/* 773 */, +/* 774 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const u = __webpack_require__(676).fromCallback +module.exports = { + copy: u(__webpack_require__(595)) +} + + +/***/ }), +/* 775 */, +/* 776 */, +/* 777 */, +/* 778 */, +/* 779 */, +/* 780 */, +/* 781 */, +/* 782 */, +/* 783 */, +/* 784 */, +/* 785 */, +/* 786 */, +/* 787 */ +/***/ (function(module) { + +module.exports = { + warn: "warn", + error: "error", + ignore: "ignore" +}; + + +/***/ }), +/* 788 */, +/* 789 */, +/* 790 */, +/* 791 */, +/* 792 */, +/* 793 */, +/* 794 */, +/* 795 */, +/* 796 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var osName = _interopDefault(__webpack_require__(2)); + +function getUserAgent() { + try { + return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`; + } catch (error) { + if (/wmic os get Caption/.test(error.message)) { + return "Windows "; + } + + return ""; + } +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 797 */, +/* 798 */, +/* 799 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const fs = __webpack_require__(747); + +const { getUrlContent } = __webpack_require__(593); +const { treatUrl } = __webpack_require__(824); +const { + validateDefinition, + validateDependencies +} = __webpack_require__(492); +const { read: readYaml } = __webpack_require__(674); + +/** + * It will return back the definition file plus dependencies as an object + * + * @param {string} file - The definition file. It can be a URL or a in the filesystem. + * @param {Object} urlPlaceHolders the url place holders to replace url. This is needed in case either the definition file or the dependencies file are loaded from a URL + */ +async function readDefinitionFile(file, urlPlaceHolders = {}) { + return file.startsWith("http") + ? readDefinitionFileFromUrl(file, urlPlaceHolders) + : readDefinitionFileFromFile(file, urlPlaceHolders); +} + +/** + * reads definition from a file and returns back the yaml object + * @param {String} filePath the definition file path + * @param {Object} urlPlaceHolders the url place holders to replace url + */ +async function readDefinitionFileFromFile(filePath, urlPlaceHolders) { + const defintionFileContent = fs.readFileSync(filePath, "utf8"); + return loadYaml( + readYaml(defintionFileContent), + filePath.substring(0, filePath.lastIndexOf("/")), + urlPlaceHolders + ); +} + +/** + * reads definition from a url and returns back the yaml object + * @param {String} url the url to the definition file + * @param {Object} urlPlaceHolders the url place holders to replace url + */ +async function readDefinitionFileFromUrl(url, urlPlaceHolders) { + const treatedUrl = treatUrl(url, urlPlaceHolders); + const definitionYaml = readYaml(await getUrlContent(treatedUrl)); + validateDefinition(definitionYaml); + // In case the dependencies are defined as relative path we should download treating definition faile + if ( + !Array.isArray(definitionYaml.dependencies) && + !definitionYaml.dependencies.startsWith("http") + ) { + const dependenciesContent = await getUrlContent( + `${treatedUrl.substring(0, treatedUrl.lastIndexOf("/"))}/${ + definitionYaml.dependencies + }` + ); + fs.writeFileSync(definitionYaml.dependencies, dependenciesContent); + } + return loadYaml(definitionYaml, "./", urlPlaceHolders); +} + +/** + * it loads dependencies content from a external file/url and returns back the yaml object + * @param {Object} definitionYaml the definition yaml object + * @param {String} definitionFileFolder the definition folder path + * @param {Object} urlPlaceHolders the url place holders to replace url + */ +async function loadYaml(definitionYaml, definitionFileFolder, urlPlaceHolders) { + validateDefinition(definitionYaml); + if (!Array.isArray(definitionYaml.dependencies)) { + const dependenciesFileContent = definitionYaml.dependencies.startsWith( + "http" + ) + ? await getUrlContent( + treatUrl(definitionYaml.dependencies, urlPlaceHolders) + ) + : fs.readFileSync( + `${definitionFileFolder}/${definitionYaml.dependencies}`, + "utf8" + ); + const dependenciesYaml = readYaml(dependenciesFileContent); + validateDependencies(dependenciesYaml); + definitionYaml.dependencies = dependenciesYaml.dependencies; + } + return definitionYaml; +} + +module.exports = { readDefinitionFile }; + + +/***/ }), +/* 800 */, +/* 801 */, +/* 802 */, +/* 803 */, +/* 804 */, +/* 805 */, +/* 806 */, +/* 807 */, +/* 808 */, +/* 809 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var Type = __webpack_require__(945); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + + +/***/ }), +/* 810 */, +/* 811 */, +/* 812 */, +/* 813 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +async function auth(token) { + const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; + return { + type: "token", + token: token, + tokenType + }; +} + +/** + * Prefix token for usage in the Authorization header + * + * @param token OAuth token or JSON Web Token + */ +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + + return `token ${token}`; +} + +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +const createTokenAuth = function createTokenAuth(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) + }); +}; + +exports.createTokenAuth = createTokenAuth; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 814 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = which +which.sync = whichSync + +var isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' + +var path = __webpack_require__(622) +var COLON = isWindows ? ';' : ':' +var isexe = __webpack_require__(742) + +function getNotFoundError (cmd) { + var er = new Error('not found: ' + cmd) + er.code = 'ENOENT' + + return er +} + +function getPathInfo (cmd, opt) { + var colon = opt.colon || COLON + var pathEnv = opt.path || process.env.PATH || '' + var pathExt = [''] + + pathEnv = pathEnv.split(colon) + + var pathExtExe = '' + if (isWindows) { + pathEnv.unshift(process.cwd()) + pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM') + pathExt = pathExtExe.split(colon) + + + // Always test the cmd itself first. isexe will check to make sure + // it's found in the pathExt set. + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + if (cmd.match(/\//) || isWindows && cmd.match(/\\/)) + pathEnv = [''] + + return { + env: pathEnv, + ext: pathExt, + extExe: pathExtExe + } +} + +function which (cmd, opt, cb) { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + + var info = getPathInfo(cmd, opt) + var pathEnv = info.env + var pathExt = info.ext + var pathExtExe = info.extExe + var found = [] + + ;(function F (i, l) { + if (i === l) { + if (opt.all && found.length) + return cb(null, found) + else + return cb(getNotFoundError(cmd)) + } + + var pathPart = pathEnv[i] + if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') + pathPart = pathPart.slice(1, -1) + + var p = path.join(pathPart, cmd) + if (!pathPart && (/^\.[\\\/]/).test(cmd)) { + p = cmd.slice(0, 2) + p + } + ;(function E (ii, ll) { + if (ii === ll) return F(i + 1, l) + var ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, function (er, is) { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return cb(null, p + ext) + } + return E(ii + 1, ll) + }) + })(0, pathExt.length) + })(0, pathEnv.length) +} + +function whichSync (cmd, opt) { + opt = opt || {} + + var info = getPathInfo(cmd, opt) + var pathEnv = info.env + var pathExt = info.ext + var pathExtExe = info.extExe + var found = [] + + for (var i = 0, l = pathEnv.length; i < l; i ++) { + var pathPart = pathEnv[i] + if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') + pathPart = pathPart.slice(1, -1) + + var p = path.join(pathPart, cmd) + if (!pathPart && /^\.[\\\/]/.test(cmd)) { + p = cmd.slice(0, 2) + p + } + for (var j = 0, ll = pathExt.length; j < ll; j ++) { + var cur = p + pathExt[j] + var is + try { + is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +} + + +/***/ }), +/* 815 */, +/* 816 */ +/***/ (function(module) { + +"use strict"; + +module.exports = /^#!.*/; + + +/***/ }), +/* 817 */, +/* 818 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(747) + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} + + +/***/ }), +/* 819 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + + +var loader = __webpack_require__(457); +var dumper = __webpack_require__(685); + + +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; +} + + +module.exports.Type = __webpack_require__(945); +module.exports.Schema = __webpack_require__(733); +module.exports.FAILSAFE_SCHEMA = __webpack_require__(581); +module.exports.JSON_SCHEMA = __webpack_require__(23); +module.exports.CORE_SCHEMA = __webpack_require__(611); +module.exports.DEFAULT_SAFE_SCHEMA = __webpack_require__(830); +module.exports.DEFAULT_FULL_SCHEMA = __webpack_require__(910); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.safeLoad = loader.safeLoad; +module.exports.safeLoadAll = loader.safeLoadAll; +module.exports.dump = dumper.dump; +module.exports.safeDump = dumper.safeDump; +module.exports.YAMLException = __webpack_require__(556); + +// Deprecated schema names from JS-YAML 2.0.x +module.exports.MINIMAL_SCHEMA = __webpack_require__(581); +module.exports.SAFE_SCHEMA = __webpack_require__(830); +module.exports.DEFAULT_SCHEMA = __webpack_require__(910); + +// Deprecated functions from JS-YAML 1.x.x +module.exports.scan = deprecated('scan'); +module.exports.parse = deprecated('parse'); +module.exports.compose = deprecated('compose'); +module.exports.addConstructor = deprecated('addConstructor'); + + +/***/ }), +/* 820 */, +/* 821 */, +/* 822 */, +/* 823 */, +/* 824 */ +/***/ (function(module) { + +/** + * it treats the url in case it contains + * @param {String} url a http(s)://whatever.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/whateverfile.txt format, where place olders are optional and can be placed anywhere on the string + * @param {Object} placeHolders the key/values to replace url's place holders + */ +function treatUrl(url, placeHolders) { + let result = url; + Object.entries(placeHolders).forEach( + ([key, value]) => (result = result.replace(`$\{${key}}`, value)) + ); + return result; +} + +module.exports = { treatUrl }; + + +/***/ }), +/* 825 */, +/* 826 */, +/* 827 */, +/* 828 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __importStar(__webpack_require__(622)); +/** + * Creates a specification for a set of files that will be downloaded + * @param artifactName the name of the artifact + * @param artifactEntries a set of container entries that describe that files that make up an artifact + * @param downloadPath the path where the artifact will be downloaded to + * @param includeRootDirectory specifies if there should be an extra directory (denoted by the artifact name) where the artifact files should be downloaded to + */ +function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { + // use a set for the directory paths so that there are no duplicates + const directories = new Set(); + const specifications = { + rootDownloadLocation: includeRootDirectory + ? path.join(downloadPath, artifactName) + : downloadPath, + directoryStructure: [], + emptyFilesToCreate: [], + filesToDownload: [] + }; + for (const entry of artifactEntries) { + // Ignore artifacts in the container that don't begin with the same name + if (entry.path.startsWith(`${artifactName}/`) || + entry.path.startsWith(`${artifactName}\\`)) { + // normalize all separators to the local OS + const normalizedPathEntry = path.normalize(entry.path); + // entry.path always starts with the artifact name, if includeRootDirectory is false, remove the name from the beginning of the path + const filePath = path.join(downloadPath, includeRootDirectory + ? normalizedPathEntry + : normalizedPathEntry.replace(artifactName, '')); + // Case insensitive folder structure maintained in the backend, not every folder is created so the 'folder' + // itemType cannot be relied upon. The file must be used to determine the directory structure + if (entry.itemType === 'file') { + // Get the directories that we need to create from the filePath for each individual file + directories.add(path.dirname(filePath)); + if (entry.fileLength === 0) { + // An empty file was uploaded, create the empty files locally so that no extra http calls are made + specifications.emptyFilesToCreate.push(filePath); + } + else { + specifications.filesToDownload.push({ + sourceLocation: entry.contentLocation, + targetPath: filePath + }); + } + } + } + } + specifications.directoryStructure = Array.from(directories); + return specifications; +} +exports.getDownloadSpecification = getDownloadSpecification; +//# sourceMappingURL=download-specification.js.map + +/***/ }), +/* 829 */, +/* 830 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + + + + +var Schema = __webpack_require__(733); + + +module.exports = new Schema({ + include: [ + __webpack_require__(611) + ], + implicit: [ + __webpack_require__(841), + __webpack_require__(633) + ], + explicit: [ + __webpack_require__(913), + __webpack_require__(181), + __webpack_require__(947), + __webpack_require__(100) + ] +}); + + +/***/ }), +/* 831 */, +/* 832 */, +/* 833 */, +/* 834 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; +/*:nodoc:* + * class ActionHelp + * + * Support action for printing help + * This class inherided from [[Action]] + **/ + + +var util = __webpack_require__(669); + +var Action = __webpack_require__(380); + +// Constants +var c = __webpack_require__(45); + +/*:nodoc:* + * new ActionHelp(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionHelp = module.exports = function ActionHelp(options) { + options = options || {}; + if (options.defaultValue !== null) { + options.defaultValue = options.defaultValue; + } else { + options.defaultValue = c.SUPPRESS; } + options.dest = (options.dest !== null ? options.dest : c.SUPPRESS); + options.nargs = 0; + Action.call(this, options); + }; +util.inherits(ActionHelp, Action); -const VERSION = "3.17.0"; +/*:nodoc:* + * ActionHelp#call(parser, namespace, values, optionString) + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Print help and exit + **/ +ActionHelp.prototype.call = function (parser) { + parser.printHelp(); + parser.exit(); +}; -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - 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); +/***/ }), +/* 835 */ +/***/ (function(module) { + +module.exports = require("url"); + +/***/ }), +/* 836 */, +/* 837 */, +/* 838 */, +/* 839 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} - if (!newMethods[scope]) { - newMethods[scope] = {}; - } +var Type = __webpack_require__(945); - const scopeMethods = newMethods[scope]; +function resolveJavascriptFunction(data) { + if (data === null) return false; - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; } - } - return newMethods; + return true; + } catch (err) { + return false; + } } -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); +function constructJavascriptFunction(data) { + /*jslint evil:true*/ - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: undefined - }); - return requestWithDefaults(options); - } // NOTE: there are currently no deprecations. But we keep the code - // below for future reference + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); - } + body = ast.body[0].expression.body.range; - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - // There is currently no deprecated parameter that is optional, - // so we never hit the else branch below at this point. +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} - /* istanbul ignore else */ - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); - if (!(alias in options)) { - options[alias] = options[name]; - } - delete options[name]; - } - } +/***/ }), +/* 840 */, +/* 841 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 +"use strict"; - return requestWithDefaults(...args); - } +var Type = __webpack_require__(945); - return Object.assign(withDecorations, requestWithDefaults); -} +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day -/** - * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary - * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is - * done, we will remove the registerEndpoints methods and return the methods - * directly as with the other plugins. At that point we will also remove the - * legacy workarounds and deprecations. - * - * See the plan at - * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1 - */ +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute -function restEndpointMethods(octokit) { - return endpointsToMethods(octokit, Endpoints); +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; } -restEndpointMethods.VERSION = VERSION; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); -/***/ }), -/* 843 */, -/* 844 */, -/* 845 */, -/* 846 */, -/* 847 */, -/* 848 */, -/* 849 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (match === null) throw new Error('Date resolve error'); -"use strict"; + // match: [1] year [2] month [3] day + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); -const u = __webpack_require__(676).fromCallback -const path = __webpack_require__(622) -const fs = __webpack_require__(598) -const _mkdirs = __webpack_require__(727) -const mkdirs = _mkdirs.mkdirs -const mkdirsSync = _mkdirs.mkdirsSync + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } -const _symlinkPaths = __webpack_require__(930) -const symlinkPaths = _symlinkPaths.symlinkPaths -const symlinkPathsSync = _symlinkPaths.symlinkPathsSync + // match: [4] hour [5] minute [6] second [7] fraction -const _symlinkType = __webpack_require__(975) -const symlinkType = _symlinkType.symlinkType -const symlinkTypeSync = _symlinkType.symlinkTypeSync + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); -const pathExists = __webpack_require__(322).pathExists + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } -function createSymlink (srcpath, dstpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - pathExists(dstpath, (err, destinationExists) => { - if (err) return callback(err) - if (destinationExists) return callback(null) - symlinkPaths(srcpath, dstpath, (err, relative) => { - if (err) return callback(err) - srcpath = relative.toDst - symlinkType(relative.toCwd, type, (err, type) => { - if (err) return callback(err) - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) - mkdirs(dir, err => { - if (err) return callback(err) - fs.symlink(srcpath, dstpath, type, callback) - }) - }) - }) - }) - }) -} + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } -function createSymlinkSync (srcpath, dstpath, type) { - const destinationExists = fs.existsSync(dstpath) - if (destinationExists) return undefined + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - const relative = symlinkPathsSync(srcpath, dstpath) - srcpath = relative.toDst - type = symlinkTypeSync(relative.toCwd, type) - const dir = path.dirname(dstpath) - const exists = fs.existsSync(dir) - if (exists) return fs.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir) - return fs.symlinkSync(srcpath, dstpath, type) + if (delta) date.setTime(date.getTime() - delta); + + return date; } -module.exports = { - createSymlink: u(createSymlink), - createSymlinkSync +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); } +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + /***/ }), -/* 850 */, -/* 851 */, -/* 852 */, -/* 853 */, -/* 854 */, -/* 855 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 842 */ +/***/ (function(__unusedmodule, 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()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __importStar(__webpack_require__(747)); -const core = __importStar(__webpack_require__(393)); -const zlib = __importStar(__webpack_require__(761)); -const utils_1 = __webpack_require__(870); -const url_1 = __webpack_require__(835); -const status_reporter_1 = __webpack_require__(176); -const perf_hooks_1 = __webpack_require__(630); -const http_manager_1 = __webpack_require__(624); -const config_variables_1 = __webpack_require__(401); -class DownloadHttpClient { - constructor() { - this.downloadHttpManager = new http_manager_1.HttpManager(config_variables_1.getDownloadFileConcurrency(), '@actions/artifact-download'); - // downloads are usually significantly faster than uploads so display status information every second - this.statusReporter = new status_reporter_1.StatusReporter(1000); - } - /** - * Gets a list of all artifacts that are in a specific container - */ - listArtifacts() { - return __awaiter(this, void 0, void 0, function* () { - const artifactUrl = utils_1.getArtifactUrl(); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.downloadHttpManager.getClient(0); - const headers = utils_1.getDownloadHeaders('application/json'); - const response = yield client.get(artifactUrl, headers); - const body = yield response.readBody(); - if (utils_1.isSuccessStatusCode(response.message.statusCode) && body) { - return JSON.parse(body); - } - utils_1.displayHttpDiagnostics(response); - throw new Error(`Unable to list artifacts for the run. Resource Url ${artifactUrl}`); - }); - } - /** - * Fetches a set of container items that describe the contents of an artifact - * @param artifactName the name of the artifact - * @param containerUrl the artifact container URL for the run - */ - getContainerItems(artifactName, containerUrl) { - return __awaiter(this, void 0, void 0, function* () { - // the itemPath search parameter controls which containers will be returned - const resourceUrl = new url_1.URL(containerUrl); - resourceUrl.searchParams.append('itemPath', artifactName); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.downloadHttpManager.getClient(0); - const headers = utils_1.getDownloadHeaders('application/json'); - const response = yield client.get(resourceUrl.toString(), headers); - const body = yield response.readBody(); - if (utils_1.isSuccessStatusCode(response.message.statusCode) && body) { - return JSON.parse(body); - } - utils_1.displayHttpDiagnostics(response); - throw new Error(`Unable to get ContainersItems from ${resourceUrl}`); - }); - } - /** - * Concurrently downloads all the files that are part of an artifact - * @param downloadItems information about what items to download and where to save them - */ - downloadSingleArtifact(downloadItems) { - return __awaiter(this, void 0, void 0, function* () { - const DOWNLOAD_CONCURRENCY = config_variables_1.getDownloadFileConcurrency(); - // limit the number of files downloaded at a single time - core.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); - const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; - let currentFile = 0; - let downloadedFiles = 0; - core.info(`Total number of files that will be downloaded: ${downloadItems.length}`); - this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); - this.statusReporter.start(); - yield Promise.all(parallelDownloads.map((index) => __awaiter(this, void 0, void 0, function* () { - while (currentFile < downloadItems.length) { - const currentFileToDownload = downloadItems[currentFile]; - currentFile += 1; - const startTime = perf_hooks_1.performance.now(); - yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); - if (core.isDebug()) { - core.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); - } - this.statusReporter.incrementProcessedCount(); - } - }))) - .catch(error => { - throw new Error(`Unable to download the artifact: ${error}`); - }) - .finally(() => { - this.statusReporter.stop(); - // safety dispose all connections - this.downloadHttpManager.disposeAndReplaceAllClients(); - }); - }); - } - /** - * Downloads an individual file - * @param httpClientIndex the index of the http client that is used to make all of the calls - * @param artifactLocation origin location where a file will be downloaded from - * @param downloadPath destination location for the file being downloaded - */ - downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { - return __awaiter(this, void 0, void 0, function* () { - let retryCount = 0; - const retryLimit = config_variables_1.getRetryLimit(); - const destinationStream = fs.createWriteStream(downloadPath); - const headers = utils_1.getDownloadHeaders('application/json', true, true); - // a single GET request is used to download a file - const makeDownloadRequest = () => __awaiter(this, void 0, void 0, function* () { - const client = this.downloadHttpManager.getClient(httpClientIndex); - return yield client.get(artifactLocation, headers); - }); - // check the response headers to determine if the file was compressed using gzip - const isGzip = (incomingHeaders) => { - return ('content-encoding' in incomingHeaders && - incomingHeaders['content-encoding'] === 'gzip'); - }; - // Increments the current retry count and then checks if the retry limit has been reached - // If there have been too many retries, fail so the download stops. If there is a retryAfterValue value provided, - // it will be used - const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { - retryCount++; - if (retryCount > retryLimit) { - return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); - } - else { - this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); - if (retryAfterValue) { - // Back off by waiting the specified time denoted by the retry-after header - core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); - yield new Promise(resolve => setTimeout(resolve, retryAfterValue)); - } - else { - // Back off using an exponential value that depends on the retry count - const backoffTime = utils_1.getExponentialRetryTimeInMilliseconds(retryCount); - core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); - yield new Promise(resolve => setTimeout(resolve, backoffTime)); - } - core.info(`Finished backoff for retry #${retryCount}, continuing with download`); - } - }); - // keep trying to download a file until a retry limit has been reached - while (retryCount <= retryLimit) { - let response; - try { - response = yield makeDownloadRequest(); - } - catch (error) { - // if an error is caught, it is usually indicative of a timeout so retry the download - core.info('An error occurred while attempting to download a file'); - // eslint-disable-next-line no-console - console.log(error); - // increment the retryCount and use exponential backoff to wait before making the next request - yield backOff(); - continue; - } - if (utils_1.isSuccessStatusCode(response.message.statusCode)) { - // The body contains the contents of the file however calling response.readBody() causes all the content to be converted to a string - // which can cause some gzip encoded data to be lost - // Instead of using response.readBody(), response.message is a readableStream that can be directly used to get the raw body contents - return this.pipeResponseToFile(response, destinationStream, isGzip(response.message.headers)); - } - else if (utils_1.isRetryableStatusCode(response.message.statusCode)) { - core.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); - // if a throttled status code is received, try to get the retryAfter header value, else differ to standard exponential backoff - utils_1.isThrottledStatusCode(response.message.statusCode) - ? yield backOff(utils_1.tryGetRetryAfterValueTimeInMilliseconds(response.message.headers)) - : yield backOff(); - } - else { - // Some unexpected response code, fail immediately and stop the download - utils_1.displayHttpDiagnostics(response); - return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); - } - } - }); - } - /** - * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary - * @param response the http response received when downloading a file - * @param destinationStream the stream where the file should be written to - * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it - */ - pipeResponseToFile(response, destinationStream, isGzip) { - return __awaiter(this, void 0, void 0, function* () { - yield new Promise((resolve, reject) => { - if (isGzip) { - const gunzip = zlib.createGunzip(); - response.message - .pipe(gunzip) - .pipe(destinationStream) - .on('close', () => { - resolve(); - }) - .on('error', error => { - core.error(`An error has been encountered while decompressing and writing a downloaded file to ${destinationStream.path}`); - reject(error); - }); - } - else { - response.message - .pipe(destinationStream) - .on('close', () => { - resolve(); - }) - .on('error', error => { - core.error(`An error has been encountered while writing a downloaded file to ${destinationStream.path}`); - reject(error); - }); - } - }); - return; - }); - } -} -exports.DownloadHttpClient = DownloadHttpClient; -//# sourceMappingURL=download-http-client.js.map -/***/ }), -/* 856 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored +Object.defineProperty(exports, '__esModule', { value: true }); + +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + createOrUpdateSecretForRepo: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "createOrUpdateRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + createRegistrationToken: ["POST /repos/{owner}/{repo}/actions/runners/registration-token", {}, { + renamed: ["actions", "createRegistrationTokenForRepo"] + }], + createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], + createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createRemoveToken: ["POST /repos/{owner}/{repo}/actions/runners/remove-token", {}, { + renamed: ["actions", "createRemoveTokenForRepo"] + }], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], + deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + deleteSecretFromRepo: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "deleteRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], + deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], + downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], + downloadWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { + renamed: ["actions", "downloadJobLogsForWorkflowRun"] + }], + downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + 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}"], + getPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key", {}, { + renamed: ["actions", "getRepoPublicKey"] + }], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + getSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "getRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + getSelfHostedRunner: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { + renamed: ["actions", "getSelfHostedRunnerForRepo"] + }], + 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}"], + getWorkflowJob: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}", {}, { + renamed: ["actions", "getJobForWorkflowRun"] + }], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + 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"], + listDownloadsForSelfHostedRunnerApplication: ["GET /repos/{owner}/{repo}/actions/runners/downloads", {}, { + renamed: ["actions", "listRunnerApplicationsForRepo"] + }], + listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/runs", {}, { + renamed: ["actions", "listWorkflowRunsForRepo"] + }], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], + listSecretsForRepo: ["GET /repos/{owner}/{repo}/actions/secrets", {}, { + renamed: ["actions", "listRepoSecrets"] + }], + listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { + renamed: ["actions", "downloadWorkflowJobLogs"] + }], + listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], + listWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs", {}, { + renamed: ["actions", "downloadWorkflowRunLogs"] + }], + listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + removeSelfHostedRunner: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { + renamed: ["actions", "deleteSelfHostedRunnerFromRepo"] + }], + setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + checkStarringRepo: ["GET /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "checkRepoIsStarredByAuthenticatedUser"] + }], + 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}"], + getThreadSubscription: ["PUT /notifications", {}, { + renamed: ["activity", "getThreadSubscriptionForAuthenticatedUser"] + }], + getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listEventsForOrg: ["GET /users/{username}/events/orgs/{org}", {}, { + renamed: ["activity", "listOrgEventsForAuthenticatedUser"] + }], + listEventsForUser: ["GET /users/{username}/events", {}, { + renamed: ["activity", "listEventsForAuthenticatedUser"] + }], + listFeeds: ["GET /feeds", {}, { + renamed: ["activity", "getFeeds"] + }], + listNotifications: ["GET /notifications", {}, { + renamed: ["activity", "listNotificationsForAuthenticatedUser"] + }], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listNotificationsForRepo: ["GET /repos/{owner}/{repo}/notifications", {}, { + renamed: ["activity", "listRepoNotificationsForAuthenticatedUser"] + }], + listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listPublicEvents: ["GET /events"], + listPublicEventsForOrg: ["GET /orgs/{org}/events", {}, { + renamed: ["activity", "listPublicOrgEvents"] + }], + 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"], + markAsRead: ["PUT /notifications", {}, { + renamed: ["activity", "markNotificationsAsRead"] + }], + markNotificationsAsRead: ["PUT /notifications"], + markNotificationsAsReadForRepo: ["PUT /repos/{owner}/{repo}/notifications", {}, { + renamed: ["activity", "markRepoNotificationsAsRead"] + }], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + starRepo: ["PUT /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "starRepoForAuthenticatedUser"] + }], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepo: ["DELETE /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "unstarRepoForAuthenticatedUser"] + }], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + checkAccountIsAssociatedWithAny: ["GET /marketplace_listing/accounts/{account_id}", {}, { + renamed: ["apps", "getSubscriptionPlanForAccount"] + }], + checkAccountIsAssociatedWithAnyStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}", {}, { + renamed: ["apps", "getSubscriptionPlanForAccountStubbed"] + }], + checkToken: ["POST /applications/{client_id}/token"], + createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] + } + }], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens", { + mediaType: { + previews: ["machine-man"] + } + }], + createInstallationToken: ["POST /app/installations/{installation_id}/access_tokens", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["apps", "createInstallationAccessToken"] + }], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app", { + mediaType: { + previews: ["machine-man"] + } + }], + getBySlug: ["GET /apps/{app_slug}", { + mediaType: { + previews: ["machine-man"] + } + }], + getInstallation: ["GET /app/installations/{installation_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + getOrgInstallation: ["GET /orgs/{org}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], + getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getUserInstallation: ["GET /users/{username}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], + listAccountsUserOrOrgOnPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts", {}, { + renamed: ["apps", "listAccountsForPlan"] + }], + listAccountsUserOrOrgOnPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", {}, { + renamed: ["apps", "listAccountsForPlanStubbed"] + }], + listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories", { + mediaType: { + previews: ["machine-man"] + } + }], + listInstallations: ["GET /app/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listInstallationsForAuthenticatedUser: ["GET /user/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listMarketplacePurchasesForAuthenticatedUser: ["GET /user/marketplace_purchases", {}, { + renamed: ["apps", "listSubscriptionsForAuthenticatedUser"] + }], + listMarketplacePurchasesForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed", {}, { + renamed: ["apps", "listSubscriptionsForAuthenticatedUserStubbed"] + }], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listRepos: ["GET /installation/repositories", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["apps", "listReposAccessibleToInstallation"] + }], + listReposAccessibleToInstallation: ["GET /installation/repositories", { + mediaType: { + previews: ["machine-man"] + } + }], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + revokeInstallationToken: ["DELETE /installation/token", {}, { + renamed: ["apps", "revokeInstallationAccessToken"] + }], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + createSuite: ["POST /repos/{owner}/{repo}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}", { + mediaType: { + previews: ["antiope"] + } + }], + listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", { + mediaType: { + previews: ["antiope"] + } + }], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest", { + mediaType: { + previews: ["antiope"] + } + }], + setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences", { + mediaType: { + previews: ["antiope"] + } + }], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }] + }, + codeScanning: { + getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getConductCode: ["GET /codes_of_conduct/{key}", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + listConductCodes: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }, { + renamed: ["codesOfConduct", "getAllCodesOfConduct"] + }] + }, + 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"], + listPublicForUser: ["GET /users/{username}/gists", {}, { + renamed: ["gists", "listForUser"] + }], + 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}"], + listTemplates: ["GET /gitignore/templates", {}, { + renamed: ["gitignore", "getAllTemplates"] + }] + }, + interactions: { + addOrUpdateRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }, { + renamed: ["interactions", "setRestrictionsForOrg"] + }], + addOrUpdateRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }, { + renamed: ["interactions", "setRestrictionsForRepo"] + }], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }] + }, + issues: { + addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkAssignee: ["GET /repos/{owner}/{repo}/assignees/{assignee}", {}, { + renamed: ["issues", "checkUserCanBeAssigned"] + }], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/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", { + mediaType: { + previews: ["mockingbird"] + } + }], + 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"], + listMilestonesForRepo: ["GET /repos/{owner}/{repo}/milestones", {}, { + renamed: ["issues", "listMilestones"] + }], + 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}"], + removeLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "removeAllLabels"] + }], + replaceAllLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "setLabels"] + }], + replaceLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "replaceAllLabels"] + }], + 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"], + listCommonlyUsed: ["GET /licenses", {}, { + renamed: ["licenses", "getAllCommonlyUsed"] + }] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: ["POST /markdown/raw", { + headers: { + "content-type": "text/plain; charset=utf-8" + } + }] + }, + meta: { + get: ["GET /meta"] + }, + migrations: { + cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], + getImportProgress: ["GET /repos/{owner}/{repo}/import", {}, { + renamed: ["migrations", "getImportStatus"] + }], + getImportStatus: ["GET /repos/{owner}/{repo}/import"], + getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForAuthenticatedUser: ["GET /user/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForOrg: ["GET /orgs/{org}/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForUser: ["GET /user/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], + setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: ["PUT /repos/{owner}/{repo}/import"], + unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + updateImport: ["PATCH /repos/{owner}/{repo}/import"] + }, + orgs: { + addOrUpdateMembership: ["PUT /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "setMembershipForUser"] + }], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembership: ["GET /orgs/{org}/members/{username}", {}, { + renamed: ["orgs", "checkMembershipForUser"] + }], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembership: ["GET /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "checkPublicMembershipForUser"] + }], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + concealMembership: ["DELETE /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "removePublicMembershipForAuthenticatedUser"] + }], + convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + createHook: ["POST /orgs/{org}/hooks", {}, { + renamed: ["orgs", "createWebhook"] + }], + createInvitation: ["POST /orgs/{org}/invitations"], + createWebhook: ["POST /orgs/{org}/hooks"], + deleteHook: ["DELETE /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "deleteWebhook"] + }], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getHook: ["GET /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "getWebhook"] + }], + getMembership: ["GET /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "getMembershipForUser"] + }], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listHooks: ["GET /orgs/{org}/hooks", {}, { + renamed: ["orgs", "listWebhooks"] + }], + listInstallations: ["GET /orgs/{org}/installations", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["orgs", "listAppInstallations"] + }], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMemberships: ["GET /user/memberships/orgs", {}, { + renamed: ["orgs", "listMembershipsForAuthenticatedUser"] + }], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingHook: ["POST /orgs/{org}/hooks/{hook_id}/pings", {}, { + renamed: ["orgs", "pingWebhook"] + }], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + publicizeMembership: ["PUT /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "setPublicMembershipForAuthenticatedUser"] + }], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembership: ["DELETE /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "removeMembershipForUser"] + }], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], + removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateHook: ["PATCH /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "updateWebhook"] + }], + updateMembership: ["PATCH /user/memberships/orgs/{org}", {}, { + renamed: ["orgs", "updateMembershipForAuthenticatedUser"] + }], + updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + createCard: ["POST /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + createColumn: ["POST /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + createForAuthenticatedUser: ["POST /user/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForOrg: ["POST /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForRepo: ["POST /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + delete: ["DELETE /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteCard: ["DELETE /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteColumn: ["DELETE /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + get: ["GET /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getCard: ["GET /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getColumn: ["GET /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { + mediaType: { + previews: ["inertia"] + } + }], + listCards: ["GET /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + listCollaborators: ["GET /projects/{project_id}/collaborators", { + mediaType: { + previews: ["inertia"] + } + }], + listColumns: ["GET /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + listForOrg: ["GET /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForRepo: ["GET /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForUser: ["GET /users/{username}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + moveCard: ["POST /projects/columns/cards/{card_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + moveColumn: ["POST /projects/columns/{column_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + reviewUserPermissionLevel: ["GET /projects/{project_id}/collaborators/{username}/permission", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["projects", "getPermissionForUser"] + }], + update: ["PATCH /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateCard: ["PATCH /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateColumn: ["PATCH /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { + renamed: ["pulls", "createReviewComment"] + }], + 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"], + createReviewCommentReply: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", {}, { + renamed: ["pulls", "createReplyForReviewComment"] + }], + createReviewRequest: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "requestReviewers"] + }], + deleteComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "deleteReviewComment"] + }], + deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + deleteReviewRequest: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "removeRequestedReviewers"] + }], + dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "getReviewComment"] + }], + getCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", {}, { + renamed: ["pulls", "listCommentsForReview"] + }], + 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"], + listComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { + renamed: ["pulls", "listReviewComments"] + }], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments", {}, { + renamed: ["pulls", "listReviewCommentsForRepo"] + }], + 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"], + listReviewRequests: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "listRequestedReviewers"] + }], + 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", { + mediaType: { + previews: ["lydian"] + } + }], + updateComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "updateReviewComment"] + }], + 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", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + delete: ["DELETE /reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }, { + renamed: ["reactions", "deleteLegacy"] + }], + deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteLegacy: ["DELETE /reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }, { + deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy" + }], + listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }] + }, + repos: { + acceptInvitation: ["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}"], + addDeployKey: ["POST /repos/{owner}/{repo}/keys", {}, { + renamed: ["repos", "createDeployKey"] + }], + addProtectedBranchAdminEnforcement: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "setAdminBranchProtection"] + }], + addProtectedBranchAppRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "addAppAccessRestrictions"] + }], + addProtectedBranchRequiredSignatures: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "createCommitSignatureProtection"] + }], + addProtectedBranchRequiredStatusChecksContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "addStatusCheckContexts"] + }], + addProtectedBranchTeamRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "addTeamAccessRestrictions"] + }], + addProtectedBranchUserRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "addUserAccessRestrictions"] + }], + 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" + }], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + 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"], + createHook: ["POST /repos/{owner}/{repo}/hooks", {}, { + renamed: ["repos", "createWebhook"] + }], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateFile: ["PUT /repos/{owner}/{repo}/contents/{path}", {}, { + renamed: ["repos", "createOrUpdateFileContents"] + }], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}", {}, { + renamed: ["repos", "createCommitStatus"] + }], + createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { + mediaType: { + previews: ["baptiste"] + } + }], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: ["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"], + 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", { + mediaType: { + previews: ["zzzax"] + } + }], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteDownload: ["DELETE /repos/{owner}/{repo}/downloads/{download_id}"], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteHook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "deleteWebhook"] + }], + deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + 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}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + disablePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }, { + renamed: ["repos", "deletePagesSite"] + }], + disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + downloadArchive: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}"], + enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + enablePagesSite: ["POST /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }, { + renamed: ["repos", "createPagesSite"] + }], + enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], + getAllTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getArchiveLink: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}", {}, { + renamed: ["repos", "downloadArchive"] + }], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + 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", { + mediaType: { + previews: ["zzzax"] + } + }], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContents: ["GET /repos/{owner}/{repo}/contents/{path}", {}, { + renamed: ["repos", "getContent"] + }], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], + getDownload: ["GET /repos/{owner}/{repo}/downloads/{download_id}"], + getHook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "getWebhook"] + }], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getProtectedBranchAdminEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "getAdminBranchProtection"] + }], + getProtectedBranchPullRequestReviewEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "getPullRequestReviewProtection"] + }], + getProtectedBranchRequiredSignatures: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "getCommitSignatureProtection"] + }], + getProtectedBranchRequiredStatusChecks: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "getStatusChecksProtection"] + }], + getProtectedBranchRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { + renamed: ["repos", "getAccessRestrictions"] + }], + 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"], + 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}"], + 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}"], + list: ["GET /user/repos", {}, { + renamed: ["repos", "listForAuthenticatedUser"] + }], + listAssetsForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets", {}, { + renamed: ["repos", "listReleaseAssets"] + }], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { + mediaType: { + previews: ["groot"] + } + }], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommitComments: ["GET /repos/{owner}/{repo}/comments", {}, { + renamed: ["repos", "listCommitCommentsForRepo"] + }], + 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"], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listDownloads: ["GET /repos/{owner}/{repo}/downloads"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listHooks: ["GET /repos/{owner}/{repo}/hooks", {}, { + renamed: ["repos", "listWebhooks"] + }], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listProtectedBranchRequiredStatusChecksContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + renamed: ["repos", "getAllStatusCheckContexts"] + }], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { + mediaType: { + previews: ["groot"] + } + }], + listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses", {}, { + renamed: ["repos", "listCommitStatusesForRef"] + }], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }, { + renamed: ["repos", "getAllTopics"] + }], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + pingHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings", {}, { + renamed: ["repos", "pingWebhook"] + }], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + removeBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection", {}, { + renamed: ["repos", "deleteBranchProtection"] + }], + removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], + removeDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}", {}, { + renamed: ["repos", "deleteDeployKey"] + }], + removeProtectedBranchAdminEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "deleteAdminBranchProtection"] + }], + removeProtectedBranchAppRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "removeAppAccessRestrictions"] + }], + removeProtectedBranchPullRequestReviewEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "deletePullRequestReviewProtection"] + }], + removeProtectedBranchRequiredSignatures: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "deleteCommitSignatureProtection"] + }], + removeProtectedBranchRequiredStatusChecks: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "removeStatusChecksProtection"] + }], + removeProtectedBranchRequiredStatusChecksContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "removeStatusCheckContexts"] + }], + removeProtectedBranchRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { + renamed: ["repos", "deleteAccessRestrictions"] + }], + removeProtectedBranchTeamRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "removeTeamAccessRestrictions"] + }], + removeProtectedBranchUserRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "removeUserAccessRestrictions"] + }], + 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" + }], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + replaceProtectedBranchAppRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "setAppAccessRestrictions"] + }], + replaceProtectedBranchRequiredStatusChecksContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "setStatusCheckContexts"] + }], + replaceProtectedBranchTeamRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "setTeamAccessRestrictions"] + }], + replaceProtectedBranchUserRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "setUserAccessRestrictions"] + }], + replaceTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }, { + renamed: ["repos", "replaceAllTopics"] + }], + requestPageBuild: ["POST /repos/{owner}/{repo}/pages/builds", {}, { + renamed: ["repos", "requestPagesBuild"] + }], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + retrieveCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile", {}, { + renamed: ["repos", "getCommunityProfileMetrics"] + }], + 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" + }], + testPushHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests", {}, { + renamed: ["repos", "testPushWebhook"] + }], + 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}"], + updateHook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "updateWebhook"] + }], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], + updateProtectedBranchPullRequestReviewEnforcement: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "updatePullRequestReviewProtection"] + }], + updateProtectedBranchRequiredStatusChecks: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "updateStatusChecksProtection"] + }], + 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}"], + updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + 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", { + mediaType: { + previews: ["cloak"] + } + }], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + teams: { + addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], + addOrUpdateMembershipInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "addOrUpdateMembershipForUserInOrg"] + }], + addOrUpdateProjectInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["teams", "addOrUpdateProjectPermissionsInOrg"] + }], + addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + addOrUpdateRepoInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { + renamed: ["teams", "addOrUpdateRepoPermissionsInOrg"] + }], + addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + checkManagesRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { + renamed: ["teams", "checkPermissionsForRepoInOrg"] + }], + checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + 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}"], + getMembershipInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "getMembershipForUserInOrg"] + }], + 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", { + mediaType: { + previews: ["inertia"] + } + }], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], + removeMembershipInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "removeMembershipForUserInOrg"] + }], + removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + reviewProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["teams", "checkPermissionsForProjectInOrg"] + }], + 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"], + addEmails: ["POST /user/emails", {}, { + renamed: ["users", "addEmailsForAuthenticated"] + }], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowing: ["GET /user/following/{username}", {}, { + renamed: ["users", "checkPersonIsFollowedByAuthenticated"] + }], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKey: ["POST /user/gpg_keys", {}, { + renamed: ["users", "createGpgKeyForAuthenticated"] + }], + createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], + createPublicKey: ["POST /user/keys", {}, { + renamed: ["users", "createPublicSshKeyForAuthenticated"] + }], + createPublicSshKeyForAuthenticated: ["POST /user/keys"], + deleteEmailForAuthenticated: ["DELETE /user/emails"], + deleteEmails: ["DELETE /user/emails", {}, { + renamed: ["users", "deleteEmailsForAuthenticated"] + }], + deleteGpgKey: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "deleteGpgKeyForAuthenticated"] + }], + deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicKey: ["DELETE /user/keys/{key_id}", {}, { + renamed: ["users", "deletePublicSshKeyForAuthenticated"] + }], + deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKey: ["GET /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "getGpgKeyForAuthenticated"] + }], + getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicKey: ["GET /user/keys/{key_id}", {}, { + renamed: ["users", "getPublicSshKeyForAuthenticated"] + }], + getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], + list: ["GET /users"], + listBlocked: ["GET /user/blocks", {}, { + renamed: ["users", "listBlockedByAuthenticated"] + }], + listBlockedByAuthenticated: ["GET /user/blocks"], + listEmails: ["GET /user/emails", {}, { + renamed: ["users", "listEmailsForAuthenticated"] + }], + listEmailsForAuthenticated: ["GET /user/emails"], + listFollowedByAuthenticated: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForAuthenticatedUser: ["GET /user/following", {}, { + renamed: ["users", "listFollowedByAuthenticated"] + }], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeys: ["GET /user/gpg_keys", {}, { + renamed: ["users", "listGpgKeysForAuthenticated"] + }], + listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmails: ["GET /user/public_emails", {}, { + renamed: ["users", "listPublicEmailsForAuthenticatedUser"] + }], + listPublicEmailsForAuthenticated: ["GET /user/public_emails"], + listPublicKeys: ["GET /user/keys", {}, { + renamed: ["users", "listPublicSshKeysForAuthenticated"] + }], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: ["GET /user/keys"], + setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], + togglePrimaryEmailVisibility: ["PATCH /user/email/visibility", {}, { + renamed: ["users", "setPrimaryEmailVisibilityForAuthenticated"] + }], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; + +const VERSION = "3.17.0"; + +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} + for (const [scope, endpoints] of Object.entries(endpointsMap)) { + 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); -var path = __webpack_require__(622) -var minimatch = __webpack_require__(571) -var isAbsolute = __webpack_require__(681) -var Minimatch = minimatch.Minimatch + if (!newMethods[scope]) { + newMethods[scope] = {}; + } -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} + const scopeMethods = newMethods[scope]; -function alphasort (a, b) { - return a.localeCompare(b) + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; + } + + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + } + } + + return newMethods; } -function setupIgnores (self, options) { - self.ignore = options.ignore || [] +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] + function withDecorations(...args) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined + }); + return requestWithDefaults(options); + } // NOTE: there are currently no deprecations. But we keep the code + // below for future reference + + + 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) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + const options = requestWithDefaults.endpoint.merge(...args); + + for (const [name, alias] of Object.entries(decorations.renamedParameters)) { + // There is currently no deprecated parameter that is optional, + // so we never hit the else branch below at this point. + + /* istanbul ignore else */ + if (name in options) { + octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); + + if (!(alias in options)) { + options[alias] = options[name]; + } + + delete options[name]; + } + } + + return requestWithDefaults(options); + } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + + + return requestWithDefaults(...args); } + + return Object.assign(withDecorations, requestWithDefaults); } -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } +/** + * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary + * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is + * done, we will remove the registerEndpoints methods and return the methods + * directly as with the other plugins. At that point we will also remove the + * legacy workarounds and deprecations. + * + * See the plan at + * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1 + */ - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } +function restEndpointMethods(octokit) { + return endpointsToMethods(octokit, Endpoints); +} +restEndpointMethods.VERSION = VERSION; + +exports.restEndpointMethods = restEndpointMethods; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 843 */, +/* 844 */ +/***/ (function(module) { + +function ReadYamlException(message) { + this.message = message; + this.name = "ReadYamlException"; } -function setopts (self, pattern, options) { - if (!options) - options = {} +module.exports = { ReadYamlException }; + + +/***/ }), +/* 845 */, +/* 846 */, +/* 847 */, +/* 848 */, +/* 849 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute +const u = __webpack_require__(676).fromCallback +const path = __webpack_require__(622) +const fs = __webpack_require__(598) +const _mkdirs = __webpack_require__(727) +const mkdirs = _mkdirs.mkdirs +const mkdirsSync = _mkdirs.mkdirsSync - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) +const _symlinkPaths = __webpack_require__(930) +const symlinkPaths = _symlinkPaths.symlinkPaths +const symlinkPathsSync = _symlinkPaths.symlinkPathsSync - setupIgnores(self, options) +const _symlinkType = __webpack_require__(975) +const symlinkType = _symlinkType.symlinkType +const symlinkTypeSync = _symlinkType.symlinkTypeSync - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } +const pathExists = __webpack_require__(322).pathExists - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") +function createSymlink (srcpath, dstpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount + pathExists(dstpath, (err, destinationExists) => { + if (err) return callback(err) + if (destinationExists) return callback(null) + symlinkPaths(srcpath, dstpath, (err, relative) => { + if (err) return callback(err) + srcpath = relative.toDst + symlinkType(relative.toCwd, type, (err, type) => { + if (err) return callback(err) + const dir = path.dirname(dstpath) + pathExists(dir, (err, dirExists) => { + if (err) return callback(err) + if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) + mkdirs(dir, err => { + if (err) return callback(err) + fs.symlink(srcpath, dstpath, type, callback) + }) + }) + }) + }) + }) +} - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true +function createSymlinkSync (srcpath, dstpath, type) { + const destinationExists = fs.existsSync(dstpath) + if (destinationExists) return undefined - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options + const relative = symlinkPathsSync(srcpath, dstpath) + srcpath = relative.toDst + type = symlinkTypeSync(relative.toCwd, type) + const dir = path.dirname(dstpath) + const exists = fs.existsSync(dir) + if (exists) return fs.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir) + return fs.symlinkSync(srcpath, dstpath, type) } -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) +module.exports = { + createSymlink: u(createSymlink), + createSymlinkSync +} - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } - } - if (!nou) - all = Object.keys(all) +/***/ }), +/* 850 */, +/* 851 */, +/* 852 */, +/* 853 */, +/* 854 */, +/* 855 */ +/***/ (function(__unusedmodule, exports, __webpack_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()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __importStar(__webpack_require__(747)); +const core = __importStar(__webpack_require__(393)); +const zlib = __importStar(__webpack_require__(761)); +const utils_1 = __webpack_require__(870); +const url_1 = __webpack_require__(835); +const status_reporter_1 = __webpack_require__(176); +const perf_hooks_1 = __webpack_require__(630); +const http_manager_1 = __webpack_require__(624); +const config_variables_1 = __webpack_require__(401); +class DownloadHttpClient { + constructor() { + this.downloadHttpManager = new http_manager_1.HttpManager(config_variables_1.getDownloadFileConcurrency(), '@actions/artifact-download'); + // downloads are usually significantly faster than uploads so display status information every second + this.statusReporter = new status_reporter_1.StatusReporter(1000); + } + /** + * Gets a list of all artifacts that are in a specific container + */ + listArtifacts() { + return __awaiter(this, void 0, void 0, function* () { + const artifactUrl = utils_1.getArtifactUrl(); + // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately + const client = this.downloadHttpManager.getClient(0); + const headers = utils_1.getDownloadHeaders('application/json'); + const response = yield client.get(artifactUrl, headers); + const body = yield response.readBody(); + if (utils_1.isSuccessStatusCode(response.message.statusCode) && body) { + return JSON.parse(body); + } + utils_1.displayHttpDiagnostics(response); + throw new Error(`Unable to list artifacts for the run. Resource Url ${artifactUrl}`); + }); + } + /** + * Fetches a set of container items that describe the contents of an artifact + * @param artifactName the name of the artifact + * @param containerUrl the artifact container URL for the run + */ + getContainerItems(artifactName, containerUrl) { + return __awaiter(this, void 0, void 0, function* () { + // the itemPath search parameter controls which containers will be returned + const resourceUrl = new url_1.URL(containerUrl); + resourceUrl.searchParams.append('itemPath', artifactName); + // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately + const client = this.downloadHttpManager.getClient(0); + const headers = utils_1.getDownloadHeaders('application/json'); + const response = yield client.get(resourceUrl.toString(), headers); + const body = yield response.readBody(); + if (utils_1.isSuccessStatusCode(response.message.statusCode) && body) { + return JSON.parse(body); + } + utils_1.displayHttpDiagnostics(response); + throw new Error(`Unable to get ContainersItems from ${resourceUrl}`); + }); + } + /** + * Concurrently downloads all the files that are part of an artifact + * @param downloadItems information about what items to download and where to save them + */ + downloadSingleArtifact(downloadItems) { + return __awaiter(this, void 0, void 0, function* () { + const DOWNLOAD_CONCURRENCY = config_variables_1.getDownloadFileConcurrency(); + // limit the number of files downloaded at a single time + core.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); + const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; + let currentFile = 0; + let downloadedFiles = 0; + core.info(`Total number of files that will be downloaded: ${downloadItems.length}`); + this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); + this.statusReporter.start(); + yield Promise.all(parallelDownloads.map((index) => __awaiter(this, void 0, void 0, function* () { + while (currentFile < downloadItems.length) { + const currentFileToDownload = downloadItems[currentFile]; + currentFile += 1; + const startTime = perf_hooks_1.performance.now(); + yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); + if (core.isDebug()) { + core.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); + } + this.statusReporter.incrementProcessedCount(); + } + }))) + .catch(error => { + throw new Error(`Unable to download the artifact: ${error}`); + }) + .finally(() => { + this.statusReporter.stop(); + // safety dispose all connections + this.downloadHttpManager.disposeAndReplaceAllClients(); + }); + }); + } + /** + * Downloads an individual file + * @param httpClientIndex the index of the http client that is used to make all of the calls + * @param artifactLocation origin location where a file will be downloaded from + * @param downloadPath destination location for the file being downloaded + */ + downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { + return __awaiter(this, void 0, void 0, function* () { + let retryCount = 0; + const retryLimit = config_variables_1.getRetryLimit(); + const destinationStream = fs.createWriteStream(downloadPath); + const headers = utils_1.getDownloadHeaders('application/json', true, true); + // a single GET request is used to download a file + const makeDownloadRequest = () => __awaiter(this, void 0, void 0, function* () { + const client = this.downloadHttpManager.getClient(httpClientIndex); + return yield client.get(artifactLocation, headers); + }); + // check the response headers to determine if the file was compressed using gzip + const isGzip = (incomingHeaders) => { + return ('content-encoding' in incomingHeaders && + incomingHeaders['content-encoding'] === 'gzip'); + }; + // Increments the current retry count and then checks if the retry limit has been reached + // If there have been too many retries, fail so the download stops. If there is a retryAfterValue value provided, + // it will be used + const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { + retryCount++; + if (retryCount > retryLimit) { + return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); + } + else { + this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); + if (retryAfterValue) { + // Back off by waiting the specified time denoted by the retry-after header + core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); + yield new Promise(resolve => setTimeout(resolve, retryAfterValue)); + } + else { + // Back off using an exponential value that depends on the retry count + const backoffTime = utils_1.getExponentialRetryTimeInMilliseconds(retryCount); + core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); + yield new Promise(resolve => setTimeout(resolve, backoffTime)); + } + core.info(`Finished backoff for retry #${retryCount}, continuing with download`); + } + }); + // keep trying to download a file until a retry limit has been reached + while (retryCount <= retryLimit) { + let response; + try { + response = yield makeDownloadRequest(); + } + catch (error) { + // if an error is caught, it is usually indicative of a timeout so retry the download + core.info('An error occurred while attempting to download a file'); + // eslint-disable-next-line no-console + console.log(error); + // increment the retryCount and use exponential backoff to wait before making the next request + yield backOff(); + continue; + } + if (utils_1.isSuccessStatusCode(response.message.statusCode)) { + // The body contains the contents of the file however calling response.readBody() causes all the content to be converted to a string + // which can cause some gzip encoded data to be lost + // Instead of using response.readBody(), response.message is a readableStream that can be directly used to get the raw body contents + return this.pipeResponseToFile(response, destinationStream, isGzip(response.message.headers)); + } + else if (utils_1.isRetryableStatusCode(response.message.statusCode)) { + core.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); + // if a throttled status code is received, try to get the retryAfter header value, else differ to standard exponential backoff + utils_1.isThrottledStatusCode(response.message.statusCode) + ? yield backOff(utils_1.tryGetRetryAfterValueTimeInMilliseconds(response.message.headers)) + : yield backOff(); + } + else { + // Some unexpected response code, fail immediately and stop the download + utils_1.displayHttpDiagnostics(response); + return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); + } + } + }); + } + /** + * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary + * @param response the http response received when downloading a file + * @param destinationStream the stream where the file should be written to + * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it + */ + pipeResponseToFile(response, destinationStream, isGzip) { + return __awaiter(this, void 0, void 0, function* () { + yield new Promise((resolve, reject) => { + if (isGzip) { + const gunzip = zlib.createGunzip(); + response.message + .pipe(gunzip) + .pipe(destinationStream) + .on('close', () => { + resolve(); + }) + .on('error', error => { + core.error(`An error has been encountered while decompressing and writing a downloaded file to ${destinationStream.path}`); + reject(error); + }); + } + else { + response.message + .pipe(destinationStream) + .on('close', () => { + resolve(); + }) + .on('error', error => { + core.error(`An error has been encountered while writing a downloaded file to ${destinationStream.path}`); + reject(error); + }); + } + }); + return; + }); + } +} +exports.DownloadHttpClient = DownloadHttpClient; +//# sourceMappingURL=download-http-client.js.map + +/***/ }), +/* 856 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) +module.exports = __webpack_require__(141); - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) - } - } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) +/***/ }), +/* 857 */, +/* 858 */, +/* 859 */, +/* 860 */, +/* 861 */, +/* 862 */ +/***/ (function(__unusedmodule, exports) { - self.found = all -} +"use strict"; -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) +Object.defineProperty(exports, '__esModule', { value: true }); - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - - return abs -} - - -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) + return ""; } -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map /***/ }), -/* 857 */, -/* 858 */, -/* 859 */, -/* 860 */, -/* 861 */, -/* 862 */, /* 863 */, /* 864 */, /* 865 */, @@ -30075,20 +29244,14 @@ exports.createEmptyFilesForArtifact = createEmptyFilesForArtifact; /***/ }), /* 871 */, -/* 872 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = __webpack_require__(141); - - -/***/ }), +/* 872 */, /* 873 */, /* 874 */, /* 875 */ /***/ (function(module, __unusedexports, __webpack_require__) { const {promisify} = __webpack_require__(669); -const tmp = __webpack_require__(803); +const tmp = __webpack_require__(402); // file module.exports.fileSync = tmp.fileSync; @@ -30652,15 +29815,18 @@ var isArray = Array.isArray || function (xs) { Object.defineProperty(exports, '__esModule', { value: true }); var request = __webpack_require__(753); -var universalUserAgent = __webpack_require__(796); +var universalUserAgent = __webpack_require__(862); -const VERSION = "4.5.1"; +const VERSION = "4.5.6"; class GraphqlError extends Error { constructor(request, response) { const message = response.data.errors[0].message; super(message); Object.assign(this, response.data); + Object.assign(this, { + headers: response.headers + }); this.name = "GraphqlError"; this.request = request; // Maintains proper stack trace (only available on V8) @@ -30674,13 +29840,18 @@ class GraphqlError extends Error { } const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; function graphql(request, query, options) { - options = typeof query === "string" ? options = Object.assign({ + if (typeof query === "string" && options && "query" in options) { + return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); + } + + const parsedOptions = typeof query === "string" ? Object.assign({ query - }, options) : options = query; - const requestOptions = Object.keys(options).reduce((result, key) => { + }, options) : query; + const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = options[key]; + result[key] = parsedOptions[key]; return result; } @@ -30688,12 +29859,27 @@ function graphql(request, query, options) { result.variables = {}; } - result.variables[key] = options[key]; + result.variables[key] = parsedOptions[key]; return result; - }, {}); + }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix + // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 + + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; + + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request(requestOptions).then(response => { if (response.data.errors) { + const headers = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlError(requestOptions, { + headers, data: response.data }); } @@ -31444,7 +30630,21 @@ module.exports = { /***/ }), /* 931 */, /* 932 */, -/* 933 */, +/* 933 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +const core = __webpack_require__(393); + +function getDefinitionFile() { + return core.getInput("definition-file"); +} + +module.exports = { + getDefinitionFile +}; + + +/***/ }), /* 934 */, /* 935 */, /* 936 */, @@ -31605,12 +30805,11 @@ module.exports = function(fn) { /***/ }), /* 949 */, /* 950 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; @@ -31625,7 +30824,7 @@ function getProxyUrl(reqUrl) { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { - proxyUrl = url.parse(proxyVar); + proxyUrl = new URL(proxyVar); } return proxyUrl; } diff --git a/docs/pull_request.yml b/docs/pull_request.yml index 5c553ed9..885d3bfa 100644 --- a/docs/pull_request.yml +++ b/docs/pull_request.yml @@ -6,13 +6,10 @@ jobs: name: Build Pull Request steps: - uses: actions/checkout@v2 - - name: Build Chain + - name: Build Chain ${{ matrix.java-version }} id: build-chain - uses: kiegroup/github-action-build-chain@master + uses: ginxo/github-action-build-chain@BXMSPROD-1025 with: - parent-dependencies: "lienzo-core" - child-dependencies: "droolsjbpm-build-bootstrap" - build-command: "mvn clean install" - build-command-upstream: "mvn clean" + definition-file: https://raw.githubusercontent.com/${GROUP}/${PROJECT_NAME}/${BRANCH}/.ci/pull-request-config.yaml env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/it/it.js b/it/it.js index d560da14..2b59f78c 100644 --- a/it/it.js +++ b/it/it.js @@ -12,9 +12,7 @@ async function main() { auth: `token ${token}`, userAgent: "kiegroup/github-build-chain-action-it" }); - addInputVariableToEnv("parent-dependencies"); - addInputVariableToEnv("child-dependencies"); - addInputVariableToEnv("workflow-file-name"); + addInputVariableToEnv("definition-file", true); const config = await createConfigLocally( octokit, process.env.URL, @@ -24,10 +22,19 @@ async function main() { await executeGitHubAction(context); } -function addInputVariableToEnv(inputVariable) { +/** + * The idea here is to add every env variable as an INPUT_X variable, this is the way github actions sets variables to the environment, so it's the way to introduce inputs from command line + * @param {String} inputVariable the input variable name + * @param {Boolean} mandatory is the input variable mandatory + */ +function addInputVariableToEnv(inputVariable, mandatory) { if (process.env[inputVariable]) { process.env[`INPUT_${inputVariable.replace(/ /g, "_").toUpperCase()}`] = process.env[inputVariable]; + } else if (mandatory) { + throw new Error( + `Input variable ${inputVariable} is mandatory and it's not defined. Please add it following documentation.` + ); } } diff --git a/package-lock.json b/package-lock.json index 6ad78d42..e636f1b8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,14 +16,6 @@ "tmp-promise": "^2.0.2" }, "dependencies": { - "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "requires": { - "glob": "^7.1.3" - } - }, "tmp": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.1.0.tgz", @@ -35,9 +27,9 @@ } }, "@actions/core": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.4.tgz", - "integrity": "sha512-YJCEq8BE3CdN8+7HPZ/4DxJjk/OkZV2FFIf+DlZTC/4iBlzYCD5yjRR6eiOS5llO11zbRltIRuKAjMKaWTE6cg==" + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz", + "integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA==" }, "@actions/exec": { "version": "1.0.4", @@ -57,9 +49,9 @@ } }, "@actions/http-client": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.8.tgz", - "integrity": "sha512-G4JjJ6f9Hb3Zvejj+ewLLKLf99ZC+9v+yCxoYf9vSyH+WkzPLB2LuUtRMGNkooMqdugGBFStIKXOuvH1W+EctA==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.9.tgz", + "integrity": "sha512-0O4SsJ7q+MK0ycvXPl2e6bMXV7dxAXOGjrXS1eTF9s2S401Tp6c/P3c3Joz04QefC1J6Gt942Wl2jbm3f4mLcg==", "requires": { "tunnel": "0.0.6" } @@ -79,34 +71,37 @@ } }, "@babel/core": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.10.4.tgz", - "integrity": "sha512-3A0tS0HWpy4XujGc7QtOIHTeNwUgWaZc/WuS5YQrfhU67jnVmsD6OGPc1AKHH0LJHQICGncy3+YUjIhVlfDdcA==", + "version": "7.12.3", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.12.3.tgz", + "integrity": "sha512-0qXcZYKZp3/6N2jKYVxZv0aNCsxTSVCiK72DTiTYZAu7sjg73W0/aynWjMbiGd87EQL4WyA8reiJVh92AVla9g==", "dev": true, "requires": { "@babel/code-frame": "^7.10.4", - "@babel/generator": "^7.10.4", - "@babel/helper-module-transforms": "^7.10.4", - "@babel/helpers": "^7.10.4", - "@babel/parser": "^7.10.4", + "@babel/generator": "^7.12.1", + "@babel/helper-module-transforms": "^7.12.1", + "@babel/helpers": "^7.12.1", + "@babel/parser": "^7.12.3", "@babel/template": "^7.10.4", - "@babel/traverse": "^7.10.4", - "@babel/types": "^7.10.4", + "@babel/traverse": "^7.12.1", + "@babel/types": "^7.12.1", "convert-source-map": "^1.7.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.1", "json5": "^2.1.2", - "lodash": "^4.17.13", + "lodash": "^4.17.19", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" }, "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true + "json5": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } }, "source-map": { "version": "0.5.7", @@ -117,14 +112,13 @@ } }, "@babel/generator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.10.4.tgz", - "integrity": "sha512-toLIHUIAgcQygFZRAQcsLQV3CBuX6yOIru1kJk/qqqvcRmZrYe6WavZTSG+bB8MxhnL9YPf+pKQfuiP161q7ng==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.12.1.tgz", + "integrity": "sha512-DB+6rafIdc9o72Yc3/Ph5h+6hUjeOp66pF0naQBgUFFuPqzQwIlPTm3xZR7YNvduIMtkDIj2t21LSQwnbCrXvg==", "dev": true, "requires": { - "@babel/types": "^7.10.4", + "@babel/types": "^7.12.1", "jsesc": "^2.5.1", - "lodash": "^4.17.13", "source-map": "^0.5.0" }, "dependencies": { @@ -157,36 +151,38 @@ } }, "@babel/helper-member-expression-to-functions": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.10.4.tgz", - "integrity": "sha512-m5j85pK/KZhuSdM/8cHUABQTAslV47OjfIB9Cc7P+PvlAoBzdb79BGNfw8RhT5Mq3p+xGd0ZfAKixbrUZx0C7A==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.12.1.tgz", + "integrity": "sha512-k0CIe3tXUKTRSoEx1LQEPFU9vRQfqHtl+kf8eNnDqb4AUJEy5pz6aIiog+YWtVm2jpggjS1laH68bPsR+KWWPQ==", "dev": true, "requires": { - "@babel/types": "^7.10.4" + "@babel/types": "^7.12.1" } }, "@babel/helper-module-imports": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.10.4.tgz", - "integrity": "sha512-nEQJHqYavI217oD9+s5MUBzk6x1IlvoS9WTPfgG43CbMEeStE0v+r+TucWdx8KFGowPGvyOkDT9+7DHedIDnVw==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.12.1.tgz", + "integrity": "sha512-ZeC1TlMSvikvJNy1v/wPIazCu3NdOwgYZLIkmIyAsGhqkNpiDoQQRmaCK8YP4Pq3GPTLPV9WXaPCJKvx06JxKA==", "dev": true, "requires": { - "@babel/types": "^7.10.4" + "@babel/types": "^7.12.1" } }, "@babel/helper-module-transforms": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.10.4.tgz", - "integrity": "sha512-Er2FQX0oa3nV7eM1o0tNCTx7izmQtwAQsIiaLRWtavAAEcskb0XJ5OjJbVrYXWOTr8om921Scabn4/tzlx7j1Q==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.12.1.tgz", + "integrity": "sha512-QQzehgFAZ2bbISiCpmVGfiGux8YVFXQ0abBic2Envhej22DVXV9nCFaS5hIQbkyo1AdGb+gNME2TSh3hYJVV/w==", "dev": true, "requires": { - "@babel/helper-module-imports": "^7.10.4", - "@babel/helper-replace-supers": "^7.10.4", - "@babel/helper-simple-access": "^7.10.4", - "@babel/helper-split-export-declaration": "^7.10.4", + "@babel/helper-module-imports": "^7.12.1", + "@babel/helper-replace-supers": "^7.12.1", + "@babel/helper-simple-access": "^7.12.1", + "@babel/helper-split-export-declaration": "^7.11.0", + "@babel/helper-validator-identifier": "^7.10.4", "@babel/template": "^7.10.4", - "@babel/types": "^7.10.4", - "lodash": "^4.17.13" + "@babel/traverse": "^7.12.1", + "@babel/types": "^7.12.1", + "lodash": "^4.17.19" } }, "@babel/helper-optimise-call-expression": { @@ -205,34 +201,33 @@ "dev": true }, "@babel/helper-replace-supers": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.10.4.tgz", - "integrity": "sha512-sPxZfFXocEymYTdVK1UNmFPBN+Hv5mJkLPsYWwGBxZAxaWfFu+xqp7b6qWD0yjNuNL2VKc6L5M18tOXUP7NU0A==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.12.1.tgz", + "integrity": "sha512-zJjTvtNJnCFsCXVi5rUInstLd/EIVNmIKA1Q9ynESmMBWPWd+7sdR+G4/wdu+Mppfep0XLyG2m7EBPvjCeFyrw==", "dev": true, "requires": { - "@babel/helper-member-expression-to-functions": "^7.10.4", + "@babel/helper-member-expression-to-functions": "^7.12.1", "@babel/helper-optimise-call-expression": "^7.10.4", - "@babel/traverse": "^7.10.4", - "@babel/types": "^7.10.4" + "@babel/traverse": "^7.12.1", + "@babel/types": "^7.12.1" } }, "@babel/helper-simple-access": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.10.4.tgz", - "integrity": "sha512-0fMy72ej/VEvF8ULmX6yb5MtHG4uH4Dbd6I/aHDb/JVg0bbivwt9Wg+h3uMvX+QSFtwr5MeItvazbrc4jtRAXw==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.12.1.tgz", + "integrity": "sha512-OxBp7pMrjVewSSC8fXDFrHrBcJATOOFssZwv16F3/6Xtc138GHybBfPbm9kfiqQHKhYQrlamWILwlDCeyMFEaA==", "dev": true, "requires": { - "@babel/template": "^7.10.4", - "@babel/types": "^7.10.4" + "@babel/types": "^7.12.1" } }, "@babel/helper-split-export-declaration": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.10.4.tgz", - "integrity": "sha512-pySBTeoUff56fL5CBU2hWm9TesA4r/rOkI9DyJLvvgz09MB9YtfIYe3iBriVaYNaPe+Alua0vBIOVOLs2buWhg==", + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz", + "integrity": "sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg==", "dev": true, "requires": { - "@babel/types": "^7.10.4" + "@babel/types": "^7.11.0" } }, "@babel/helper-validator-identifier": { @@ -242,14 +237,14 @@ "dev": true }, "@babel/helpers": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.10.4.tgz", - "integrity": "sha512-L2gX/XeUONeEbI78dXSrJzGdz4GQ+ZTA/aazfUsFaWjSe95kiCuOZ5HsXvkiw3iwF+mFHSRUfJU8t6YavocdXA==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.12.1.tgz", + "integrity": "sha512-9JoDSBGoWtmbay98efmT2+mySkwjzeFeAL9BuWNoVQpkPFQF8SIIFUfY5os9u8wVzglzoiPRSW7cuJmBDUt43g==", "dev": true, "requires": { "@babel/template": "^7.10.4", - "@babel/traverse": "^7.10.4", - "@babel/types": "^7.10.4" + "@babel/traverse": "^7.12.1", + "@babel/types": "^7.12.1" } }, "@babel/highlight": { @@ -261,12 +256,25 @@ "@babel/helper-validator-identifier": "^7.10.4", "chalk": "^2.0.0", "js-tokens": "^4.0.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } } }, "@babel/parser": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.10.4.tgz", - "integrity": "sha512-8jHII4hf+YVDsskTF6WuMB3X4Eh+PsUkC2ljq22so5rHvH+T8BzyL94VOdyFLNR8tBSVXOTbNHOKpR4TfRxVtA==", + "version": "7.12.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.3.tgz", + "integrity": "sha512-kFsOS0IbsuhO5ojF8Hc8z/8vEIOkylVBrjiZUbLTE3XFe0Qi+uu6HjzQixkFaqr0ZPAMZcBVxEwmsnsLPZ2Xsw==", "dev": true }, "@babel/plugin-syntax-async-generators": { @@ -288,9 +296,9 @@ } }, "@babel/plugin-syntax-class-properties": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.10.4.tgz", - "integrity": "sha512-GCSBF7iUle6rNugfURwNmCGG3Z/2+opxAMLs1nND4bhEG5PuxTIggDBoeYYSujAlLtsupzOHYJQgPS3pivwXIA==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.1.tgz", + "integrity": "sha512-U40A76x5gTwmESz+qiqssqmeEsKvcSyvtgktrm0uzcARAmM9I1jR221f6Oq+GmHrcD+LvZDag1UTOTe2fL3TeA==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.10.4" @@ -368,16 +376,6 @@ "@babel/helper-plugin-utils": "^7.8.0" } }, - "@babel/runtime-corejs3": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.10.4.tgz", - "integrity": "sha512-BFlgP2SoLO9HJX9WBwN67gHWMBhDX/eDz64Jajd6mR/UAUzqrNMm99d4qHnVaKscAElZoFiPv+JpR/Siud5lXw==", - "dev": true, - "requires": { - "core-js-pure": "^3.0.0", - "regenerator-runtime": "^0.13.4" - } - }, "@babel/template": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.10.4.tgz", @@ -390,20 +388,20 @@ } }, "@babel/traverse": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.10.4.tgz", - "integrity": "sha512-aSy7p5THgSYm4YyxNGz6jZpXf+Ok40QF3aA2LyIONkDHpAcJzDUqlCKXv6peqYUs2gmic849C/t2HKw2a2K20Q==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.12.1.tgz", + "integrity": "sha512-MA3WPoRt1ZHo2ZmoGKNqi20YnPt0B1S0GTZEPhhd+hw2KGUzBlHuVunj6K4sNuK+reEvyiPwtp0cpaqLzJDmAw==", "dev": true, "requires": { "@babel/code-frame": "^7.10.4", - "@babel/generator": "^7.10.4", + "@babel/generator": "^7.12.1", "@babel/helper-function-name": "^7.10.4", - "@babel/helper-split-export-declaration": "^7.10.4", - "@babel/parser": "^7.10.4", - "@babel/types": "^7.10.4", + "@babel/helper-split-export-declaration": "^7.11.0", + "@babel/parser": "^7.12.1", + "@babel/types": "^7.12.1", "debug": "^4.1.0", "globals": "^11.1.0", - "lodash": "^4.17.13" + "lodash": "^4.17.19" }, "dependencies": { "globals": { @@ -415,13 +413,13 @@ } }, "@babel/types": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.10.4.tgz", - "integrity": "sha512-UTCFOxC3FsFHb7lkRMVvgLzaRVamXuAs2Tz4wajva4WxtVY82eZeaUBtC2Zt95FU9TiznuC0Zk35tsim8jeVpg==", + "version": "7.12.1", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.1.tgz", + "integrity": "sha512-BzSY3NJBKM4kyatSOWh3D/JJ2O3CVzBybHWxtgxnggaxEuaSTTDqeiSb/xk9lrkw2Tbqyivw5ZU4rT+EfznQsA==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.10.4", - "lodash": "^4.17.13", + "lodash": "^4.17.19", "to-fast-properties": "^2.0.0" } }, @@ -441,6 +439,24 @@ "minimist": "^1.2.0" } }, + "@eslint/eslintrc": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.1.3.tgz", + "integrity": "sha512-4YVwPkANLeNtRjMekzux1ci8hIaH5eGKktGqR0d3LWsKNn5B2X/1Z6Trxy7jQXl9EBGE6Yj02O+t09FMeRllaA==", + "dev": true, + "requires": { + "ajv": "^6.12.4", + "debug": "^4.1.1", + "espree": "^7.3.0", + "globals": "^12.1.0", + "ignore": "^4.0.6", + "import-fresh": "^3.2.1", + "js-yaml": "^3.13.1", + "lodash": "^4.17.19", + "minimatch": "^3.0.4", + "strip-json-comments": "^3.1.1" + } + }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -454,6 +470,55 @@ "resolve-from": "^5.0.0" }, "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -482,12 +547,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -523,9 +587,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -570,12 +634,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -610,19 +673,19 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "glob": "^7.1.3" } }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -699,12 +762,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -740,9 +802,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -811,12 +873,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -852,9 +913,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -875,12 +936,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -916,9 +976,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -926,6 +986,22 @@ } } }, + "@kie/build-chain-configuration-reader": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/@kie/build-chain-configuration-reader/-/build-chain-configuration-reader-0.0.4.tgz", + "integrity": "sha512-UDo0SpwUmIugYontHgPgMU/NQ3SwX6Psp4lz0AUhA4MSuI7zkFf4d/XJe9nkg+bB8R2P1snebfRvdja0zqGiYA==", + "requires": { + "@actions/artifact": "^0.3.5", + "@actions/core": "^1.1.3", + "@actions/exec": "^1.0.4", + "@actions/glob": "^0.1.0", + "@octokit/rest": "^17.6.0", + "argparse": "^1.0.7", + "fs-extra": "^9.0.0", + "js-yaml": "^3.14.0", + "tmp": "^0.2.1" + } + }, "@octokit/auth-token": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.2.tgz", @@ -948,38 +1024,45 @@ } }, "@octokit/endpoint": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.3.tgz", - "integrity": "sha512-Y900+r0gIz+cWp6ytnkibbD95ucEzDSKzlEnaWS52hbCDNcCJYO5mRmWW7HRAnDc7am+N/5Lnd8MppSaTYx1Yg==", + "version": "6.0.8", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.8.tgz", + "integrity": "sha512-MuRrgv+bM4Q+e9uEvxAB/Kf+Sj0O2JAOBA131uo1o6lgdq1iS8ejKwtqHgdfY91V3rN9R/hdGKFiQYMzVzVBEQ==", "requires": { "@octokit/types": "^5.0.0", - "is-plain-object": "^3.0.0", - "universal-user-agent": "^5.0.0" + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" }, "dependencies": { - "is-plain-object": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.1.tgz", - "integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==" + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" } } }, "@octokit/graphql": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.1.tgz", - "integrity": "sha512-qgMsROG9K2KxDs12CO3bySJaYoUu2aic90qpFrv7A8sEBzZ7UFGvdgPKiLw5gOPYEYbS0Xf8Tvf84tJutHPulQ==", + "version": "4.5.6", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.6.tgz", + "integrity": "sha512-Rry+unqKTa3svswT2ZAuqenpLrzJd+JTv89LTeVa5UM/5OX8o4KTkPL7/1ABq4f/ZkELb0XEK/2IEoYwykcLXg==", "requires": { "@octokit/request": "^5.3.0", "@octokit/types": "^5.0.0", - "universal-user-agent": "^5.0.0" + "universal-user-agent": "^6.0.0" + }, + "dependencies": { + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + } } }, "@octokit/plugin-paginate-rest": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.3.tgz", - "integrity": "sha512-eKTs91wXnJH8Yicwa30jz6DF50kAh7vkcqCQ9D7/tvBAP5KKkg6I2nNof8Mp/65G0Arjsb4QcOJcIEQY+rK1Rg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.4.0.tgz", + "integrity": "sha512-YT6Klz3LLH6/nNgi0pheJnUmTFW4kVnxGft+v8Itc41IIcjl7y1C8TatmKQBbCSuTSNFXO5pCENnqg6sjwpJhg==", "requires": { - "@octokit/types": "^5.0.0" + "@octokit/types": "^5.5.0" } }, "@octokit/plugin-request-log": { @@ -1007,24 +1090,24 @@ } }, "@octokit/request": { - "version": "5.4.5", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.5.tgz", - "integrity": "sha512-atAs5GAGbZedvJXXdjtKljin+e2SltEs48B3naJjqWupYl2IUBbB/CJisyjbNHcKpHzb3E+OYEZ46G8eakXgQg==", + "version": "5.4.9", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.9.tgz", + "integrity": "sha512-CzwVvRyimIM1h2n9pLVYfTDmX9m+KHSgCpqPsY8F1NdEK8IaWqXhSBXsdjOBFZSpEcxNEeg4p0UO9cQ8EnOCLA==", "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", "@octokit/types": "^5.0.0", "deprecation": "^2.0.0", - "is-plain-object": "^3.0.0", - "node-fetch": "^2.3.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.1", "once": "^1.4.0", - "universal-user-agent": "^5.0.0" + "universal-user-agent": "^6.0.0" }, "dependencies": { - "is-plain-object": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.1.tgz", - "integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==" + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" } } }, @@ -1050,26 +1133,26 @@ } }, "@octokit/types": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.0.1.tgz", - "integrity": "sha512-GorvORVwp244fGKEt3cgt/P+M0MGy4xEDbckw+K5ojEezxyMDgCaYPKVct+/eWQfZXOT7uq0xRpmrl/+hliabA==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.5.0.tgz", + "integrity": "sha512-UZ1pErDue6bZNjYOotCNveTXArOMZQFG6hKJfOnGnulVCMcVVi7YIIuuR4WfBhjo7zgpmzn/BkPDnUXtNx+PcQ==", "requires": { "@types/node": ">= 8" } }, "@sinonjs/commons": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.0.tgz", - "integrity": "sha512-wEj54PfsZ5jGSwMX68G8ZXFawcSglQSXqCftWX3ec8MDUzQdHgcKvw97awHbY0efQEL5iKUOAmmVtoYgmrSG4Q==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.1.tgz", + "integrity": "sha512-892K+kWUUi3cl+LlqEWIDrhvLgdL79tECi8JZUyq6IviKy/DNhuzCRlbHUjxK89f4ypPMMaFnFuR9Ie6DoIMsw==", "dev": true, "requires": { "type-detect": "4.0.8" } }, "@types/babel__core": { - "version": "7.1.9", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.9.tgz", - "integrity": "sha512-sY2RsIJ5rpER1u3/aQ8OFSI7qGIy8o1NEEbgb2UaJcvOtXOMpd39ko723NBpjQFg9SIX7TXtjejZVGeIMLhoOw==", + "version": "7.1.10", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.10.tgz", + "integrity": "sha512-x8OM8XzITIMyiwl5Vmo2B1cR1S1Ipkyv4mdlbJjMa1lmuKvKY9FrBbEANIaMlnWn5Rf7uO+rC/VgYabNkE17Hw==", "dev": true, "requires": { "@babel/parser": "^7.1.0", @@ -1080,18 +1163,18 @@ } }, "@types/babel__generator": { - "version": "7.6.1", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.1.tgz", - "integrity": "sha512-bBKm+2VPJcMRVwNhxKu8W+5/zT7pwNEqeokFOmbvVSqGzFneNxYcEBro9Ac7/N9tlsaPYnZLK8J1LWKkMsLAew==", + "version": "7.6.2", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.2.tgz", + "integrity": "sha512-MdSJnBjl+bdwkLskZ3NGFp9YcXGx5ggLpQQPqtgakVhsWK0hTtNYhjpZLlWQTviGTvF8at+Bvli3jV7faPdgeQ==", "dev": true, "requires": { "@babel/types": "^7.0.0" } }, "@types/babel__template": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.0.2.tgz", - "integrity": "sha512-/K6zCpeW7Imzgab2bLkLEbz0+1JlFSrUMdw7KoIIu+IUdu51GWaBZpd3y1VXGVXzynvGa4DaIaxNZHiON3GXUg==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.0.3.tgz", + "integrity": "sha512-uCoznIPDmnickEi6D0v11SBpW0OuVqHJCa7syXqQHy5uktSCreIlt0iglsCnmvz8yCb38hGcWeseA8cWJSwv5Q==", "dev": true, "requires": { "@babel/parser": "^7.1.0", @@ -1099,20 +1182,14 @@ } }, "@types/babel__traverse": { - "version": "7.0.13", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.13.tgz", - "integrity": "sha512-i+zS7t6/s9cdQvbqKDARrcbrPvtJGlbYsMkazo03nTAK3RX9FNrLllXys22uiTGJapPOTZTQ35nHh4ISph4SLQ==", + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.15.tgz", + "integrity": "sha512-Pzh9O3sTK8V6I1olsXpCfj2k/ygO2q1X0vhhnDrEQyYLHZesWz+zMZMVcwXLCYf0U36EtmyYaFGPfXlTtDHe3A==", "dev": true, "requires": { "@babel/types": "^7.3.0" } }, - "@types/color-name": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", - "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", - "dev": true - }, "@types/graceful-fs": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.3.tgz", @@ -1148,9 +1225,9 @@ } }, "@types/json-schema": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.5.tgz", - "integrity": "sha512-7+2BITlgjgDhH0vvwZU/HZJVyk+2XUlvxXe8dFMedNX/aMkaOq++rMAFXc0tM7ij15QaWlbdQASBR9dihi+bDQ==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.6.tgz", + "integrity": "sha512-3c+yGKvVP5Y9TYBEibGNR+kLtijnj7mYrXRg+WpFb2X9xm04g/DXYkfg4hmzJQosc9snFNUPkbYIhu+KAm6jJw==", "dev": true }, "@types/json5": { @@ -1160,9 +1237,9 @@ "dev": true }, "@types/node": { - "version": "14.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.14.tgz", - "integrity": "sha512-syUgf67ZQpaJj01/tRTknkMNoBBLWJOBODF0Zm4NrXmiSuxjymFrxnTu1QVYRubhVkRcZLYZG8STTwJRdVm/WQ==" + "version": "14.14.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.0.tgz", + "integrity": "sha512-BfbIHP9IapdupGhq/hc+jT5dyiBVZ2DdeC5WwJWQWDb0GijQlzUFAeIQn/2GtvZcd2HVUU7An8felIICFTC2qg==" }, "@types/normalize-package-data": { "version": "2.4.0", @@ -1188,9 +1265,9 @@ "integrity": "sha512-6IwZ9HzWbCq6XoQWhxLpDjuADodH/MKXRUIDFudvgjcVdjFknvmR+DNsoUeer4XPrEnrZs04Jj+kfV9pFsrhmA==" }, "@types/yargs": { - "version": "15.0.5", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.5.tgz", - "integrity": "sha512-Dk/IDOPtOgubt/IaevIUbTgV7doaKkoorvOyYM2CMwuDyP89bekI7H4xLIwunNYiK9jhCkmc6pUrJk3cj2AB9w==", + "version": "15.0.9", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.9.tgz", + "integrity": "sha512-HmU8SeIRhZCWcnRskCs36Q1Q00KBV6Cqh/ora8WN1+22dY07AZdn6Gel8QZ3t26XYPImtcL8WV/eqjhVmMEw4g==", "dev": true, "requires": { "@types/yargs-parser": "*" @@ -1229,6 +1306,12 @@ "tsutils": "^3.17.1" }, "dependencies": { + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true + }, "semver": { "version": "7.3.2", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", @@ -1244,15 +1327,15 @@ "dev": true }, "abab": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.3.tgz", - "integrity": "sha512-tsFzPpcttalNjFBCFMqsKYQcWxxen1pgJR56by//QwvJc4/OUS3kPOOttx2tSIfjsylB0pYu7f5D3K1RCxUnUg==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz", + "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", "dev": true }, "acorn": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.3.1.tgz", - "integrity": "sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA==", + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", "dev": true }, "acorn-globals": { @@ -1266,17 +1349,17 @@ }, "dependencies": { "acorn": { - "version": "6.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.1.tgz", - "integrity": "sha512-ZVA9k326Nwrj3Cj9jlh3wGFutC2ZornPNARZwsNYqQYgN0EsV2d53w5RN/co65Ohn4sUAUtb1rSUAOD6XN9idA==", + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.2.tgz", + "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", "dev": true } } }, "acorn-jsx": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.2.0.tgz", - "integrity": "sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.1.tgz", + "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==", "dev": true }, "acorn-walk": { @@ -1286,9 +1369,9 @@ "dev": true }, "ajv": { - "version": "6.12.3", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.3.tgz", - "integrity": "sha512-4K0cK3L1hsqk9xIb2z9vs/XU+PGJZ9PNpJRDS9YLzmNdX6jmVPfamLvTJr0aDAusnHyCHO6MjzlkAsgtqp9teA==", + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", @@ -1455,9 +1538,9 @@ "dev": true }, "aws4": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.10.0.tgz", - "integrity": "sha512-3YDiu347mtVtjpyV3u5kVqQLP242c06zwDOgpeRnybmXlYYsLbtTrUBUm8i8srONt+FWobl5aibnU1030PeeuA==", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.10.1.tgz", + "integrity": "sha512-zg7Hz2k5lI8kb7U32998pRRFin7zJlkfezGJjUc2heaD4Pw2wObakCDVzkKztTm/Ln7eiVvYsjqak0Ed4LkMDA==", "dev": true }, "babel-jest": { @@ -1477,12 +1560,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -1518,9 +1600,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -1553,9 +1635,9 @@ } }, "babel-preset-current-node-syntax": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-0.1.3.tgz", - "integrity": "sha512-uyexu1sVwcdFnyq9o8UQYsXwXflIh8LvrF5+cKrYam93ned1CStffB3+BEcsxGSgagoA3GEyjDqO4a/58hyPYQ==", + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-0.1.4.tgz", + "integrity": "sha512-5/INNCYhUGqw7VbVjT/hb3ucjgkVHKXY7lX3ZjlN4gm565VyFmJUrJ/h+h16ECVB38R/9SF6aACydpKMLZ/c9w==", "dev": true, "requires": { "@babel/plugin-syntax-async-generators": "^7.8.4", @@ -1756,14 +1838,54 @@ "dev": true }, "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", "dev": true, "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } } }, "ci-info": { @@ -1806,13 +1928,27 @@ "wrap-ansi": "^6.2.0" }, "dependencies": { - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" } } } @@ -1895,12 +2031,6 @@ "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, - "core-js-pure": { - "version": "3.6.5", - "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.6.5.tgz", - "integrity": "sha512-lacdXOimsiD0QyNf9BC/mxivNJ/ybBGJXQFKzRekp1WTHoVUWsUHEn+2T8GJAzzIhyOuXA+gOxCVN3l+5PLPUA==", - "dev": true - }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -1917,13 +2047,6 @@ "semver": "^5.5.0", "shebang-command": "^1.2.0", "which": "^1.2.9" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" - } } }, "cssom": { @@ -1970,22 +2093,19 @@ } }, "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.2.0.tgz", + "integrity": "sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg==", "dev": true, "requires": { - "ms": "^2.1.1" + "ms": "2.1.2" } }, "decamelize": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-3.2.0.tgz", - "integrity": "sha512-4TgkVUsmmu7oCSyGBm5FvfMoACuoh9EOidm7V5/J2X2djAwwt57qb3F2KMP2ITqODTCSwb+YRV+0Zqrv18k/hw==", - "dev": true, - "requires": { - "xregexp": "^4.2.4" - } + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true }, "decode-uri-component": { "version": "0.2.0", @@ -2113,9 +2233,9 @@ } }, "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, "end-of-stream": { @@ -2145,20 +2265,20 @@ } }, "es-abstract": { - "version": "1.17.6", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.6.tgz", - "integrity": "sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw==", + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", "dev": true, "requires": { "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", "has": "^1.0.3", "has-symbols": "^1.0.1", - "is-callable": "^1.2.0", - "is-regex": "^1.1.0", - "object-inspect": "^1.7.0", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", "object-keys": "^1.1.1", - "object.assign": "^4.1.0", + "object.assign": "^4.1.1", "string.prototype.trimend": "^1.0.1", "string.prototype.trimstart": "^1.0.1" } @@ -2191,25 +2311,67 @@ "esutils": "^2.0.2", "optionator": "^0.8.1", "source-map": "~0.6.1" + }, + "dependencies": { + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + } } }, "eslint": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.6.0.tgz", - "integrity": "sha512-QlAManNtqr7sozWm5TF4wIH9gmUm2hE3vNRUvyoYAa4y1l5/jxD/PQStEjBMQtCqZmSep8UxrcecI60hOpe61w==", + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.11.0.tgz", + "integrity": "sha512-G9+qtYVCHaDi1ZuWzBsOWo2wSwd70TXnU6UHA3cTYHp7gCTXZcpggWFoUVAMRarg68qtPoNfFbzPh+VdOgmwmw==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", + "@eslint/eslintrc": "^0.1.3", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.0.1", "doctrine": "^3.0.0", "enquirer": "^2.3.5", - "eslint-scope": "^5.1.0", + "eslint-scope": "^5.1.1", "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^1.3.0", - "espree": "^7.2.0", + "eslint-visitor-keys": "^2.0.0", + "espree": "^7.3.0", "esquery": "^1.2.0", "esutils": "^2.0.2", "file-entry-cache": "^5.0.1", @@ -2237,41 +2399,6 @@ "v8-compile-cache": "^2.0.3" }, "dependencies": { - "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", - "dev": true, - "requires": { - "@types/color-name": "^1.1.1", - "color-convert": "^2.0.1" - } - }, - "chalk": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", - "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, "cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -2283,52 +2410,10 @@ "which": "^2.0.1" } }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - } - }, - "lodash": { - "version": "4.17.19", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz", - "integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==", - "dev": true - }, - "optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", - "dev": true, - "requires": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.3" - } - }, "path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true - }, - "prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true }, "semver": { @@ -2352,33 +2437,6 @@ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.0" - } - }, - "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - }, - "type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1" - } - }, "which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -2397,9 +2455,9 @@ "dev": true }, "eslint-config-prettier": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.11.0.tgz", - "integrity": "sha512-oB8cpLWSAjOVFEJhhyMZh6NOEOtBVziaqdDQ86+qhDHFbZXoRTM7pNSvFRfW/W/L/LrQ38C99J5CGuRBBzBsdA==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.13.0.tgz", + "integrity": "sha512-LcT0i0LSmnzqK2t764pyIt7kKH2AuuqKRTtJTdddWxOiUja9HdG5GXBVF2gmCTvVYWVsTu8J2MhJLVGRh+pj8w==", "dev": true, "requires": { "get-stdin": "^6.0.0" @@ -2457,69 +2515,11 @@ "ms": "2.0.0" } }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "^2.0.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - } - }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true - }, - "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", - "dev": true, - "requires": { - "p-try": "^1.0.0" - } - }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "^1.1.0" - } - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true - }, - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - }, - "pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", - "dev": true, - "requires": { - "find-up": "^2.1.0" - } } } }, @@ -2534,9 +2534,9 @@ } }, "eslint-plugin-import": { - "version": "2.22.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz", - "integrity": "sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg==", + "version": "2.22.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.22.1.tgz", + "integrity": "sha512-8K7JjINHOpH64ozkAhpT3sd+FswIZTfMZTjdx052pnWrgRCVfp8op9tbjpAk3DdUeI/Ba4C8OjdC0r90erHEOw==", "dev": true, "requires": { "array-includes": "^3.1.1", @@ -2544,7 +2544,7 @@ "contains-path": "^0.1.0", "debug": "^2.6.9", "doctrine": "1.5.0", - "eslint-import-resolver-node": "^0.3.3", + "eslint-import-resolver-node": "^0.3.4", "eslint-module-utils": "^2.6.0", "has": "^1.0.3", "minimatch": "^3.0.4", @@ -2573,81 +2573,11 @@ "isarray": "^1.0.0" } }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "^2.0.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - } - }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true - }, - "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", - "dev": true, - "requires": { - "p-try": "^1.0.0" - } - }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "^1.1.0" - } - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true - }, - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - }, - "read-pkg": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", - "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", - "dev": true, - "requires": { - "load-json-file": "^2.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^2.0.0" - } - }, - "read-pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", - "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", - "dev": true, - "requires": { - "find-up": "^2.0.0", - "read-pkg": "^2.0.0" - } } } }, @@ -2679,6 +2609,12 @@ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", "dev": true + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true } } }, @@ -2704,12 +2640,12 @@ "dev": true }, "eslint-scope": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.0.tgz", - "integrity": "sha512-iiGRvtxWqgtx5m8EyQUJihBloE4EnYeGE/bz1wSPwJE6tZuJUtHlhqDM4Xj2ukE8Dyy1+HCZ4hE0fzIVMzb58w==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "requires": { - "esrecurse": "^4.1.0", + "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, @@ -2720,23 +2656,39 @@ "dev": true, "requires": { "eslint-visitor-keys": "^1.1.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true + } } }, "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz", + "integrity": "sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ==", "dev": true }, "espree": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.2.0.tgz", - "integrity": "sha512-H+cQ3+3JYRMEIOl87e7QdHX70ocly5iW4+dttuR8iYSPr/hXKFb+7dBsZ7+u1adC4VrnPlTkv0+OwuPnDop19g==", + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.0.tgz", + "integrity": "sha512-dksIWsvKCixn1yrEXO8UosNSxaDoSYpq9reEjZSbHLpT5hpaCAKTLBwq0RHtLrIr+c0ByiYzWT8KTMRzoRCNlw==", "dev": true, "requires": { - "acorn": "^7.3.1", + "acorn": "^7.4.0", "acorn-jsx": "^5.2.0", "eslint-visitor-keys": "^1.3.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true + } } }, "esprima": { @@ -2754,20 +2706,28 @@ }, "dependencies": { "estraverse": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.1.0.tgz", - "integrity": "sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", "dev": true } } }, "esrecurse": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", - "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { - "estraverse": "^4.1.0" + "estraverse": "^5.2.0" + }, + "dependencies": { + "estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "dev": true + } } }, "estraverse": { @@ -2873,12 +2833,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -2923,6 +2882,15 @@ "requires": { "is-plain-object": "^2.0.4" } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } } } }, @@ -3049,13 +3017,12 @@ } }, "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", "dev": true, "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" + "locate-path": "^2.0.0" } }, "flat-cache": { @@ -3256,12 +3223,12 @@ "dev": true }, "har-validator": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", - "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", "dev": true, "requires": { - "ajv": "^6.5.5", + "ajv": "^6.12.3", "har-schema": "^2.0.0" } }, @@ -3409,6 +3376,66 @@ "requires": { "pkg-dir": "^4.2.0", "resolve-cwd": "^3.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + } } }, "imurmurhash": { @@ -3470,9 +3497,9 @@ "dev": true }, "is-callable": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.0.tgz", - "integrity": "sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", "dev": true }, "is-ci": { @@ -3484,6 +3511,15 @@ "ci-info": "^2.0.0" } }, + "is-core-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.0.0.tgz", + "integrity": "sha512-jq1AH6C8MuteOoBPwkxHafmByhL9j5q4OaPGdbuD+ZtQJVzH+i6E3BJDQcBA09k57i2Hh2yQbEG8yObZ0jdlWw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, "is-data-descriptor": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", @@ -3530,9 +3566,9 @@ } }, "is-docker": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.0.0.tgz", - "integrity": "sha512-pJEdRugimx4fBMra5z2/5iRdZ63OhYV0vr0Dwm5+xtW4D1FvRkB8hamMIhnWfyJeDdyr/aa7BDyNbtG38VxgoQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.1.1.tgz", + "integrity": "sha512-ZOoqiXfEwtGknTiuDEy8pN2CfE3TxMHprvNer1mXiqwkOT77Rw3YVrUQ52EqAOU3QAWDQ+bQdx7HJzrv7LS2Hw==", "dev": true, "optional": true }, @@ -3549,9 +3585,9 @@ "dev": true }, "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "is-generator-fn": { @@ -3569,6 +3605,12 @@ "is-extglob": "^2.1.1" } }, + "is-negative-zero": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz", + "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=", + "dev": true + }, "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -3576,18 +3618,14 @@ "dev": true }, "is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", - "dev": true, - "requires": { - "isobject": "^3.0.1" - } + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" }, "is-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.0.tgz", - "integrity": "sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", "dev": true, "requires": { "has-symbols": "^1.0.1" @@ -3674,6 +3712,14 @@ "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.0.0", "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, "istanbul-lib-report": { @@ -3694,9 +3740,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -3737,12 +3783,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -3800,9 +3845,9 @@ } }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -3851,9 +3896,9 @@ } }, "get-stream": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", - "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", "dev": true, "requires": { "pump": "^3.0.0" @@ -3940,12 +3985,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -3981,9 +4025,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4004,12 +4048,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4045,9 +4088,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4078,12 +4121,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4119,9 +4161,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4155,6 +4197,14 @@ "jest-mock": "^25.5.0", "jest-util": "^25.5.0", "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, "jest-get-type": { @@ -4221,12 +4271,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4262,9 +4311,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4295,12 +4344,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4336,9 +4384,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4363,12 +4411,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4404,9 +4451,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4453,12 +4500,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4487,16 +4533,108 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "parse-json": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.1.0.tgz", + "integrity": "sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "read-pkg": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", + "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", + "dev": true, + "requires": { + "@types/normalize-package-data": "^2.4.0", + "normalize-package-data": "^2.5.0", + "parse-json": "^5.0.0", + "type-fest": "^0.6.0" + }, + "dependencies": { + "type-fest": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", + "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", + "dev": true + } + } + }, + "read-pkg-up": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", + "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", + "dev": true, + "requires": { + "find-up": "^4.1.0", + "read-pkg": "^5.2.0", + "type-fest": "^0.8.1" + } + }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4543,12 +4681,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4584,9 +4721,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4629,12 +4766,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4669,10 +4805,16 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, + "strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true + }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4713,12 +4855,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4753,10 +4894,16 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4778,12 +4925,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4819,9 +4965,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4844,12 +4990,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4885,9 +5030,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4910,12 +5055,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -4951,9 +5095,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -4978,9 +5122,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -5049,10 +5193,10 @@ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "dev": true }, "json-schema": { @@ -5080,12 +5224,12 @@ "dev": true }, "json5": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", - "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", "dev": true, "requires": { - "minimist": "^1.2.5" + "minimist": "^1.2.0" } }, "jsonfile": { @@ -5128,13 +5272,13 @@ "dev": true }, "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "requires": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" } }, "lines-and-columns": { @@ -5153,38 +5297,22 @@ "parse-json": "^2.2.0", "pify": "^2.0.0", "strip-bom": "^3.0.0" - }, - "dependencies": { - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "dev": true, - "requires": { - "error-ex": "^1.2.0" - } - }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - } } }, "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", "dev": true, "requires": { - "p-locate": "^4.1.0" + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" } }, "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "version": "4.17.20", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", + "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", "dev": true }, "lodash.sortby": { @@ -5203,9 +5331,9 @@ } }, "macos-release": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.4.0.tgz", - "integrity": "sha512-ko6deozZYiAkqa/0gmcsz+p4jSy3gY7/ZsCEokPaYd8k+6/aXGkiTgr61+Owup7Sf+xjqW8u2ElhoM9SEcEfuA==" + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.4.1.tgz", + "integrity": "sha512-H/QHeBIN1fIGJX517pvK8IEK53yQOW7YcEI55oYtgjDdoCQQz7eJS94qt5kNrscReEyuD/JcdFCm2XBEcGOITg==" }, "make-dir": { "version": "3.1.0", @@ -5214,6 +5342,14 @@ "dev": true, "requires": { "semver": "^6.0.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } } }, "makeerror": { @@ -5309,6 +5445,15 @@ "requires": { "is-plain-object": "^2.0.4" } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } } } }, @@ -5358,9 +5503,9 @@ "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" }, "node-fetch": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", - "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" }, "node-int64": { "version": "0.4.0", @@ -5386,6 +5531,15 @@ "semver": "^6.3.0", "shellwords": "^0.1.1", "which": "^1.3.1" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "optional": true + } } }, "normalize-package-data": { @@ -5398,14 +5552,6 @@ "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - } } }, "normalize-path": { @@ -5487,15 +5633,37 @@ } }, "object.assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.1.tgz", + "integrity": "sha512-VT/cxmx5yaoHSOTSyrCygIDFco+RsibY2NM0a4RdEeY/4KgqezwFtK1yr3U67xYhqJSlASm2pKhLVzPj2lr4bA==", "dev": true, "requires": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0-next.0", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + } } }, "object.pick": { @@ -5528,26 +5696,26 @@ } }, "onetime": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", - "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dev": true, "requires": { "mimic-fn": "^2.1.0" } }, "optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", + "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", "dev": true, "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.3" } }, "os-name": { @@ -5571,27 +5739,27 @@ "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" }, "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", "dev": true, "requires": { - "p-try": "^2.0.0" + "p-try": "^1.0.0" } }, "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", "dev": true, "requires": { - "p-limit": "^2.2.0" + "p-limit": "^1.1.0" } }, "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", "dev": true }, "parent-module": { @@ -5604,15 +5772,12 @@ } }, "parse-json": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.0.0.tgz", - "integrity": "sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1", - "lines-and-columns": "^1.1.6" + "error-ex": "^1.2.0" } }, "parse5": { @@ -5628,9 +5793,9 @@ "dev": true }, "path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", "dev": true }, "path-is-absolute": { @@ -5686,12 +5851,12 @@ } }, "pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", "dev": true, "requires": { - "find-up": "^4.0.0" + "find-up": "^2.1.0" } }, "pn": { @@ -5707,15 +5872,15 @@ "dev": true }, "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, "prettier": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.5.tgz", - "integrity": "sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.1.2.tgz", + "integrity": "sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg==", "dev": true }, "prettier-linter-helpers": { @@ -5740,12 +5905,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -5816,34 +5980,24 @@ "dev": true }, "read-pkg": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", - "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", "dev": true, "requires": { - "@types/normalize-package-data": "^2.4.0", - "normalize-package-data": "^2.5.0", - "parse-json": "^5.0.0", - "type-fest": "^0.6.0" - }, - "dependencies": { - "type-fest": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", - "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", - "dev": true - } + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" } }, "read-pkg-up": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", - "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", "dev": true, "requires": { - "find-up": "^4.1.0", - "read-pkg": "^5.2.0", - "type-fest": "^0.8.1" + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" } }, "realpath-native": { @@ -5852,12 +6006,6 @@ "integrity": "sha512-v1SEYUOXXdbBZK8ZuNgO4TBjamPsiSgcFr0aP+tEKpQZK8vooEUqV6nm6Cv502mX4NF2EfsnVqtNAHG+/6Ur1Q==", "dev": true }, - "regenerator-runtime": { - "version": "0.13.5", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz", - "integrity": "sha512-ZS5w8CpKFinUzOwW3c83oPeVXoNsrLsaCoLtJvAClH135j/R77RuymhiSErhm2lKcwSCIpmvIWSbDkIfAqKQlA==", - "dev": true - }, "regex-not": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", @@ -5933,21 +6081,21 @@ } }, "request-promise-core": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.3.tgz", - "integrity": "sha512-QIs2+ArIGQVp5ZYbWD5ZLCY29D5CfWizP8eWnm8FoGD1TX61veauETVQbrV60662V0oFBkrDOuaBI8XgtuyYAQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.4.tgz", + "integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==", "dev": true, "requires": { - "lodash": "^4.17.15" + "lodash": "^4.17.19" } }, "request-promise-native": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.8.tgz", - "integrity": "sha512-dapwLGqkHtwL5AEbfenuzjTYg35Jd6KPytsC2/TLkVMz8rm+tNt72MGUWT1RP/aYawMpN6HqbNGBQaRcBtjQMQ==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.9.tgz", + "integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==", "dev": true, "requires": { - "request-promise-core": "1.1.3", + "request-promise-core": "1.1.4", "stealthy-require": "^1.1.1", "tough-cookie": "^2.3.3" }, @@ -5977,11 +6125,12 @@ "dev": true }, "resolve": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", - "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.18.1.tgz", + "integrity": "sha512-lDfCPaMKfOJXjy0dPayzPdF1phampNWr3qFCjAu+rw/qbQmr5jWH5xN2hwh9QKfw9E5v4hwV7A+jrCmL8yjjqA==", "dev": true, "requires": { + "is-core-module": "^2.0.0", "path-parse": "^1.0.6" } }, @@ -6021,9 +6170,9 @@ "dev": true }, "rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "requires": { "glob": "^7.1.3" } @@ -6206,10 +6355,9 @@ } }, "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "set-blocking": { "version": "2.0.0", @@ -6237,6 +6385,15 @@ "requires": { "is-extendable": "^0.1.0" } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } } } }, @@ -6286,14 +6443,6 @@ "ansi-styles": "^3.2.0", "astral-regex": "^1.0.0", "is-fullwidth-code-point": "^2.0.0" - }, - "dependencies": { - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - } } }, "snapdragon": { @@ -6486,9 +6635,9 @@ } }, "spdx-license-ids": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz", - "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==", + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.6.tgz", + "integrity": "sha512-+orQK83kyMva3WyPf59k1+Y525csj5JejicWut55zeTWANuN17qSiSLUXWtzHeNWORSvT7GLDJ/E/XiIWoXBTw==", "dev": true }, "split-string": { @@ -6563,71 +6712,130 @@ "requires": { "astral-regex": "^1.0.0", "strip-ansi": "^5.2.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } } }, "string-width": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", - "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "dev": true, "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" }, "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "ansi-regex": "^4.1.0" } } } }, "string.prototype.trimend": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz", - "integrity": "sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.2.tgz", + "integrity": "sha512-8oAG/hi14Z4nOVP0z6mdiVZ/wqjDtWSLygMigTzAb+7aPEDTleeFf+WrF+alzecxIRkckkJVn+dTlwzJXORATw==", "dev": true, "requires": { "define-properties": "^1.1.3", - "es-abstract": "^1.17.5" + "es-abstract": "^1.18.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + } } }, "string.prototype.trimstart": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz", - "integrity": "sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.2.tgz", + "integrity": "sha512-7F6CdBTl5zyu30BJFdzSTlSlLPwODC23Od+iLoVH8X6+3fvDPPuBVVj9iaB1GOsSTSIgVfsfm27R2FGrAPznWg==", "dev": true, "requires": { "define-properties": "^1.1.3", - "es-abstract": "^1.17.5" + "es-abstract": "^1.18.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + } } }, "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { - "ansi-regex": "^4.1.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "dev": true - } + "ansi-regex": "^5.0.0" } }, "strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", "dev": true }, "strip-eof": { @@ -6673,9 +6881,9 @@ "dev": true }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -6699,31 +6907,6 @@ "lodash": "^4.17.14", "slice-ansi": "^2.1.0", "string-width": "^3.0.0" - }, - "dependencies": { - "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "dev": true, - "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - } - } } }, "terminal-link": { @@ -6765,6 +6948,16 @@ "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", "requires": { "rimraf": "^3.0.0" + }, + "dependencies": { + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "requires": { + "glob": "^7.1.3" + } + } } }, "tmp-promise": { @@ -6775,14 +6968,6 @@ "tmp": "0.1.0" }, "dependencies": { - "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "requires": { - "glob": "^7.1.3" - } - }, "tmp": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.1.0.tgz", @@ -6876,29 +7061,12 @@ "json5": "^1.0.1", "minimist": "^1.2.0", "strip-bom": "^3.0.0" - }, - "dependencies": { - "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - } } }, "tslib": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.13.0.tgz", - "integrity": "sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q==", + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", "dev": true }, "tsutils": { @@ -6931,12 +7099,12 @@ "dev": true }, "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "requires": { - "prelude-ls": "~1.1.2" + "prelude-ls": "^1.2.1" } }, "type-detect": { @@ -7026,9 +7194,9 @@ } }, "uri-js": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", - "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.0.tgz", + "integrity": "sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g==", "dev": true, "requires": { "punycode": "^2.1.0" @@ -7174,9 +7342,9 @@ "dev": true }, "windows-release": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.1.tgz", - "integrity": "sha512-Pngk/RDCaI/DkuHPlGTdIkDiTAnAkyMjoQMZqRsxydNl1qGXNIoZrB7RK8g53F2tEgQBMqQJHQdYZuQEEAu54A==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.3.tgz", + "integrity": "sha512-OSOGH1QYiW5yVor9TtmXKQvt2vjQqbYS+DqmsZw+r7xDwLXEeT3JGW0ZppFmHx4diyXmxt238KFR3N9jzevBRg==", "requires": { "execa": "^1.0.0" } @@ -7199,12 +7367,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -7223,13 +7390,27 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" } } } @@ -7278,15 +7459,6 @@ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true }, - "xregexp": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-4.3.0.tgz", - "integrity": "sha512-7jXDIFXh5yJ/orPn4SXjuVrWWoi4Cr8jfV1eHv9CixKSbU+jY4mxfrBwAuDvupPNKpMUY+FeIqsVw/JLT9+B8g==", - "dev": true, - "requires": { - "@babel/runtime-corejs3": "^7.8.3" - } - }, "y18n": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", @@ -7294,13 +7466,13 @@ "dev": true }, "yargs": { - "version": "15.4.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.0.tgz", - "integrity": "sha512-D3fRFnZwLWp8jVAAhPZBsmeIHY8tTsb8ItV9KaAaopmC6wde2u6Yw29JBIZHXw14kgkRnYmDgmQU4FVMDlIsWw==", + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { "cliui": "^6.0.0", - "decamelize": "^3.2.0", + "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", @@ -7310,6 +7482,80 @@ "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" + }, + "dependencies": { + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + } } }, "yargs-parser": { @@ -7320,14 +7566,6 @@ "requires": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" - }, - "dependencies": { - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - } } } } diff --git a/package.json b/package.json index 5996c767..cf253e80 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "build-chain-action", - "version": "0.0.1", + "version": "2.0.0", "description": "GitHub action to define action chains", "main": "src/lib/api.js", "author": "Enrique Mingorance Cano ", @@ -29,6 +29,7 @@ "@actions/core": "^1.1.3", "@actions/exec": "^1.0.4", "@actions/glob": "^0.1.0", + "@kie/build-chain-configuration-reader": "^0.0.4", "@octokit/rest": "^17.6.0", "argparse": "^1.0.7", "fs-extra": "^9.0.0", @@ -38,7 +39,7 @@ "devDependencies": { "@zeit/ncc": "^0.22.3", "dotenv": "^8.2.0", - "eslint": "^7.5.0", + "eslint": "^7.10.0", "eslint-config-google": "^0.14.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", diff --git a/project-dependencies.yaml b/project-dependencies.yaml new file mode 100644 index 00000000..292c7ad6 --- /dev/null +++ b/project-dependencies.yaml @@ -0,0 +1,147 @@ +version: "1.0" +dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/lienzo-tests + dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/droolsjbpm-build-bootstrap + dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/kie-soup + dependencies: + - project: kiegroup/droolsjbpm-build-bootstrap + + - project: kiegroup/appformer + dependencies: + - project: kiegroup/droolsjbpm-build-bootstrap + - project: kiegroup/lienzo-tests + - project: kiegroup/kie-soup + + - project: kiegroup/droolsjbpm-knowledge + dependencies: + - project: kiegroup/kie-soup + + - project: kiegroup/drools + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-soup + + - project: kiegroup/jbpm + dependencies: + - project: kiegroup/drools + - project: kiegroup/kie-soup + + - project: kiegroup/optaplanner + dependencies: + - project: kiegroup/drools + mapping: + source: 7.x + target: master + - project: kiegroup/jbpm + mapping: + source: 7.x + target: master + + - project: kiegroup/kie-jpmml-integration + dependencies: + - project: kiegroup/drools + - project: kiegroup/jbpm + + - project: kiegroup/droolsjbpm-integration + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/kie-jpmml-integration + - project: kiegroup/jbpm + - project: kiegroup/kie-soup + + - project: kiegroup/openshift-drools-hacep + dependencies: + - project: kiegroup/droolsjbpm-integration + + - project: kiegroup/droolsjbpm-tools + dependencies: + - project: kiegroup/jbpm + - project: kiegroup/drools + - project: kiegroup/kie-soup + + - project: kiegroup/kie-uberfire-extensions + dependencies: + - project: kiegroup/appformer + + - project: kiegroup/kie-wb-playground + dependencies: + - project: kiegroup/openshift-drools-hacep + + - project: kiegroup/kie-wb-common + dependencies: + - project: kiegroup/kie-wb-playground + - project: kiegroup/droolsjbpm-integration + + - project: kiegroup/drools-wb + dependencies: + - project: kiegroup/kie-wb-common + + - project: kiegroup/optaplanner-wb + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/drools-wb + - project: kiegroup/drools + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/kie-soup + - project: kiegroup/kie-wb-common + - project: kiegroup/kie-wb-playground + + - project: kiegroup/jbpm-designer + dependencies: + - project: kiegroup/kie-wb-common + + - project: kiegroup/jbpm-work-items + dependencies: + - project: kiegroup/openshift-drools-hacep + - project: kiegroup/kie-wb-playground + + - project: kiegroup/jbpm-wb + dependencies: + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/drools-wb + - project: kiegroup/jbpm-designer + - project: kiegroup/jbpm-work-items + + - project: kiegroup/kie-docs + + - project: kiegroup/optaweb-employee-rostering + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + + - project: kiegroup/optaweb-vehicle-routing + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + + - project: kiegroup/kie-wb-distributions + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-soup + - project: kiegroup/drools + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/jbpm + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/jbpm-wb diff --git a/src/lib/action-utils.js b/src/lib/action-utils.js deleted file mode 100644 index b738de2a..00000000 --- a/src/lib/action-utils.js +++ /dev/null @@ -1,9 +0,0 @@ -const core = require("@actions/core"); - -function getWorkflowfileName() { - return core.getInput("workflow-file-name"); -} - -module.exports = { - getWorkflowfileName -}; diff --git a/src/lib/artifacts/build-chain-flow-archive-artifact-helper.js b/src/lib/artifacts/build-chain-flow-archive-artifact-helper.js new file mode 100644 index 00000000..3e0d2199 --- /dev/null +++ b/src/lib/artifacts/build-chain-flow-archive-artifact-helper.js @@ -0,0 +1,113 @@ +const { run: uploadArtifacts } = require("./upload-artifacts"); +const { logger } = require("../common"); + +async function archiveArtifacts(nodeTirggering, nodeArray, on) { + const nodesToArchive = getNodesToArchive(nodeTirggering, nodeArray); + logger.info( + nodesToArchive.length > 0 + ? `Archiving artifacts for ${nodesToArchive.map(node => node.project)}` + : "No artifacts to archive" + ); + + await uploadNodes(nodesToArchive, on); +} + +function getNodesToArchive(nodeTriggering, nodeArray) { + const archiveDependencies = + nodeTriggering.build["archive-artifacts"] && + nodeTriggering.build["archive-artifacts"].dependencies + ? nodeTriggering.build["archive-artifacts"].dependencies + : "none"; + + return archiveDependencies === "none" + ? [nodeTriggering].filter( + node => + node.build["archive-artifacts"] && + node.build["archive-artifacts"].paths + ) + : nodeArray.filter( + node => + node.build["archive-artifacts"] && + node.build["archive-artifacts"].paths && + (archiveDependencies === "all" || + archiveDependencies.includes(node.project) || + node.project === nodeTriggering.project) + ); +} + +async function uploadNodes(nodesToArchive, on) { + await Promise.allSettled( + nodesToArchive.map(async node => { + logger.info(`Project [${node.project}]. Uploading artifacts...`); + const uploadResponse = await uploadArtifacts( + node.build["archive-artifacts"], + on + ); + if (uploadResponse) { + const uploadArtifactsMessage = + uploadResponse.artifactItems && + uploadResponse.artifactItems.length > 0 + ? `Uploaded Items (${uploadResponse.artifactItems.length}): ${uploadResponse.artifactItems}.` + : ""; + if ( + uploadResponse.failedItems && + uploadResponse.failedItems.length > 0 + ) { + logger.error( + `Project [${node.project}] Failed State. Artifact [${uploadResponse.artifactName}]. Failed Items (${uploadResponse.failedItems.length}): ${uploadResponse.failedItems}. ${uploadArtifactsMessage}` + ); + return Promise.reject(uploadResponse); + } else { + logger.info( + `Project [${node.project}]. Artifact [${uploadResponse.artifactName}]. ${uploadArtifactsMessage}` + ); + return Promise.resolve(uploadResponse); + } + } else { + logger.info(`Project [${node.project}]. No artifacts uploaded`); + return Promise.resolve(undefined); + } + }) + ).then(promises => { + logger.info("-------------- ARCHIVE ARTIFACTS SUMMARY --------------"); + const totalUploadResponses = promises + .map(promiseResult => promiseResult.value || promiseResult.reason) + .filter( + uploadResponse => + uploadResponse && + uploadResponse.artifactItems && + uploadResponse.artifactItems.length > 0 + ); + const uploadedFiles = totalUploadResponses.flatMap( + uploadResponse => uploadResponse.artifactItems + ); + const failureUploadResponses = promises + .filter(promiseResult => promiseResult.reason) + .map(promiseResult => promiseResult.reason) + .filter( + uploadResponse => + uploadResponse && + uploadResponse.failedItems && + uploadResponse.failedItems.length > 0 + ); + const failedFiles = failureUploadResponses.flatMap( + uploadResponse => uploadResponse.failedItems + ); + logger.info( + `Artifacts uploaded (${ + totalUploadResponses.length + }): ${totalUploadResponses.map( + uploadResponse => uploadResponse.artifactName + )}. Files (${uploadedFiles.length}): ${uploadedFiles}` + ); + logger.info( + `Artifacts failed (${ + failureUploadResponses.length + }): ${failureUploadResponses.map( + uploadResponse => uploadResponse.artifactName + )}. Files (${failedFiles.length}): ${failedFiles}` + ); + }); +} + +module.exports = { archiveArtifacts }; diff --git a/src/lib/build-chain-flow-helper.js b/src/lib/build-chain-flow-helper.js index 31c15385..1c4961f9 100644 --- a/src/lib/build-chain-flow-helper.js +++ b/src/lib/build-chain-flow-helper.js @@ -6,58 +6,60 @@ const { getForkedProject } = require("./git"); const { logger } = require("./common"); -const { saveCheckoutInfo } = require("./context"); +const { + parentChainFromNode, + treatUrl +} = require("@kie/build-chain-configuration-reader"); +const { checkUrlExist } = require("./util/http"); -async function checkoutDependencies( - context, - dependencies, - currentTargetBranch -) { - const result = {}; - for (const dependencyKey of Object.keys(dependencies)) { - result[dependencyKey] = await checkoutProject( - context, - dependencyKey, - dependencies[dependencyKey], - currentTargetBranch - ); +async function checkoutDefinitionTree(context, treeNode) { + const nodeChain = await parentChainFromNode(treeNode); + let currentTargetBranch = context.config.github.targetBranch; + for (const node of [...nodeChain].reverse()) { + try { + node.checkoutInfo = await checkoutProject( + context, + node, + currentTargetBranch + ); + currentTargetBranch = node.checkoutInfo.targetBranch; + } catch (err) { + logger.error(`Error checking out project ${node.project}`); + throw err; + } } - return result; + + return nodeChain; } -async function checkoutProject( - context, - project, - dependencyInformation, - currentTargetBranch -) { - const dir = getDir(context.config.rootFolder, project); +async function checkoutProject(context, node, currentTargetBranch) { + logger.info(`[${node.project}] Checking out project`); + const dir = getDir(context.config.rootFolder, node.project); const checkoutInfo = await getCheckoutInfo( context, - dependencyInformation.group, - project, + node.repo.group, + node.repo.name, currentTargetBranch, - dependencyInformation.mapping + node.mapping ); if (checkoutInfo == undefined) { - const msg = `Trying to checking out ${project} into '${dir}'. It does not exist.`; + const msg = `Trying to checking out ${node.project} into '${dir}'. It does not exist.`; logger.error(msg); throw new Error(msg); } - if (checkoutInfo.merge) { logger.info( - `Merging ${context.config.github.serverUrl}/${dependencyInformation.group}/${project}:${checkoutInfo.targetBranch} into ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}` + `[${node.project}] Merging ${context.config.github.serverUrl}/${node.project}:${checkoutInfo.targetBranch} into ${context.config.github.serverUrl}/${checkoutInfo.group}/${checkoutInfo.project}:${checkoutInfo.branch}` ); try { await clone( - `${context.config.github.serverUrl}/${dependencyInformation.group}/${project}`, + `${context.config.github.serverUrl}/${node.project}`, dir, checkoutInfo.targetBranch ); } catch (err) { logger.error( - `Error checking out (before merging) ${context.config.github.serverUrl}/${dependencyInformation.group}/${project}:${context.config.github.targetBranch}` + `Error checking out (before merging) ${context.config.github.serverUrl}/${node.repo.group}/${node.project}:${context.config.github.targetBranch}` ); throw err; } @@ -91,7 +93,6 @@ async function checkoutProject( throw err; } } - saveCheckoutInfo(context, project, checkoutInfo); return checkoutInfo; } @@ -115,7 +116,7 @@ async function getCheckoutInfo( sourceGroup ); logger.info( - `Getting checkout Info for ${targetProject}. sourceProject: ${forkedProjectName} sourceGroup: ${sourceGroup}. sourceBranch: ${sourceBranch}. targetGroup: ${targetGroup}. targetBranch: ${targetBranch}. Mapping: ${ + `[${targetGroup}/${targetProject}] Getting checkout Info. sourceProject: ${forkedProjectName} sourceGroup: ${sourceGroup}. sourceBranch: ${sourceBranch}. targetGroup: ${targetGroup}. targetBranch: ${targetBranch}. Mapping: ${ mapping ? "source:" + mapping.source + " target:" + mapping.target : "not defined" @@ -198,9 +199,50 @@ async function getForkedProjectName(octokit, owner, project, wantedOwner) { } } +/** + * it checks what's the proper URL to retrieve definition from in case a URL with ${} expression is defined. It will try sourceGroup/sourceBranch then targetGroup/sourceBranch and then targetGroup/targetBranch in this order. + * @param {Object} context the context information + * @param {Object} definitionFile the definition file path or URL + */ +async function getFinalDefinitionFilePath(context, definitionFile) { + if (definitionFile.startsWith("http") && definitionFile.includes("${")) { + const sourceGroupAndBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.sourceGroup, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.sourceBranch + }); + if (!(await checkUrlExist(sourceGroupAndBranchOption))) { + const targetGroupSourceBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.group, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.sourceBranch + }); + if (!(await checkUrlExist(targetGroupSourceBranchOption))) { + const targetGroupAndBranchOption = treatUrl(definitionFile, { + GROUP: context.config.github.group, + PROJECT_NAME: context.config.github.project, + BRANCH: context.config.github.targetBranch + }); + if (!(await checkUrlExist(targetGroupAndBranchOption))) { + throw new Error( + `Definition file ${definitionFile} does not exist for any of these cases: ${sourceGroupAndBranchOption}, ${targetGroupSourceBranchOption} or ${targetGroupAndBranchOption}` + ); + } else { + return targetGroupAndBranchOption; + } + } else { + return targetGroupSourceBranchOption; + } + } else { + return sourceGroupAndBranchOption; + } + } + return definitionFile; +} + module.exports = { - checkoutDependencies, - checkoutProject, + checkoutDefinitionTree, getCheckoutInfo, - getDir + getDir, + getFinalDefinitionFilePath }; diff --git a/src/lib/build-chain-flow.js b/src/lib/build-chain-flow.js index 1d797f0a..98b9c17d 100644 --- a/src/lib/build-chain-flow.js +++ b/src/lib/build-chain-flow.js @@ -1,198 +1,128 @@ -const { checkoutProject, getDir } = require("./build-chain-flow-helper"); -const { printCheckoutInformation } = require("./summary"); const { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation -} = require("./workflow-information/reader"); + checkoutDefinitionTree, + getDir, + getFinalDefinitionFilePath +} = require("./build-chain-flow-helper"); +const { getTreeForProject } = require("@kie/build-chain-configuration-reader"); + +const { printCheckoutInformation } = require("./summary"); const { logger } = require("./common"); -const { execute } = require("./command"); +const { execute } = require("./command/command"); const { treatCommand } = require("./command/command-treatment-delegator"); const core = require("@actions/core"); -const uploadArtifacts = require("./artifacts/upload-artifacts"); -const { getCheckoutInfo } = require("./context"); +const { + archiveArtifacts +} = require("./artifacts/build-chain-flow-archive-artifact-helper"); async function start(context) { core.startGroup( - `Checkout ${context.config.github.group}/${context.config.github.project}.` + `Checking out ${context.config.github.groupProject} and its dependencies` ); - const projectFolder = getDir( - context.config.rootFolder, - context.config.github.project - ); - await checkoutProject( + const definitionFile = await getFinalDefinitionFilePath( context, - context.config.github.project, - { - group: context.config.github.group - }, - context.config.github.targetBranch + context.config.github.inputs.definitionFile + ); + const definitionTree = await getTreeForProject( + definitionFile, + context.config.github.repository ); - const workflowInformation = readWorkflowInformation( - context.config.github.project, - context.config.github.jobId, - `.github/workflows/${context.config.github.flowFile}`, - context.config.github.group, - context.config.matrixVariables, - projectFolder + logger.info( + `Tree for project ${ + context.config.github.repository + } loaded from ${definitionFile}. Dependencies: ${ + definitionTree.dependencies + ? definitionTree.dependencies.map(node => node.project) + : "no dependencies" + }` ); + const nodeChain = await checkoutDefinitionTree(context, definitionTree); core.endGroup(); - const parentWorkflowInformationArray = ( - await checkoutParentsAndGetWorkflowInformation( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ) - ).reverse(); - core.startGroup(`Checkout Summary...`); - printCheckoutInformation(getCheckoutInfo(context)); + printCheckoutInformation( + nodeChain.reduce((acc, curr) => { + acc[curr.project] = curr.checkoutInfo; + return acc; + }, {}) + ); core.endGroup(); - const executionResult = await executeBuildCommandsWorkflowInformation( + const executionResult = await executeBuild( context.config.rootFolder, - workflowInformation, - parentWorkflowInformationArray + nodeChain, + context.config.github.repository ) .then(() => true) .catch(e => e); core.startGroup(`Archiving artifacts...`); await archiveArtifacts( - workflowInformation, - parentWorkflowInformationArray.concat(workflowInformation), + nodeChain.find(node => node.project === context.config.github.repository), + nodeChain, executionResult === true ? ["success", "always"] : ["failure", "always"] ); core.endGroup(); + if (executionResult !== true) { logger.error(executionResult); throw new Error( - "Command executions have failed, please review latest execution" + `Command executions have failed, please review latest execution ${executionResult}` + ); + } +} + +async function executeBuild(rootFolder, nodeChain, projectTriggeringJob) { + for await (const node of nodeChain) { + await executeNodeBuildCommands( + rootFolder, + node, + projectTriggeringJob === node.project ); } } -async function executeBuildCommandsWorkflowInformation( +async function executeNodeBuildCommands( rootFolder, - workflowInformation, - parentWorkflowInformationArray + node, + isProjectTriggeringJob ) { - for await (const wi of parentWorkflowInformationArray) { + const dir = getDir(rootFolder, node.project); + if (node.build["build-command"].before) { await executeBuildCommands( - getDir(rootFolder, wi.project), - wi["buildCommandsUpstream"] || wi["buildCommands"], - wi.project + dir, + getCommand(node.build["build-command"].before, isProjectTriggeringJob), + node.project ); } await executeBuildCommands( - getDir(rootFolder, workflowInformation.project), - workflowInformation["buildCommands"], - workflowInformation.project + dir, + getCommand(node.build["build-command"], isProjectTriggeringJob), + node.project ); + if (node.build["build-command"].after) { + await executeBuildCommands( + dir, + getCommand(node.build["build-command"].after, isProjectTriggeringJob), + node.project + ); + } } -async function archiveArtifacts( - workflowInformationTriggering, - workflowInformationArray, - on -) { - const archiveDependencies = - workflowInformationTriggering.archiveArtifacts.dependencies; - logger.info( - `${archiveDependencies} parent artifact(s) will be treated to be uploaded. Events ${on}` - ); - const wiArrayWithArtifacts = - archiveDependencies === "none" - ? [workflowInformationTriggering].filter(wi => wi.archiveArtifacts.paths) - : workflowInformationArray.filter( - wi => - wi.archiveArtifacts.paths && - (archiveDependencies === "all" || - archiveDependencies.includes(wi.project) || - wi.project === workflowInformationTriggering.project) - ); - logger.info( - wiArrayWithArtifacts.length > 0 - ? `Archiving artifacts for ${wiArrayWithArtifacts.map(wi => wi.project)}` - : "No artifacts to archive" - ); - - await Promise.allSettled( - wiArrayWithArtifacts.map(async wi => { - logger.info(`Project [${wi.project}]. Uploading artifacts...`); - const uploadResponse = await uploadArtifacts.run(wi.archiveArtifacts, on); - if (uploadResponse) { - const uploadArtifactsMessage = - uploadResponse.artifactItems && - uploadResponse.artifactItems.length > 0 - ? `Uploaded Items (${uploadResponse.artifactItems.length}): ${uploadResponse.artifactItems}.` - : ""; - if ( - uploadResponse.failedItems && - uploadResponse.failedItems.length > 0 - ) { - logger.error( - `Project [${wi.project}] Failed State. Artifact [${uploadResponse.artifactName}]. Failed Items (${uploadResponse.failedItems.length}): ${uploadResponse.failedItems}. ${uploadArtifactsMessage}` - ); - return Promise.reject(uploadResponse); - } else { - logger.info( - `Project [${wi.project}]. Artifact [${uploadResponse.artifactName}]. ${uploadArtifactsMessage}` - ); - return Promise.resolve(uploadResponse); - } - } else { - logger.info(`Project [${wi.project}]. No artifacts uploaded`); - return Promise.resolve(undefined); - } - }) - ).then(promises => { - logger.info("-------------- ARCHIVE ARTIFACTS SUMMARY --------------"); - const totalUploadResponses = promises - .map(promiseResult => promiseResult.value || promiseResult.reason) - .filter( - uploadResponse => - uploadResponse && - uploadResponse.artifactItems && - uploadResponse.artifactItems.length > 0 - ); - const uploadedFiles = totalUploadResponses.flatMap( - uploadResponse => uploadResponse.artifactItems - ); - const failureUploadResponses = promises - .filter(promiseResult => promiseResult.reason) - .map(promiseResult => promiseResult.reason) - .filter( - uploadResponse => - uploadResponse && - uploadResponse.failedItems && - uploadResponse.failedItems.length > 0 - ); - const failedFiles = failureUploadResponses.flatMap( - uploadResponse => uploadResponse.failedItems - ); - logger.info( - `Artifacts uploaded (${ - totalUploadResponses.length - }): ${totalUploadResponses.map( - uploadResponse => uploadResponse.artifactName - )}. Files (${uploadedFiles.length}): ${uploadedFiles}` - ); - logger.info( - `Artifacts failed (${ - failureUploadResponses.length - }): ${failureUploadResponses.map( - uploadResponse => uploadResponse.artifactName - )}. Files (${failedFiles.length}): ${failedFiles}` - ); - }); +function getCommand(buildCommand, isProjectTriggeringJob) { + return isProjectTriggeringJob + ? buildCommand.current + : buildCommand.upstream || buildCommand.current; } async function executeBuildCommands(cwd, buildCommands, project) { - for (const command of buildCommands) { - await execute(cwd, treatCommand(command), project); + if (buildCommands) { + for (const command of Array.isArray(buildCommands) + ? buildCommands.filter(c => c) + : [buildCommands]) { + core.startGroup(`[${project}]. Command: '${command}' in dir ${cwd}`); + await execute(cwd, treatCommand(command)); + core.endGroup(); + } } } diff --git a/src/lib/command.js b/src/lib/command/command.js similarity index 61% rename from src/lib/command.js rename to src/lib/command/command.js index 12398822..03bd28ff 100644 --- a/src/lib/command.js +++ b/src/lib/command/command.js @@ -1,6 +1,5 @@ -const { logger } = require("./common"); +const { logger } = require("../common"); const exec = require("@actions/exec"); -const core = require("@actions/core"); class ExitError extends Error { constructor(message, code) { @@ -9,13 +8,11 @@ class ExitError extends Error { } } -async function execute(cwd, command, project) { - core.startGroup(`[${project}]. Command: '${command}' in dir ${cwd}`); +async function execute(cwd, command) { logger.info(`Execute command '${command}' in dir '${cwd}'`); const options = {}; options.cwd = cwd; await exec.exec(command, [], options); - core.endGroup(); } module.exports = { diff --git a/src/lib/config.js b/src/lib/config.js index 413f5d21..aad9b4fe 100644 --- a/src/lib/config.js +++ b/src/lib/config.js @@ -1,9 +1,15 @@ const { ClientError, logger } = require("./common"); -const { getWorkflowfileName } = require("./action-utils"); +const { getDefinitionFile } = require("./util/action-utils"); const GITHUB_URL_REGEXP = /^https:\/\/github.com\/([^/]+)\/([^/]+)\/(pull|tree)\/([^ ]+)$/; const GIT_URL_REGEXP = /^(https?:\/\/.*\/)([^/]+)\/([^/]+)\/(pull|tree)\/([^ ]+)$/; +function getInputs() { + return { + definitionFile: getDefinitionFile() + }; +} + async function createConfig(eventData, rootFolder, env = {}) { async function parseGitHub(env) { return { @@ -25,9 +31,10 @@ async function createConfig(eventData, rootFolder, env = {}) { repository: env["GITHUB_REPOSITORY"], // Ginxo/lienzo-tests group: env["GITHUB_REPOSITORY"].split("/")[0], // Ginxo project: env["GITHUB_REPOSITORY"].split("/")[1], // lienzo-tests - flowFile: getWorkflowfileName(), // main.yml + groupProject: env["GITHUB_REPOSITORY"], workflowName: env["GITHUB_WORKFLOW"], // Build Chain - ref: env["GITHUB_REF"] // refs/pull/1/merge' + ref: env["GITHUB_REF"], // refs/pull/1/merge' + inputs: getInputs() }; } return { diff --git a/src/lib/context.js b/src/lib/context.js deleted file mode 100644 index 37b47562..00000000 --- a/src/lib/context.js +++ /dev/null @@ -1,26 +0,0 @@ -function getCheckoutInfo(context) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; - } - return context.checkoutInfo; -} - -function getCheckoutInfoProject(context, project) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; - } - return context.checkoutInfo[project]; -} - -function saveCheckoutInfo(context, project, checkoutInfo) { - if (!context.checkoutInfo) { - context.checkoutInfo = {}; - } - return (context.checkoutInfo[project] = checkoutInfo); -} - -module.exports = { - getCheckoutInfo, - getCheckoutInfoProject, - saveCheckoutInfo -}; diff --git a/src/lib/util/action-utils.js b/src/lib/util/action-utils.js new file mode 100644 index 00000000..bc22dc54 --- /dev/null +++ b/src/lib/util/action-utils.js @@ -0,0 +1,9 @@ +const core = require("@actions/core"); + +function getDefinitionFile() { + return core.getInput("definition-file"); +} + +module.exports = { + getDefinitionFile +}; diff --git a/src/lib/util/http.js b/src/lib/util/http.js new file mode 100644 index 00000000..4cb672bb --- /dev/null +++ b/src/lib/util/http.js @@ -0,0 +1,14 @@ +const http = require("http"); +const https = require("https"); + +function checkUrlExist(url) { + return new Promise(resolve => { + (url.startsWith("https://") ? https : http).get(url, response => { + resolve(200 === response.statusCode); + }); + }); +} + +module.exports = { + checkUrlExist +}; diff --git a/src/lib/workflow-information/reader.js b/src/lib/workflow-information/reader.js deleted file mode 100644 index aadbbbe4..00000000 --- a/src/lib/workflow-information/reader.js +++ /dev/null @@ -1,286 +0,0 @@ -const fs = require("fs"); -const path = require("path"); -const { logger } = require("../common"); -const { getYamlFileContent } = require("../fs-helper"); -var assert = require("assert"); -const core = require("@actions/core"); -const { checkoutDependencies, getDir } = require("../build-chain-flow-helper"); - -async function checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - currentTargetBranch, - workflowInformation -) { - if (!projectList[project]) { - projectList.push(project); - if ( - workflowInformation.parentDependencies && - Object.keys(workflowInformation.parentDependencies).length > 0 - ) { - core.startGroup( - `Checking out dependencies [${Object.keys( - workflowInformation.parentDependencies - ).join(", ")}] for project ${project}` - ); - const checkoutInfos = await checkoutDependencies( - context, - workflowInformation.parentDependencies, - currentTargetBranch - ); - core.endGroup(); - for (const [parentProject, parentDependency] of Object.entries( - workflowInformation.parentDependencies - ).filter( - ([parentDependencyKey]) => - parentDependencyKey !== null && parentDependencyKey !== "" - )) { - const dir = getDir(context.config.rootFolder, parentProject); - const parentWorkflowInformation = readWorkflowInformation( - parentProject, - parentDependency.jobId - ? parentDependency.jobId - : workflowInformation.jobId, - `.github/workflows/${ - parentDependency.flowFile - ? parentDependency.flowFile - : workflowInformation.flowFile - }`, - context.config.github.group, - context.config.matrixVariables, - dir - ); - - if (parentWorkflowInformation) { - return [parentWorkflowInformation].concat( - await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - parentProject, - checkoutInfos[parentProject].targetBranch, - parentWorkflowInformation - ) - ); - } else { - logger.warn( - `workflow information ${ - parentDependency.flowFile - ? parentDependency.flowFile - : context.config.github.flowFile - } not present for ${parentProject}.` - ); - return []; - } - } - } - } - return []; -} - -function readWorkflowInformation( - project, - jobId, - workflowFilePath, - defaultGroup, - matrixVariables, - dir = "." -) { - const filePath = path.join(dir, workflowFilePath); - if (!fs.existsSync(filePath)) { - logger.warn(`file ${filePath} does not exist`); - return undefined; - } - return parseWorkflowInformation( - project, - jobId, - getYamlFileContent(filePath), - defaultGroup, - matrixVariables - ); -} - -function parseWorkflowInformation( - project, - jobId, - workflowData, - defaultGroup, - matrixVariables -) { - assert(workflowData.jobs[jobId], `The job id '${jobId}' does not exist`); - const buildChainStep = workflowData.jobs[jobId].steps.find( - step => step.uses && step.uses.includes("github-action-build-chain") - ); - assert( - buildChainStep.with["workflow-file-name"], - `The workflow file name does not exist for '${project}' and it's mandatory` - ); - buildChainStep.with = Object.entries(buildChainStep.with) - .filter(([key]) => key !== "matrix-variables") - .reduce((acc, [key, value]) => { - acc[key] = treatMatrixVariables(value, matrixVariables); - return acc; - }, {}); - return { - id: buildChainStep.id, - project, - name: buildChainStep.name, - buildCommands: splitCommands(buildChainStep.with["build-command"]), - buildCommandsUpstream: splitCommands( - buildChainStep.with["build-command-upstream"] - ), - buildCommandsDownstream: splitCommands( - buildChainStep.with["build-command-downstream"] - ), - childDependencies: dependenciesToObject( - buildChainStep.with["child-dependencies"], - defaultGroup - ), - parentDependencies: dependenciesToObject( - buildChainStep.with["parent-dependencies"], - defaultGroup - ), - archiveArtifacts: getArchiveArtifacts(buildChainStep, project), - jobId, - flowFile: buildChainStep.with["workflow-file-name"] - }; -} - -function splitCommands(commands) { - return commands - ? commands - .split("\n") - .filter(line => line) - .map(item => item.trim()) - : undefined; -} - -function treatMatrixVariables(withExpression, matrixVariables) { - let result = withExpression; - const exp = /((\${{ )([a-zA-Z0-9\\.\\-]*)( }}))/g; - let match = undefined; - while ((match = exp.exec(withExpression))) { - if (!matrixVariables || !matrixVariables[match[3]]) { - throw new Error( - `The variable '${match[3]}' is not defined in "with" 'matrix-variables' so it can't be replaced. Please define it in the flow triggering the job.` - ); - } - result = result.replace(`${match[1]}`, matrixVariables[match[3]]); - } - return result; -} - -function getArchiveArtifacts(step, defaultName = "artifact") { - return { - name: step.with["archive-artifacts-name"] - ? step.with["archive-artifacts-name"] - : step.with["archive-artifacts-path"] - ? defaultName - : undefined, - - paths: treatArchiveArtifactsPath(step.with["archive-artifacts-path"]), - ifNoFilesFound: step.with["archive-artifacts-if-no-files-found"] - ? step.with["archive-artifacts-if-no-files-found"] - : step.with["archive-artifacts-path"] - ? "warn" - : undefined, - dependencies: treatArchiveArtifactsDependencies( - step.with["archive-artifacts-dependencies"] - ) - }; -} - -function treatArchiveArtifactsPath(archiveArtifacts) { - return archiveArtifacts - ? archiveArtifacts - .split("\n") - .filter(line => line) - .reduce((acc, pathExpression) => { - acc.push(convertPathExpressionToPath(pathExpression)); - return acc; - }, []) - : undefined; -} - -function convertPathExpressionToPath(pathExpression) { - const match = pathExpression.match(/([^@]*)@?(always|success|failure)?/); - return match - ? { - path: match[1], - on: match[2] ? match[2] : "success" - } - : pathExpression; -} - -function treatArchiveArtifactsDependencies(archiveArtifactsDependencies) { - if (archiveArtifactsDependencies) { - if ( - archiveArtifactsDependencies === "all" || - archiveArtifactsDependencies === "none" - ) { - return archiveArtifactsDependencies; - } else { - return archiveArtifactsDependencies - .split("\n") - .filter(line => line) - .map(item => item.trim()); - } - } else { - return "none"; - } -} - -function dependenciesToObject(dependencies, defaultGroup) { - const dependenciesObject = {}; - dependencies - ? dependencies - .split("\n") - .filter(line => line) - .forEach(dependency => { - const projectName = getProjectName(dependency.trim()); - dependenciesObject[projectName] = { - group: getGroupFromDependency(dependency, defaultGroup), - mapping: getMappingFromDependency(dependency), - flowFile: getFlowFileFromDependency(dependency), - jobId: getJobIdFromDependency(dependency) - }; - }) - : {}; - return dependenciesObject; -} - -function getProjectName(dependency) { - const match = dependency.match(/(.*\/)?([\w\-.]*).*/); - return match[2]; -} - -function getGroupFromDependency(dependency, defaultGroup) { - const match = dependency.match(/([\w\-.]*)\//); - return match ? match[1] : defaultGroup; -} - -function getMappingFromDependency(dependency) { - const match = dependency.match(/@([\w\-.]*):([\w\-.]*)/); - return match - ? { - source: match[1], - target: match[2] - } - : undefined; -} - -function getFlowFileFromDependency(dependency) { - const match = dependency.match(/\|([\w\-.]*):?/); - return match && match[1] ? match[1] : undefined; -} - -function getJobIdFromDependency(dependency) { - const match = dependency.match(/\|.*:([\w\-.]*)/); - return match && match[1] ? match[1] : undefined; -} - -module.exports = { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation, - dependenciesToObject -}; diff --git a/test/build-chain-flow-helper.test.js b/test/build-chain-flow-helper.test.js index 66b152cc..31026ebc 100644 --- a/test/build-chain-flow-helper.test.js +++ b/test/build-chain-flow-helper.test.js @@ -1,7 +1,7 @@ const { getCheckoutInfo, - checkoutDependencies, - checkoutProject + checkoutDefinitionTree, + getFinalDefinitionFilePath } = require("../src/lib/build-chain-flow-helper"); jest.mock("../src/lib/git"); const { @@ -12,6 +12,12 @@ const { getForkedProject: getForkedProjectMock } = require("../src/lib/git"); +const { getTreeForProject } = require("@kie/build-chain-configuration-reader"); +const path = require("path"); + +const { checkUrlExist } = require("../src/lib/util/http"); +jest.mock("../src/lib/util/http"); + afterEach(() => { jest.clearAllMocks(); }); @@ -322,12 +328,17 @@ test("getCheckoutInfo. sourceBranch and sourceTarget exist with merge. Mapping n expect(result.targetBranch).toEqual("targetBranch"); }); -test("checkoutDependencies", async () => { +test("checkoutDefinitionTree", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", sourceGroup: "sourceGroup", author: "author", @@ -337,428 +348,715 @@ test("checkoutDependencies", async () => { rootFolder: "folder" } }; - const dependencies = { - "project-A": { group: "groupA" }, - projectB: { - group: "groupB", - mapping: { source: "tBranch", target: "tBranchMapped" } - }, - projectC: { group: "groupC" }, - projectD: { - group: "groupD", - mapping: { source: "branchX", target: "branchY" } - }, - projectE: { - group: "groupE", - mapping: { source: "branchX", target: "tBranchMapped" } - } - }; - doesBranchExistMock - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(true); - hasPullRequestMock - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(false); getForkedProjectMock - .mockResolvedValueOnce({ name: "project-A" }) - .mockResolvedValueOnce({ name: "projectB" }) - .mockResolvedValueOnce({ name: "projectC" }) - .mockResolvedValueOnce({ name: "projectD" }) - .mockResolvedValueOnce({ name: "projectEFroked" }); + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); + // Act - await checkoutDependencies( - context, - dependencies, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupA/project-A", - "folder/project_A", - "tBranch" - ); + expect(mergeMock).toHaveBeenCalledTimes(2); expect(mergeMock).toHaveBeenCalledWith( - "folder/project_A", + "folder/kiegroup/lienzo_core", "sourceGroup", - "project-A", + "lienzo-core-forked", "sBranch" ); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupB/projectB", - "folder/projectB", - "tBranchMapped" - ); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupC/projectC", - "folder/projectC", - "tBranch" - ); expect(mergeMock).toHaveBeenCalledWith( - "folder/projectC", - "groupC", - "projectC", + "folder/kiegroup/droolsjbpm_build_bootstrap", + "sourceGroup", + "droolsjbpm-build-bootstrap-forked", "sBranch" ); + + expect(cloneMock).toHaveBeenCalledTimes(2); expect(cloneMock).toHaveBeenCalledWith( - "URL/groupD/projectD", - "folder/projectD", + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", "tBranch" ); expect(cloneMock).toHaveBeenCalledWith( - "URL/sourceGroup/projectEFroked", - "folder/projectE", - "sBranch" - ); - expect(mergeMock).not.toHaveBeenCalledWith( - "folder/projectE", - "sourceGroup", - "projectEFroked", - "sBranch" + "URL/kiegroup/droolsjbpm-build-bootstrap", + "folder/kiegroup/droolsjbpm_build_bootstrap", + "tBranch" ); - expect(mergeMock).not.toHaveBeenCalledWith( - "folder/projectE", - "groupE", - "projectEFroked", - "sBranch" + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); }); -test("checkoutProject sGroup/projectXFroked:sBranch exists has PR", async () => { +test("checkoutDefinitionTree has no PR", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "tBranch" }, rootFolder: "folder" } }; - doesBranchExistMock.mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + getForkedProjectMock + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); expect(mergeMock).toHaveBeenCalledTimes(1); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", + "sBranch" + ); + + expect(cloneMock).toHaveBeenCalledTimes(2); expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", "tBranch" ); - expect(mergeMock).toHaveBeenCalledWith( - "folder/projectx", - "sGroup", - "projectXFroked", + expect(cloneMock).toHaveBeenCalledWith( + "URL/sourceGroup/droolsjbpm-build-bootstrap-forked", + "folder/kiegroup/droolsjbpm_build_bootstrap", "sBranch" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" + ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: false + }); }); -test("checkoutProject sGroup/projectXFroked:sBranch exists has no PR", async () => { +test("checkoutDefinitionTree sBranch does not exists but has PR", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "tBranch" }, rootFolder: "folder" } }; - doesBranchExistMock.mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(false); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + getForkedProjectMock + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); + // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(cloneMock).toHaveBeenCalledWith( - "URL/sGroup/projectXFroked", - "folder/projectx", + expect(mergeMock).toHaveBeenCalledTimes(2); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", + "sBranch" + ); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/droolsjbpm_build_bootstrap", + "kiegroup", + "droolsjbpm-build-bootstrap", "sBranch" ); - expect(mergeMock).not.toHaveBeenCalled(); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + + expect(cloneMock).toHaveBeenCalledTimes(2); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", + "tBranch" + ); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/droolsjbpm-build-bootstrap", + "folder/kiegroup/droolsjbpm_build_bootstrap", + "tBranch" + ); + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" + ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap", + group: "kiegroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); }); -test("checkoutProject sGroup/projectX:sBranch does not exists but groupx/projectX:sBranch has PR", async () => { +test("checkoutDefinitionTree sBranch does not exists but has PR no root Folder", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "tBranch" }, - rootFolder: "folder" + rootFolder: undefined } }; - doesBranchExistMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + getForkedProjectMock + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(mergeMock).toHaveBeenCalledTimes(1); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", - "tBranch" + expect(mergeMock).toHaveBeenCalledTimes(2); + expect(mergeMock).toHaveBeenCalledWith( + "./kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", + "sBranch" ); expect(mergeMock).toHaveBeenCalledWith( - "folder/projectx", - "groupx", - "projectx", + "./kiegroup/droolsjbpm_build_bootstrap", + "kiegroup", + "droolsjbpm-build-bootstrap", "sBranch" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + + expect(cloneMock).toHaveBeenCalledTimes(2); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/lienzo-core", + "./kiegroup/lienzo_core", + "tBranch" + ); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/droolsjbpm-build-bootstrap", + "./kiegroup/droolsjbpm_build_bootstrap", + "tBranch" + ); + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" + ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap", + group: "kiegroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); }); -test("checkoutProject author/projectX:sBranch does not exists but groupx/projectX:sBranch has PR no rootFolder", async () => { +test("checkoutDefinitionTree sBranch does not exists but has no PR", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "tBranch" }, - rootFolder: undefined + rootFolder: "folder" } }; - doesBranchExistMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + getForkedProjectMock + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true); // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); expect(mergeMock).toHaveBeenCalledTimes(1); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", + "sBranch" + ); + + expect(cloneMock).toHaveBeenCalledTimes(2); expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "./projectx", + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", "tBranch" ); - expect(mergeMock).toHaveBeenCalledWith( - "./projectx", - "groupx", - "projectx", + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/droolsjbpm-build-bootstrap", + "folder/kiegroup/droolsjbpm_build_bootstrap", "sBranch" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" + ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap", + group: "kiegroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: false + }); }); -test("checkoutProject author/projectX:sBranch does not exists but groupx/projectX:sBranch has no PR", async () => { +test("checkoutDefinitionTree sBranch does not exists but tBranch", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "tBranch" }, rootFolder: "folder" } }; - doesBranchExistMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(false); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + getForkedProjectMock + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); + doesBranchExistMock + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true); + hasPullRequestMock.mockResolvedValueOnce(true).mockResolvedValueOnce(true); // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(mergeMock).toHaveBeenCalledTimes(0); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", + expect(mergeMock).toHaveBeenCalledTimes(1); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", "sBranch" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + + expect(cloneMock).toHaveBeenCalledTimes(2); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", + "tBranch" + ); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/droolsjbpm-build-bootstrap", + "folder/kiegroup/droolsjbpm_build_bootstrap", + "tBranch" + ); + + expect(result.length).toBe(2); + expect(result[0].project).toStrictEqual("kiegroup/lienzo-core"); + expect(result[0].checkoutInfo).toStrictEqual({ + project: "lienzo-core-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: true + }); + expect(result[1].project).toStrictEqual( + "kiegroup/droolsjbpm-build-bootstrap" + ); + expect(result[1].checkoutInfo).toStrictEqual({ + project: "droolsjbpm-build-bootstrap", + group: "kiegroup", + branch: "tBranch", + targetGroup: "kiegroup", + targetBranch: "tBranch", + merge: false + }); }); -test("checkoutProject author/projectX:sBranch and groupx/projectX:sBranch but groupx/projectX:tBranch", async () => { +test("checkoutDefinitionTree with mapping", async () => { // Arrange + const project = "kiegroup/optaplanner"; + const definitionTree = await getTreeForProject( + path.join(".", "test", "resources", "build-config", "build-config.yaml"), + project + ); + const context = { config: { github: { - flowFile: "main.yml", serverUrl: "URL", + sourceGroup: "sourceGroup", author: "author", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" + targetBranch: "7.x" }, rootFolder: "folder" } }; + getForkedProjectMock + .mockResolvedValueOnce({ name: "optaplanner-forked" }) + .mockResolvedValueOnce({ name: "jbpm-forked" }) + .mockResolvedValueOnce({ name: "drools-forked" }) + .mockResolvedValueOnce({ name: "appformer-forked" }) + .mockResolvedValueOnce({ name: "kie-soup-forked" }) + .mockResolvedValueOnce({ name: "lienzo-tests-forked" }) + .mockResolvedValueOnce({ name: "droolsjbpm-build-bootstrap-forked" }) + .mockResolvedValueOnce({ name: "lienzo-core-forked" }); doesBranchExistMock - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true); + hasPullRequestMock + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(true) .mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); // Act - const result = await checkoutProject( - context, - "projectx", - { group: "groupx" }, - context.config.github.targetBranch - ); + const result = await checkoutDefinitionTree(context, definitionTree); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(hasPullRequestMock).toHaveBeenCalledTimes(0); - expect(mergeMock).toHaveBeenCalledTimes(0); + expect(mergeMock).toHaveBeenCalledTimes(8); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/optaplanner", + "sourceGroup", + "optaplanner-forked", + "sBranch" + ); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/jbpm", + "sourceGroup", + "jbpm-forked", + "sBranch" + ); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/drools", + "sourceGroup", + "drools-forked", + "sBranch" + ); + expect(mergeMock).toHaveBeenCalledWith( + "folder/kiegroup/lienzo_core", + "sourceGroup", + "lienzo-core-forked", + "sBranch" + ); + + expect(cloneMock).toHaveBeenCalledTimes(8); expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", - "tBranch" + "URL/kiegroup/optaplanner", + "folder/kiegroup/optaplanner", + "7.x" + ); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/jbpm", + "folder/kiegroup/jbpm", + "master" + ); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/drools", + "folder/kiegroup/drools", + "master" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + expect(cloneMock).toHaveBeenCalledWith( + "URL/kiegroup/lienzo-core", + "folder/kiegroup/lienzo_core", + "master" + ); + + expect(result.length).toBe(8); + expect(result[7].project).toStrictEqual("kiegroup/optaplanner"); + expect(result[7].checkoutInfo).toStrictEqual({ + project: "optaplanner-forked", + group: "sourceGroup", + branch: "sBranch", + targetGroup: "kiegroup", + targetBranch: "7.x", + merge: true + }); }); -test("checkoutProject sGroup/projectXFroked:sBranch exists has PR. With mapping matching", async () => { +test("getFinalDefinitionFilePath no url", async () => { // Arrange const context = { config: { github: { - flowFile: "main.yml", - serverUrl: "URL", - author: "author", + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" - }, - rootFolder: "folder" + targetBranch: "tBranch" + } } }; - doesBranchExistMock.mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + const definitionFile = "./definition-file.yaml"; // Act - const result = await checkoutProject( - context, - "projectx", - { - group: "groupx", - mapping: { source: "tBranch", target: "tBranchMapped" } - }, - context.config.github.targetBranch - ); + const result = await getFinalDefinitionFilePath(context, definitionFile); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(mergeMock).toHaveBeenCalledTimes(1); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", - "tBranchMapped" - ); - expect(mergeMock).toHaveBeenCalledWith( - "folder/projectx", - "sGroup", - "projectXFroked", - "sBranch" - ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); + expect(result).toBe(definitionFile); }); -test("checkoutProject sGroup/projectXFroked:sBranch exists has PR. With mapping matching", async () => { +test("getFinalDefinitionFilePath url no ${} expression", async () => { // Arrange const context = { config: { github: { - flowFile: "main.yml", - serverUrl: "URL", - author: "author", + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", sourceBranch: "sBranch", - targetBranch: "tBranch", - sourceGroup: "sGroup" - }, - rootFolder: "folder" + targetBranch: "tBranch" + } } }; - doesBranchExistMock.mockResolvedValueOnce(true); - hasPullRequestMock.mockResolvedValueOnce(true); - getForkedProjectMock.mockResolvedValueOnce({ name: "projectXFroked" }); + const definitionFile = "http://whateverurl.domain/file.yaml"; // Act - const result = await checkoutProject( - context, - "projectx", - { - group: "groupx", - mapping: { source: "tBranch", target: "tBranchMapped" } - }, - context.config.github.targetBranch + const result = await getFinalDefinitionFilePath(context, definitionFile); + + // Assert + expect(result).toBe(definitionFile); +}); + +test("getFinalDefinitionFilePath url. source group and branch ok", async () => { + // Arrange + const context = { + config: { + github: { + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", + sourceBranch: "sBranch", + targetBranch: "tBranch" + } + } + }; + const definitionFile = + "http://whateverurl.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/file.yaml"; + checkUrlExist.mockResolvedValueOnce(true); + // Act + const result = await getFinalDefinitionFilePath(context, definitionFile); + + // Assert + expect(checkUrlExist).toHaveBeenCalledTimes(1); + expect(result).toBe( + "http://whateverurl.domain/sGroup/projectx/sBranch/file.yaml" ); +}); + +test("getFinalDefinitionFilePath url. target group and source branch ok", async () => { + // Arrange + const context = { + config: { + github: { + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", + sourceBranch: "sBranch", + targetBranch: "tBranch" + } + } + }; + const definitionFile = + "http://whateverurl.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/file.yaml"; + checkUrlExist.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + // Act + const result = await getFinalDefinitionFilePath(context, definitionFile); + // Assert - expect(cloneMock).toHaveBeenCalledTimes(1); - expect(mergeMock).toHaveBeenCalledTimes(1); - expect(cloneMock).toHaveBeenCalledWith( - "URL/groupx/projectx", - "folder/projectx", - "tBranchMapped" + expect(checkUrlExist).toHaveBeenCalledTimes(2); + expect(result).toBe( + "http://whateverurl.domain/tGroup/projectx/sBranch/file.yaml" ); - expect(mergeMock).toHaveBeenCalledWith( - "folder/projectx", - "sGroup", - "projectXFroked", - "sBranch" +}); + +test("getFinalDefinitionFilePath url. target group and branch ok", async () => { + // Arrange + const context = { + config: { + github: { + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", + sourceBranch: "sBranch", + targetBranch: "tBranch" + } + } + }; + const definitionFile = + "http://whateverurl.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/file.yaml"; + checkUrlExist + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true); + // Act + const result = await getFinalDefinitionFilePath(context, definitionFile); + + // Assert + expect(checkUrlExist).toHaveBeenCalledTimes(3); + expect(result).toBe( + "http://whateverurl.domain/tGroup/projectx/tBranch/file.yaml" ); - expect(context.checkoutInfo).toStrictEqual({ projectx: result }); +}); + +test("getFinalDefinitionFilePath url. error", async () => { + // Arrange + const context = { + config: { + github: { + sourceGroup: "sGroup", + group: "tGroup", + project: "projectx", + sourceBranch: "sBranch", + targetBranch: "tBranch" + } + } + }; + const definitionFile = + "http://whateverurl.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/file.yaml"; + checkUrlExist + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(false); + // Act + try { + await getFinalDefinitionFilePath(context, definitionFile); + } catch (ex) { + expect(ex.message).toBe( + "Definition file http://whateverurl.domain/${GROUP}/${PROJECT_NAME}/${BRANCH}/file.yaml does not exist for any of these cases: http://whateverurl.domain/sGroup/projectx/sBranch/file.yaml, http://whateverurl.domain/tGroup/projectx/sBranch/file.yaml or http://whateverurl.domain/tGroup/projectx/tBranch/file.yaml" + ); + } }); diff --git a/test/build-chain-flow.test.js b/test/build-chain-flow.test.js index 96d1cb8d..ac7a516e 100644 --- a/test/build-chain-flow.test.js +++ b/test/build-chain-flow.test.js @@ -1,975 +1,449 @@ const { start } = require("../src/lib/build-chain-flow"); +const path = require("path"); const { - checkoutProject, - getDir + checkoutDefinitionTree, + getDir, + getFinalDefinitionFilePath } = require("../src/lib/build-chain-flow-helper"); jest.mock("../src/lib/build-chain-flow-helper"); -const { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation -} = require("../src/lib/workflow-information/reader"); -jest.mock("../src/lib/workflow-information/reader"); + const { run: runUploadArtifactsMock } = require("../src/lib/artifacts/upload-artifacts"); jest.mock("../src/lib/artifacts/upload-artifacts"); -const { execute } = require("../src/lib/command"); -jest.mock("../src/lib/command"); +const { + archiveArtifacts +} = require("../src/lib/artifacts/build-chain-flow-archive-artifact-helper"); +jest.mock("../src/lib/artifacts/build-chain-flow-archive-artifact-helper"); + +const { execute } = require("../src/lib/command/command"); +jest.mock("../src/lib/command/command"); jest.mock("@actions/core"); const { printCheckoutInformation } = require("../src/lib/summary"); jest.mock("../src/lib/summary"); +const { getTreeForProject } = require("@kie/build-chain-configuration-reader"); +jest.mock("@kie/build-chain-configuration-reader"); + afterEach(() => { jest.clearAllMocks(); }); -test("start no parent dependencies", async () => { +test("start no parent dependencies. project triggering the job", async () => { // Arrange + const project = "kiegroup/lienzo-core"; + const checkoutInfo = { + project, + group: "groupx", + branch: "branchx", + targetGroup: "targetGroupx", + targetBranch: "targetBranchx", + merge: true + }; + const definitionTree = { dependencies: [] }; const context = { config: { github: { jobId: "job-id", flowFile: "main.yaml", group: "defaultGroup", - project: "projectX", + project, sourceBranch: "sBranch", - targetBranch: "tBranch" + targetBranch: "tBranch", + inputs: { + definitionFile: path.join( + ".", + "test", + "resources", + "build-config", + "build-config.yaml" + ) + }, + repository: project }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } + rootFolder: "folder" } }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectX", - config: { - github: { - flowFile: "main.yaml" + + getFinalDefinitionFilePath.mockResolvedValueOnce("finalDefinitionFilePath"); + getTreeForProject.mockResolvedValueOnce(definitionTree); + const buildInfo = { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" } - }, - buildCommands: ["command 1", "command 2"], - buildCommandsUpstream: ["upstream 1", "upstream 2"], - buildCommandsDownstream: ["downstream 1", "downstream 2"], - parentDependencies: [], - archiveArtifacts: { - dependencies: "none" } }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([]); - getDir - .mockReturnValueOnce("folder/projectX") - .mockReturnValueOnce("folder/projectX"); + checkoutDefinitionTree.mockResolvedValueOnce([ + { + project, + checkoutInfo, + build: buildInfo + } + ]); + getDir.mockReturnValueOnce("kiegroup/lienzo_core"); // Act await start(context); // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectX", - { - group: "defaultGroup" - }, - context.config.github.targetBranch + expect(getTreeForProject).toHaveBeenCalledWith( + "finalDefinitionFilePath", + project ); - expect(readWorkflowInformation).toHaveBeenCalledWith( - "projectX", - "job-id", - ".github/workflows/main.yaml", - "defaultGroup", - { key1: "value1", key2: "value2" }, - "folder/projectX" - ); - expect(readWorkflowInformation).toHaveBeenCalledTimes(1); + expect(checkoutDefinitionTree).toHaveBeenCalledWith(context, definitionTree); + expect(printCheckoutInformation).toHaveBeenCalledTimes(1); + expect(printCheckoutInformation).toHaveBeenCalledWith({ + "kiegroup/lienzo-core": checkoutInfo + }); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation + expect(getDir).toHaveBeenCalledTimes(1); + expect(execute).toHaveBeenCalledTimes(3); + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "current command" ); - - expect(getDir).toHaveBeenCalledTimes(2); expect(execute).toHaveBeenCalledWith( - "folder/projectX", - "command 1", - "projectX" + "kiegroup/lienzo_core", + "before current command" ); expect(execute).toHaveBeenCalledWith( - "folder/projectX", - "command 2", - "projectX" + "kiegroup/lienzo_core", + "after current command" ); - expect(execute).toHaveBeenCalledTimes(2); expect(runUploadArtifactsMock).toHaveBeenCalledTimes(0); - expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); }); -test("start no parent dependencies archive artifacts", async () => { +test("start no parent dependencies. 2 projects", async () => { // Arrange + const project = "kiegroup/droolsjbpm-build-bootstrap"; + const checkoutInfo = { + project, + group: "groupx", + branch: "branchx", + targetGroup: "targetGroupx", + targetBranch: "targetBranchx", + merge: true + }; + const definitionTree = { dependencies: [] }; const context = { config: { github: { jobId: "job-id", flowFile: "main.yaml", group: "defaultGroup", - project: "projectX", + project: project, sourceBranch: "sBranch", - targetBranch: "tBranch" + targetBranch: "tBranch", + inputs: { + definitionFile: path.join( + ".", + "test", + "resources", + "build-config", + "build-config.yaml" + ) + }, + repository: project }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } + rootFolder: "folder" } }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectX", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command 1"], - buildCommandsUpstream: ["upstream 1"], - buildCommandsDownstream: ["downstream 1"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifact1", - dependencies: "none" - } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([]); - getDir - .mockReturnValueOnce("folder/projectX") - .mockReturnValueOnce("folder/projectX"); - runUploadArtifactsMock - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName1" - }) - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName2" - }); - - // Act - await start(context); - // Assert - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(1); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - name: "artifact1", - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - dependencies: "none" - }, - ["success", "always"] - ); - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectX", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ); - expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); -}); -test("start with parent dependencies without upstream command", async () => { - // Arrange - const context = { - config: { - github: { - jobId: "job-id", - flowFile: "main.yaml", - group: "defaultGroup", - project: "projectXChild", - sourceBranch: "sBranch", - targetBranch: "tBranch" + getFinalDefinitionFilePath.mockResolvedValueOnce("finalDefinitionFilePath"); + getTreeForProject.mockResolvedValueOnce(definitionTree); + const buildInfo = { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" + after: { + current: "after current command", + upstream: "after upstream command" } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - dependencies: "none" } }; - - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" - } + checkoutDefinitionTree.mockResolvedValueOnce([ + { + project: "kiegroup/lienzo-core", + checkoutInfo, + build: buildInfo }, - buildCommands: ["command-parent"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { - dependencies: "none" + { + project, + checkoutInfo, + build: buildInfo } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent ]); getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); + .mockReturnValueOnce("kiegroup/lienzo_core") + .mockReturnValueOnce("kiegroup/droolsjbpm_build_bootstrap"); // Act await start(context); // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(readWorkflowInformation).toHaveBeenCalledWith( - "projectXChild", - "job-id", - ".github/workflows/main.yaml", - "defaultGroup", - { key1: "value1", key2: "value2" }, - "folder/projectXChild" + expect(getTreeForProject).toHaveBeenCalledWith( + "finalDefinitionFilePath", + project ); - expect(readWorkflowInformation).toHaveBeenCalledTimes(1); + expect(checkoutDefinitionTree).toHaveBeenCalledWith(context, definitionTree); + expect(printCheckoutInformation).toHaveBeenCalledTimes(1); + expect(printCheckoutInformation).toHaveBeenCalledWith({ + "kiegroup/lienzo-core": checkoutInfo, + "kiegroup/droolsjbpm-build-bootstrap": checkoutInfo + }); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ); + expect(getDir).toHaveBeenCalledTimes(2); - expect(getDir).toHaveBeenCalledTimes(3); + expect(execute).toHaveBeenCalledTimes(6); expect(execute).toHaveBeenCalledWith( - "folder/projectXParent", - "command-parent", - "projectXParent" + "kiegroup/lienzo_core", + "upstream command" ); expect(execute).toHaveBeenCalledWith( - "folder/projectXChild", - "command-child", - "projectXChild" + "kiegroup/lienzo_core", + "before upstream command" ); - expect(execute).toHaveBeenCalledTimes(2); - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(0); - expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); -}); - -test("start with parent dependencies with upstream command", async () => { - // Arrange - const context = { - config: { - github: { - jobId: "job-id", - flowFile: "main.yaml", - group: "defaultGroup", - project: "projectXChild", - sourceBranch: "sBranch", - targetBranch: "tBranch" - }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - dependencies: "none" - } - }; - - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-parent"], - buildCommandsUpstream: ["command-parent-upstream"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { - dependencies: "none" - } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent - ]); - getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); - - // Act - await start(context); - // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "after upstream command" ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation + expect(execute).toHaveBeenCalledWith( + "kiegroup/droolsjbpm_build_bootstrap", + "current command" ); - expect(execute).toHaveBeenCalledWith( - "folder/projectXParent", - "command-parent-upstream", - "projectXParent" + "kiegroup/droolsjbpm_build_bootstrap", + "before current command" ); - expect(execute).not.toHaveBeenCalledWith( - "folder/projectXParent", - "command-parent", - "projectXParent" + expect(execute).toHaveBeenCalledWith( + "kiegroup/droolsjbpm_build_bootstrap", + "after current command" ); - expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); + + expect(runUploadArtifactsMock).toHaveBeenCalledTimes(0); }); -test("start with parent dependencies with archive artifacts with path", async () => { +test("start no parent dependencies archive artifacts", async () => { // Arrange + const project = "kiegroup/lienzo-core"; + const checkoutInfo = { + project, + group: "groupx", + branch: "branchx", + targetGroup: "targetGroupx", + targetBranch: "targetBranchx", + merge: true + }; + const definitionTree = { dependencies: [] }; const context = { config: { github: { jobId: "job-id", flowFile: "main.yaml", group: "defaultGroup", - project: "projectXChild", + project, sourceBranch: "sBranch", - targetBranch: "tBranch" + targetBranch: "tBranch", + inputs: { + definitionFile: path.join( + ".", + "test", + "resources", + "build-config", + "build-config.yaml" + ) + }, + repository: project }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: ["projectXParent"] + rootFolder: "folder" } }; - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" + getFinalDefinitionFilePath.mockResolvedValueOnce("finalDefinitionFilePath"); + getTreeForProject.mockResolvedValueOnce(definitionTree); + const buildInfo = { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" } }, - buildCommands: ["command-parent"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { + "archive-artifacts": { paths: [ { path: "whateverpath", on: "success" } ], - name: "artifactParent", + name: "artifact1", dependencies: "none" } }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent - ]); - getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); - runUploadArtifactsMock - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName1" - }) - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName2" - }); + const node = { + project, + checkoutInfo, + build: buildInfo + }; + checkoutDefinitionTree.mockResolvedValueOnce([node]); + getDir.mockReturnValueOnce("kiegroup/lienzo_core"); // Act await start(context); // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation + expect(getTreeForProject).toHaveBeenCalledWith( + "finalDefinitionFilePath", + project ); + expect(checkoutDefinitionTree).toHaveBeenCalledWith(context, definitionTree); + expect(printCheckoutInformation).toHaveBeenCalledTimes(1); + expect(printCheckoutInformation).toHaveBeenCalledWith({ + "kiegroup/lienzo-core": checkoutInfo + }); - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(2); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: ["projectXParent"] - }, - ["success", "always"] + expect(getDir).toHaveBeenCalledTimes(1); + expect(execute).toHaveBeenCalledTimes(3); + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "current command" ); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - }, + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "before current command" + ); + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "after current command" + ); + + expect(archiveArtifacts).toHaveBeenCalledTimes(1); + expect(archiveArtifacts).toHaveBeenCalledWith( + node, + [node], ["success", "always"] ); }); -test("start with parent dependencies with archive artifacts with path exception", async () => { +test("start no parent dependencies archive artifacts. Execute Exception", async () => { // Arrange + const project = "kiegroup/lienzo-core"; + const checkoutInfo = { + project, + group: "groupx", + branch: "branchx", + targetGroup: "targetGroupx", + targetBranch: "targetBranchx", + merge: true + }; + const definitionTree = { dependencies: [] }; const context = { config: { github: { jobId: "job-id", flowFile: "main.yaml", group: "defaultGroup", - project: "exceptionProject", + project, sourceBranch: "sBranch", - targetBranch: "tBranch" + targetBranch: "tBranch", + inputs: { + definitionFile: path.join( + ".", + "test", + "resources", + "build-config", + "build-config.yaml" + ) + }, + repository: project }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } + rootFolder: "folder" } }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "exceptionProject", - config: { - github: { - flowFile: "main.yaml" + + getFinalDefinitionFilePath.mockResolvedValueOnce("finalDefinitionFilePath"); + getTreeForProject.mockResolvedValueOnce(definitionTree); + const buildInfo = { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" } }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { + "archive-artifacts": { paths: [ { path: "whateverpath", on: "success" } ], - name: "artifactChild", - dependencies: "all" + name: "artifact1", + dependencies: "none" } }; - - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - getDir.mockReturnValueOnce("folder/exceptionProject"); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([]); + const node = { + project, + checkoutInfo, + build: buildInfo + }; + checkoutDefinitionTree.mockResolvedValueOnce([node]); + getDir.mockReturnValueOnce("kiegroup/lienzo_core"); execute.mockImplementationOnce(async () => { throw new Error("error executing command"); }); + // Act try { await start(context); } catch (ex) { expect(ex.message).toBe( - "Command executions have failed, please review latest execution" + "Command executions have failed, please review latest execution Error: error executing command" ); } // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "exceptionProject", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ); - - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(1); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: "all" - }, - ["failure", "always"] - ); -}); - -test("start with parent dependencies with archive artifacts with path dependencies all", async () => { - // Arrange - const context = { - config: { - github: { - jobId: "job-id", - flowFile: "main.yaml", - group: "defaultGroup", - project: "projectXChild", - sourceBranch: "sBranch", - targetBranch: "tBranch" - }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: "all" - } - }; - - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-parent"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent - ]); - getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); - runUploadArtifactsMock - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName1" - }) - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName2" - }); - - // Act - await start(context); - // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ); - - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(2); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: "all" - }, - ["success", "always"] - ); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - }, - ["success", "always"] - ); -}); - -test("start with parent dependencies with archive artifacts with path dependencies not matching", async () => { - // Arrange - const context = { - config: { - github: { - jobId: "job-id", - flowFile: "main.yaml", - group: "defaultGroup", - project: "projectXChild", - sourceBranch: "sBranch", - targetBranch: "tBranch" - }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: ["projectXParentX"] - } - }; - - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-parent"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent - ]); - getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); - runUploadArtifactsMock - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName1" - }) - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName2" - }); - - // Act - await start(context); - // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation - ); - - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(1); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactChild", - dependencies: ["projectXParentX"] - }, - ["success", "always"] + expect(getTreeForProject).toHaveBeenCalledWith( + "finalDefinitionFilePath", + project ); + expect(checkoutDefinitionTree).toHaveBeenCalledWith(context, definitionTree); expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); -}); - -test("start with parent dependencies with archive artifacts one of them without path", async () => { - // Arrange - const context = { - config: { - github: { - jobId: "job-id", - flowFile: "main.yaml", - group: "defaultGroup", - project: "projectXChild", - sourceBranch: "sBranch", - targetBranch: "tBranch" - }, - rootFolder: "folder", - matrixVariables: { key1: "value1", key2: "value2" } - } - }; - const workflowInformation = { - id: "build-chain", - name: "Build Chain", - project: "projectXChild", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-child"], - buildCommandsUpstream: ["command-child-upstream"], - buildCommandsDownstream: ["command-child-downstream"], - archiveArtifacts: { - name: "artifactChild", - dependencies: ["projectXParent"] - } - }; - - const workflowInformationParent = { - id: "build-chain", - name: "Build Chain", - project: "projectXParent", - config: { - github: { - flowFile: "main.yaml" - } - }, - buildCommands: ["command-parent"], - buildCommandsDownstream: ["command-parent-dowstream"], - archiveArtifacts: { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - } - }; - readWorkflowInformation.mockReturnValueOnce(workflowInformation); - checkoutParentsAndGetWorkflowInformation.mockResolvedValueOnce([ - workflowInformationParent - ]); - getDir - .mockReturnValueOnce("folder/projectXChild") - .mockReturnValueOnce("folder/projectXParent") - .mockReturnValueOnce("folder/projectXChild"); - runUploadArtifactsMock - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName1" - }) - .mockResolvedValueOnce({ - failedItems: [], - artifactName: "artifactName2" - }); + expect(printCheckoutInformation).toHaveBeenCalledWith({ + "kiegroup/lienzo-core": checkoutInfo + }); - // Act - await start(context); - // Assert - expect(checkoutProject).toHaveBeenCalledTimes(1); - expect(checkoutProject).toHaveBeenCalledWith( - context, - "projectXChild", - { - group: "defaultGroup" - }, - context.config.github.targetBranch - ); - expect(checkoutParentsAndGetWorkflowInformation).toHaveBeenCalledWith( - context, - [context.config.github.project], - context.config.github.project, - context.config.github.targetBranch, - workflowInformation + expect(getDir).toHaveBeenCalledTimes(1); + expect(execute).toHaveBeenCalledTimes(1); + expect(execute).toHaveBeenCalledWith( + "kiegroup/lienzo_core", + "before current command" ); - expect(runUploadArtifactsMock).toHaveBeenCalledTimes(1); - expect(runUploadArtifactsMock).toHaveBeenCalledWith( - { - paths: [ - { - path: "whateverpath", - on: "success" - } - ], - name: "artifactParent", - dependencies: "none" - }, - ["success", "always"] + expect(archiveArtifacts).toHaveBeenCalledTimes(1); + expect(archiveArtifacts).toHaveBeenCalledWith( + node, + [node], + ["failure", "always"] ); - expect(printCheckoutInformation).toHaveBeenCalledTimes(1); - expect(printCheckoutInformation).toHaveBeenCalledWith({}); }); diff --git a/test/config.test.js b/test/config.test.js index 27263eb0..2dc49341 100644 --- a/test/config.test.js +++ b/test/config.test.js @@ -1,19 +1,7 @@ const { createConfig } = require("../src/lib/config"); -jest.mock("../src/lib/action-utils", () => ({ - getWorkflowfileName: () => { - return "pull_request.yml"; - }, - getArchiveArtifactsName: () => { - return "artifact x"; - }, - getArchiveArtifactsPath: () => { - return "path1,path2"; - }, - getArchiveArtifactsIfNoFilesFound: () => { - return "warn"; - }, - getMatrixVariables: () => { - return { key1: "value1", key2: "value2" }; +jest.mock("../src/lib/util/action-utils", () => ({ + getDefinitionFile: () => { + return "definition-file.yaml"; } })); @@ -61,8 +49,11 @@ test("createConfig", async () => { ref: undefined, sourceRepository: "group/projectx", repository: "kiegroup/github-action-build-chain", - flowFile: "pull_request.yml", - workflowName: "build chain name" + groupProject: "kiegroup/github-action-build-chain", + workflowName: "build chain name", + inputs: { + definitionFile: "definition-file.yaml" + } }, rootFolder: "folder" }; diff --git a/test/fs-helper.test.js b/test/fs-helper.test.js index b41e4524..51cb2ffc 100644 --- a/test/fs-helper.test.js +++ b/test/fs-helper.test.js @@ -40,8 +40,7 @@ lienzo-tests `, "parent-dependencies": `lienzo-core groupx/errai -`, - "workflow-file-name": "flow.yaml" +` } } ] diff --git a/test/lib/artifacts/build-chain-flow-archive-artifact-helper.test.js b/test/lib/artifacts/build-chain-flow-archive-artifact-helper.test.js new file mode 100644 index 00000000..4e687cbe --- /dev/null +++ b/test/lib/artifacts/build-chain-flow-archive-artifact-helper.test.js @@ -0,0 +1,434 @@ +const { + archiveArtifacts +} = require("../../../src/lib/artifacts/build-chain-flow-archive-artifact-helper"); +const { + run: uploadArtifacts +} = require("../../../src/lib/artifacts/upload-artifacts"); +jest.mock("../../../src/lib/artifacts/upload-artifacts"); + +afterEach(() => { + jest.clearAllMocks(); +}); + +test("start no parent dependencies archive artifacts", async () => { + // Arrange + const node = { + project: "kiegroup/lienzo-core", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpath", + on: "success" + } + ], + name: "artifact1", + dependencies: "none" + } + } + }; + // Act + await archiveArtifacts(node, [node], ["success", "always"]); + // Assert + expect(uploadArtifacts).toHaveBeenCalledTimes(1); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [{ path: "whateverpath", on: "success" }], + name: "artifact1", + dependencies: "none" + }, + ["success", "always"] + ); +}); + +test("start with parent dependencies with archive artifacts with path", async () => { + // Arrange + const droolsNode = { + project: "kiegroup/drools", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: ["kiegroup/lienzo-core"] + } + } + }; + const lienzoCoreNode = { + project: "kiegroup/lienzo-core", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + } + } + }; + + uploadArtifacts + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName1" + }) + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName2" + }); + + // Act + await archiveArtifacts( + droolsNode, + [lienzoCoreNode, droolsNode], + ["success", "always"] + ); + // Assert + expect(uploadArtifacts).toHaveBeenCalledTimes(2); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: ["kiegroup/lienzo-core"] + }, + ["success", "always"] + ); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + }, + ["success", "always"] + ); +}); + +test("start archive artifacts. Dependencies all", async () => { + // Arrange + const droolsNode = { + project: "kiegroup/drools", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: "all" + } + } + }; + const lienzoCoreNode = { + project: "kiegroup/lienzo-core", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + } + } + }; + + uploadArtifacts + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName1" + }) + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName2" + }); + + // Act + await archiveArtifacts( + droolsNode, + [lienzoCoreNode, droolsNode], + ["success", "always"] + ); + // Assert + expect(uploadArtifacts).toHaveBeenCalledTimes(2); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: "all" + }, + ["success", "always"] + ); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + }, + ["success", "always"] + ); +}); + +test("start with parent dependencies not matching any project", async () => { + // Arrange + const droolsNode = { + project: "kiegroup/drools", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: ["notknownproject"] + } + } + }; + const lienzoCoreNode = { + project: "kiegroup/lienzo-core", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + } + } + }; + + uploadArtifacts + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName1" + }) + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName2" + }); + + // Act + await archiveArtifacts( + droolsNode, + [lienzoCoreNode, droolsNode], + ["success", "always"] + ); + // Assert + expect(uploadArtifacts).toHaveBeenCalledTimes(1); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathdrools", + on: "success" + } + ], + name: "artifactDrools", + dependencies: ["notknownproject"] + }, + ["success", "always"] + ); +}); + +test("start archive artifacts. One of the projects without paths", async () => { + // Arrange + const droolsNode = { + project: "kiegroup/drools", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + name: "artifactDrools", + dependencies: "all" + } + } + }; + const lienzoCoreNode = { + project: "kiegroup/lienzo-core", + build: { + "build-command": { + current: "current command", + upstream: "upstream command", + before: { + current: "before current command", + upstream: "before upstream command" + }, + after: { + current: "after current command", + upstream: "after upstream command" + } + }, + "archive-artifacts": { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + } + } + }; + + uploadArtifacts + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName1" + }) + .mockResolvedValueOnce({ + failedItems: [], + artifactName: "artifactName2" + }); + + // Act + await archiveArtifacts( + droolsNode, + [lienzoCoreNode, droolsNode], + ["success", "always"] + ); + // Assert + expect(uploadArtifacts).toHaveBeenCalledTimes(1); + expect(uploadArtifacts).toHaveBeenCalledWith( + { + paths: [ + { + path: "whateverpathlienzo", + on: "success" + } + ], + name: "artifactLienzo", + dependencies: "none" + }, + ["success", "always"] + ); +}); diff --git a/test/lib/command-treatment-delegator.test.js b/test/lib/command/command-treatment-delegator.test.js similarity index 89% rename from test/lib/command-treatment-delegator.test.js rename to test/lib/command/command-treatment-delegator.test.js index 39cf12fd..473fc799 100644 --- a/test/lib/command-treatment-delegator.test.js +++ b/test/lib/command/command-treatment-delegator.test.js @@ -1,13 +1,13 @@ const { treatCommand -} = require("../../src/lib/command/command-treatment-delegator"); -jest.mock("../../src/lib/command/maven-treatment", () => ({ +} = require("../../../src/lib/command/command-treatment-delegator"); +jest.mock("../../../src/lib/command/maven-treatment", () => ({ treat: () => { return "maven command"; } })); -jest.mock("../../src/lib/command/no-treatment", () => ({ +jest.mock("../../../src/lib/command/no-treatment", () => ({ treat: () => { return "same command"; } diff --git a/test/lib/maven-treatment.test.js b/test/lib/command/maven-treatment.test.js similarity index 77% rename from test/lib/maven-treatment.test.js rename to test/lib/command/maven-treatment.test.js index 91eb6994..94beda59 100644 --- a/test/lib/maven-treatment.test.js +++ b/test/lib/command/maven-treatment.test.js @@ -1,4 +1,4 @@ -const { treat } = require("../../src/lib/command/maven-treatment"); +const { treat } = require("../../../src/lib/command/maven-treatment"); test("treat", () => { // Act diff --git a/test/lib/no-treatment.test.js b/test/lib/command/no-treatment.test.js similarity index 67% rename from test/lib/no-treatment.test.js rename to test/lib/command/no-treatment.test.js index f602b3ec..a90b2e20 100644 --- a/test/lib/no-treatment.test.js +++ b/test/lib/command/no-treatment.test.js @@ -1,4 +1,4 @@ -const { treat } = require("../../src/lib/command/no-treatment"); +const { treat } = require("../../../src/lib/command/no-treatment"); test("treat", () => { // Act diff --git a/test/action-utils.test.js b/test/lib/util/action-utils.test.js similarity index 50% rename from test/action-utils.test.js rename to test/lib/util/action-utils.test.js index 85755e57..76e5bc03 100644 --- a/test/action-utils.test.js +++ b/test/lib/util/action-utils.test.js @@ -1,4 +1,4 @@ -const { getWorkflowfileName } = require("../src/lib/action-utils"); +const { getDefinitionFile } = require("../../../src/lib/util/action-utils"); const { getInput } = require("@actions/core"); jest.mock("@actions/core"); @@ -7,14 +7,14 @@ afterEach(() => { jest.clearAllMocks(); }); -test("getWorkflowfileName", () => { +test("getDefinitionFile", () => { // Arrange - const expectedResult = "pull_request.yml"; + const expectedResult = "./whateverfile"; getInput.mockImplementationOnce(param => - param === "workflow-file-name" ? expectedResult : undefined + param === "definition-file" ? expectedResult : undefined ); // Act - const result = getWorkflowfileName(); + const result = getDefinitionFile(); // Assert expect(result).toEqual(expectedResult); diff --git a/test/lib/util/http.test.js b/test/lib/util/http.test.js new file mode 100644 index 00000000..85754852 --- /dev/null +++ b/test/lib/util/http.test.js @@ -0,0 +1,23 @@ +const { checkUrlExist } = require("../../../src/lib/util/http"); + +afterEach(() => { + jest.clearAllMocks(); +}); + +test("checkUrlExist HTTPS OK", async () => { + // Act + const result = await checkUrlExist( + "https://raw.githubusercontent.com/kiegroup/github-action-build-chain/master/package.json" + ); + // Assert + expect(result).toBe(true); +}); + +test("checkUrlExist HTTP NOT OK", async () => { + // Act + const result = await checkUrlExist( + "https://raw.githubusercontent.com/kiegroup/github-action-build-chain/random_branch/nonexistingfile" + ); + // Assert + expect(result).toBe(false); +}); diff --git a/test/lib/workflow-information/reader.test.js b/test/lib/workflow-information/reader.test.js deleted file mode 100644 index 54da4596..00000000 --- a/test/lib/workflow-information/reader.test.js +++ /dev/null @@ -1,1234 +0,0 @@ -const { - readWorkflowInformation, - checkoutParentsAndGetWorkflowInformation, - dependenciesToObject -} = require("../../../src/lib/workflow-information/reader"); -jest.mock("../../../src/lib/git"); -jest.mock("@actions/core"); -const { - getDir, - checkoutDependencies -} = require("../../../src/lib/build-chain-flow-helper"); -jest.mock("../../../src/lib/build-chain-flow-helper"); - -afterEach(() => { - jest.clearAllMocks(); -}); - -test("checkoutParentsAndGetWorkflowInformation no parents", async () => { - // Arrange - const project = "parent"; - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile - } - ); - - // Assert - - expect(getDir).toHaveBeenCalledTimes(0); - expect(workflowInformationArray).toStrictEqual([]); -}); - -test("checkoutParentsAndGetWorkflowInformation 1 level", async () => { - // Arrange - getDir.mockReturnValueOnce("./test/resources/hierarchyflows/parent-parent"); - const project = "parent"; - - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - - checkoutDependencies.mockResolvedValueOnce({ - "parent-parent": { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { "parent-parent": { group: "groupX" } } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(1); - expect(workflowInformationArray[0].project).toBe("parent-parent"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "parent-parent"' - ]); -}); - -test("checkoutParentsAndGetWorkflowInformation 2 levels", async () => { - // Arrange - getDir - .mockReturnValueOnce("./test/resources/hierarchyflows/parent") - .mockReturnValueOnce("./test/resources/hierarchyflows/parent-parent"); - const project = "child"; - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - checkoutDependencies - .mockResolvedValueOnce({ - parent: { targetBranch: context.config.github.targetBranch } - }) - .mockResolvedValueOnce({ - "parent-parent": { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { parent: { group: "groupX" } } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(2); - expect(workflowInformationArray[0].project).toBe("parent"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "parent"' - ]); - expect(workflowInformationArray[1].project).toBe("parent-parent"); - expect(workflowInformationArray[1].buildCommands).toStrictEqual([ - 'echo "parent-parent"' - ]); -}); - -test("checkoutParentsAndGetWorkflowInformation 3 levels", async () => { - // Arrange - getDir - .mockReturnValueOnce("./test/resources/hierarchyflows/child") - .mockReturnValueOnce("./test/resources/hierarchyflows/parent") - .mockReturnValueOnce("./test/resources/hierarchyflows/parent-parent"); - - const project = "child-child"; - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - checkoutDependencies - .mockResolvedValueOnce({ - child: { targetBranch: context.config.github.targetBranch } - }) - .mockResolvedValueOnce({ - parent: { targetBranch: context.config.github.targetBranch } - }) - .mockResolvedValueOnce({ - "parent-parent": { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { child: { group: "groupX" } } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(3); - expect(workflowInformationArray[0].project).toBe("child"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "child"' - ]); - expect(workflowInformationArray[1].project).toBe("parent"); - expect(workflowInformationArray[1].buildCommands).toStrictEqual([ - 'echo "parent"' - ]); - expect(workflowInformationArray[2].project).toBe("parent-parent"); - expect(workflowInformationArray[2].buildCommands).toStrictEqual([ - 'echo "parent-parent"' - ]); -}); - -test("checkoutParentsAndGetWorkflowInformation 3 levels repeated project", async () => { - // Arrange - getDir - .mockReturnValueOnce("./test/resources/hierarchyflows/child") - .mockReturnValueOnce("./test/resources/hierarchyflows/parent"); - - const project = "child-child"; - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = ["parent-parent"]; - checkoutDependencies - .mockResolvedValueOnce({ - child: { targetBranch: context.config.github.targetBranch } - }) - .mockResolvedValueOnce({ - parent: { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { child: { group: "groupX" } } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(2); - expect(workflowInformationArray[0].project).toBe("child"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "child"' - ]); - expect(workflowInformationArray[1].project).toBe("parent"); - expect(workflowInformationArray[1].buildCommands).toStrictEqual([ - 'echo "parent"' - ]); -}); - -test("checkoutParentsAndGetWorkflowInformation flowFile and jobId", async () => { - // Arrange - getDir.mockReturnValueOnce("./test/resources/hierarchyflows/parent-parent"); - const project = "parent"; - - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - - checkoutDependencies.mockResolvedValueOnce({ - "parent-parent": { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { "parent-parent": { group: "groupX" } } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(1); - expect(workflowInformationArray[0].project).toBe("parent-parent"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "parent-parent"' - ]); -}); - -test("checkoutParentsAndGetWorkflowInformation 2 levels flowFile and jobId", async () => { - // Arrange - getDir - .mockReturnValueOnce("./test/resources/hierarchyflows-flowFileJobId/parent") - .mockReturnValueOnce( - "./test/resources/hierarchyflows-flowFileJobId/parent-parent" - ); - const project = "child"; - const context = { - config: { - github: { - jobId: "build-chain", - flowFile: "flow.yaml", - group: "groupX", - project: project, - targetBranch: "tBranch" - } - } - }; - - const projectList = []; - checkoutDependencies - .mockResolvedValueOnce({ - parent: { targetBranch: context.config.github.targetBranch } - }) - .mockResolvedValueOnce({ - "parent-parent": { targetBranch: context.config.github.targetBranch } - }); - // Act - const workflowInformationArray = await checkoutParentsAndGetWorkflowInformation( - context, - projectList, - project, - context.config.github.targetBranch, - { - jobId: context.config.github.jobId, - flowFile: context.config.github.flowFile, - parentDependencies: { - parent: { group: "groupX", flowFile: "flowx.yaml" } - } - } - ); - - // Assert - expect(workflowInformationArray.length).toBe(2); - expect(workflowInformationArray[0].project).toBe("parent"); - expect(workflowInformationArray[0].buildCommands).toStrictEqual([ - 'echo "parent"' - ]); - expect(workflowInformationArray[1].project).toBe("parent-parent"); - expect(workflowInformationArray[1].buildCommands).toStrictEqual([ - 'echo "parent-parent"' - ]); -}); - -test("parseWorkflowInformation without matrix definition", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation with matrix", () => { - // Arrange - const context = { - config: { - matrixVariables: { - os: "rhel", - "matrix.version": "7", - sourceBranch: "source", - "matrix.targetBranch": "target" - } - } - }; - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-matrix.yaml", - "defaultGroup", - context.config.matrixVariables, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-matrix.yaml", - buildCommands: ["echo rhel", "echo 'without matrix'"], - buildCommandsUpstream: ["echo rhel", "echo 7", "echo 'without matrix'"], - buildCommandsDownstream: ["echo 'without matrix'", "echo rhel"], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "source", target: "target" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" }, - projectx: { - group: "groupy", - mapping: { source: "source", target: "master" } - } - }, - archiveArtifacts: { - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation with matrix error definition", () => { - // Act - try { - readWorkflowInformation( - "projectx", - "build-chain", - "flow-matrix.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - } catch (e) { - expect(e.message).toBe( - "The variable 'sourceBranch' is not defined in \"with\" 'matrix-variables' so it can't be replaced. Please define it in the flow triggering the job." - ); - } -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifacts.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifacts.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "namex", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts no name and ifNoFilesFound", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsnoname.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsnoname.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "projectx", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts multiline", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-multiline.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-multiline.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "namex", - paths: [ - { - path: "path/output/bin/", - on: "success" - }, - { - path: "path/output/test-results", - on: "success" - }, - { - path: "!path/**/*.tmp", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts singleline on event", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-singleline-archive-on.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-singleline-archive-on.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "namex", - paths: [ - { - path: "path/output/bin/", - on: "failure" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts multiline different on events", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-multiline-archive-on.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-multiline-archive-on.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "namex", - paths: [ - { - path: "path/output/bin/", - on: "success" - }, - { - path: "path/output/test-results", - on: "failure" - }, - { - path: "!path/**/*.tmp", - on: "always" - }, - { - path: "!path/**/*.tmp2", - on: "success" - }, - { - path: "!path/**/*.tmp3", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts dependencies none", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsdependenciesnone.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsdependenciesnone.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "projectx", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "none" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts dependencies all", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsdependenciesall.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsdependenciesall.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "projectx", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: "all" - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts dependencies multiline", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsdependenciesmultiline.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsdependenciesmultiline.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "projectx", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: ["projectA", "none", "all", "projectB"] - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts dependencies singleline", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsdependenciessingleline.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsdependenciessingleline.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - name: "projectx", - paths: [ - { - path: "pathsx", - on: "success" - } - ], - ifNoFilesFound: "warn", - dependencies: ["projectA"] - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("parseWorkflowInformation without matrix definition and with archive-artifacts dependencies no path", () => { - // Act - const buildChainInformation = readWorkflowInformation( - "projectx", - "build-chain", - "flow-archiveartifactsdependenciesnopath.yaml", - "defaultGroup", - undefined, - "test/resources" - ); - // Assert - const expected = { - id: "build-chain", - project: "projectx", - name: "Build Chain", - jobId: "build-chain", - flowFile: "flow-archiveartifactsdependenciesnopath.yaml", - buildCommands: [ - "mvn clean", - 'mvn -e -nsu -Dfull clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -DjvmArgs="-Xms1g -Xmx4g -XX:+CMSClassUnloadingEnabled"' - ], - buildCommandsUpstream: [ - "mvn clean", - "mvn -e -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true" - ], - buildCommandsDownstream: [ - "mvn clean", - "mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g" - ], - childDependencies: { - appformer: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - "lienzo-tests": { group: "defaultGroup" } - }, - parentDependencies: { - "lienzo-core": { group: "defaultGroup" }, - errai: { group: "groupx" } - }, - archiveArtifacts: { - dependencies: ["projectA"] - } - }; - expect(buildChainInformation).toEqual(expected); -}); - -test("dependenciesToObject without branch", () => { - // Arrange - const expected = { - projectA: { group: "defaultGroup" }, - projectB: { group: "defaultGroup" }, - projectC: { group: "defaultGroup" }, - projectD: { group: "defaultGroup" } - }; - // Act - const dependencies = dependenciesToObject( - `projectA -projectB - projectC -projectD`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject without branch and with group", () => { - // Arrange - const expected = { - projectA: { group: "groupx" }, - projectB: { group: "groupy" }, - projectC: { group: "groupz" }, - projectD: { group: "defaultGroup" } - }; - // Act - const dependencies = dependenciesToObject( - `groupx/projectA -groupy/projectB - groupz/projectC -projectD`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single dependency without group", () => { - // Arrange - const expected = { projectA: { group: "defaultGroup" } }; - // Act - const dependencies = dependenciesToObject("projectA", "defaultGroup"); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single dependency with group", () => { - // Arrange - const expected = { projectA: { group: "groupx" } }; - // Act - const dependencies = dependenciesToObject("groupx/projectA", "defaultGroup"); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject with branch", () => { - // Arrange - const expected = { - projectA: { group: "defaultGroup" }, - projectB: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - }, - projectC: { group: "defaultGroup" }, - projectD: { - group: "defaultGroup", - mapping: { source: "8.0.0", target: "9.1.1" } - } - }; - // Act - const dependencies = dependenciesToObject( - `projectA -projectB@7.x:master - projectC -projectD@8.0.0:9.1.1`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single", () => { - // Arrange - const expected = { - projectA: { - group: "defaultGroup" - } - }; - // Act - const dependencies = dependenciesToObject(`projectA`, "defaultGroup"); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with group", () => { - // Arrange - const expected = { - projectA: { - group: "groupx" - } - }; - // Act - const dependencies = dependenciesToObject(`groupx/projectA`, "defaultGroup"); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with mapping", () => { - // Arrange - const expected = { - projectA: { - group: "defaultGroup", - mapping: { source: "7.x", target: "master" } - } - }; - // Act - const dependencies = dependenciesToObject( - `projectA@7.x:master`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with group and mapping", () => { - // Arrange - const expected = { - projectA: { - group: "groupx", - mapping: { source: "7.x", target: "master" } - } - }; - // Act - const dependencies = dependenciesToObject( - `groupx/projectA@7.x:master`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with flow file", () => { - // Arrange - const expected = { - projectA: { - group: "defaultGroup", - flowFile: "file37-x.yml" - } - }; - // Act - const dependencies = dependenciesToObject( - `projectA|file37-x.yml`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with group, mapping and flow file", () => { - // Arrange - const expected = { - projectA: { - group: "groupx", - mapping: { source: "7.x", target: "master" }, - flowFile: "file37-x.yml" - } - }; - // Act - const dependencies = dependenciesToObject( - `groupx/projectA@7.x:master|file37-x.yml`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); - -test("dependenciesToObject single with job id", () => { - // Arrange - const expected = { - projectA: { - group: "defaultGroup", - jobId: "job39-x-8whatever" - } - }; - // Act - const dependencies = dependenciesToObject( - `projectA|:job39-x-8whatever`, - "defaultGroup" - ); - // Assert - expect(dependencies).toEqual(expected); -}); diff --git a/test/resources/build-config/build-config.yaml b/test/resources/build-config/build-config.yaml new file mode 100644 index 00000000..e8397549 --- /dev/null +++ b/test/resources/build-config/build-config.yaml @@ -0,0 +1,75 @@ +version: "1.0" + +dependencies: ./project-dependencies.yaml + +default: + build-command: + current: mvn -e -nsu -Dfull -Pwildfly clean install -Prun-code-coverage -Dcontainer.profile=wildfly -Dcontainer=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true + upstream: mvn -e --builder smart -T1C clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true + after: + upstream: rm -rf ./* + +build: + - project: kiegroup/appformer + build-command: + upstream: mvn -e clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true + archive-artifacts: + path: | + **/dashbuilder-runtime.war + + - project: kiegroup/drools + build-command: + upstream: mvn -e clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true + + - project: kiegroup/optaplanner + build-command: + current: mvn -e clean install -nsu -Prun-code-coverage,wildfly -Dfull -Dintegration-tests=true -Dmaven.test.failure.ignore=true + upstream: mvn -e clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true + + - project: kiegroup/droolsjbpm-integration + build-command: + current: mvn -e -nsu -Dfull -Pwildfly clean install -Pjenkins-pr-builder -Prun-code-coverage -Dcontainer.profile=wildfly -Dcontainer=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true + archive-artifacts: + path: | + **/gclog + + - project: kiegroup/kie-wb-common + build-command: + current: mvn -e -nsu -Dfull clean install -Prun-code-coverage -Pwildfly -Dcontainer=wildfly -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -Dwebdriver.firefox.bin=/opt/tools/firefox-60esr/firefox-bin + upstream: -e clean install -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -Denforcer.skip=true -Dcheckstyle.skip=true -Dspotbugs.skip=true -Drevapi.skip=true + archive-artifacts: + path: | + **/target/screenshots/** + + - project: kiegroup/jbpm-wb + archive-artifacts: + path: | + **/target/jbpm-wb-case-mgmt-showcase*.war + **/target/jbpm-wb-showcase.war + + - project: kiegroup/kie-docs + build-command: + current: mvn clean install + + - project: kiegroup/optaweb-employee-rostering + archive-artifacts: + path: | + **/cypress/screenshots/** + **/cypress/videos/** + + - project: kiegroup/optaweb-vehicle-routing + archive-artifacts: + path: | + **/cypress/screenshots/** + **/cypress/videos/** + + - project: kiegroup/kie-wb-distributions + build-command: + current: mvn -e -nsu clean install -Dfull -Prun-code-coverage -Pwildfly -Dcontainer=wildfly -Dcontainer.profile=wildfly -Dintegration-tests=true -Dmaven.test.failure.ignore=true -Pbusiness-central -Dgwt.compiler.localWorkers=1 -Dwebdriver.firefox.bin=/opt/tools/firefox-60esr/firefox-bin + archive-artifacts: + path: | + **/target/screenshots/** + **/target/business-monitoring-webapp.war + **/target/business-central*eap*.war + **/target/business-central*wildfly*.war + **/target/jbpm-server*dist*.zip diff --git a/test/resources/build-config/project-dependencies.yaml b/test/resources/build-config/project-dependencies.yaml new file mode 100644 index 00000000..292c7ad6 --- /dev/null +++ b/test/resources/build-config/project-dependencies.yaml @@ -0,0 +1,147 @@ +version: "1.0" +dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/lienzo-tests + dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/droolsjbpm-build-bootstrap + dependencies: + - project: kiegroup/lienzo-core + + - project: kiegroup/kie-soup + dependencies: + - project: kiegroup/droolsjbpm-build-bootstrap + + - project: kiegroup/appformer + dependencies: + - project: kiegroup/droolsjbpm-build-bootstrap + - project: kiegroup/lienzo-tests + - project: kiegroup/kie-soup + + - project: kiegroup/droolsjbpm-knowledge + dependencies: + - project: kiegroup/kie-soup + + - project: kiegroup/drools + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-soup + + - project: kiegroup/jbpm + dependencies: + - project: kiegroup/drools + - project: kiegroup/kie-soup + + - project: kiegroup/optaplanner + dependencies: + - project: kiegroup/drools + mapping: + source: 7.x + target: master + - project: kiegroup/jbpm + mapping: + source: 7.x + target: master + + - project: kiegroup/kie-jpmml-integration + dependencies: + - project: kiegroup/drools + - project: kiegroup/jbpm + + - project: kiegroup/droolsjbpm-integration + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/kie-jpmml-integration + - project: kiegroup/jbpm + - project: kiegroup/kie-soup + + - project: kiegroup/openshift-drools-hacep + dependencies: + - project: kiegroup/droolsjbpm-integration + + - project: kiegroup/droolsjbpm-tools + dependencies: + - project: kiegroup/jbpm + - project: kiegroup/drools + - project: kiegroup/kie-soup + + - project: kiegroup/kie-uberfire-extensions + dependencies: + - project: kiegroup/appformer + + - project: kiegroup/kie-wb-playground + dependencies: + - project: kiegroup/openshift-drools-hacep + + - project: kiegroup/kie-wb-common + dependencies: + - project: kiegroup/kie-wb-playground + - project: kiegroup/droolsjbpm-integration + + - project: kiegroup/drools-wb + dependencies: + - project: kiegroup/kie-wb-common + + - project: kiegroup/optaplanner-wb + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/drools-wb + - project: kiegroup/drools + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/kie-soup + - project: kiegroup/kie-wb-common + - project: kiegroup/kie-wb-playground + + - project: kiegroup/jbpm-designer + dependencies: + - project: kiegroup/kie-wb-common + + - project: kiegroup/jbpm-work-items + dependencies: + - project: kiegroup/openshift-drools-hacep + - project: kiegroup/kie-wb-playground + + - project: kiegroup/jbpm-wb + dependencies: + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/drools-wb + - project: kiegroup/jbpm-designer + - project: kiegroup/jbpm-work-items + + - project: kiegroup/kie-docs + + - project: kiegroup/optaweb-employee-rostering + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + + - project: kiegroup/optaweb-vehicle-routing + dependencies: + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + + - project: kiegroup/kie-wb-distributions + dependencies: + - project: kiegroup/appformer + - project: kiegroup/kie-soup + - project: kiegroup/drools + - project: kiegroup/optaplanner + mapping: + source: master + target: 7.x + - project: kiegroup/jbpm + - project: kiegroup/kie-uberfire-extensions + - project: kiegroup/jbpm-wb diff --git a/test/resources/flow-archiveartifacts.yaml b/test/resources/flow-archiveartifacts.yaml index 800dc324..3ba3d789 100644 --- a/test/resources/flow-archiveartifacts.yaml +++ b/test/resources/flow-archiveartifacts.yaml @@ -28,6 +28,5 @@ jobs: archive-artifacts-name: "namex" archive-artifacts-path: "pathsx" archive-artifacts-if-no-files-found: "warn" - workflow-file-name: "flow-archiveartifacts.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsdependenciesall.yaml b/test/resources/flow-archiveartifactsdependenciesall.yaml index 04144224..a4e6e6a0 100644 --- a/test/resources/flow-archiveartifactsdependenciesall.yaml +++ b/test/resources/flow-archiveartifactsdependenciesall.yaml @@ -27,6 +27,5 @@ jobs: mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g archive-artifacts-path: "pathsx" archive-artifacts-dependencies: "all" - workflow-file-name: "flow-archiveartifactsdependenciesall.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsdependenciesmultiline.yaml b/test/resources/flow-archiveartifactsdependenciesmultiline.yaml index f7f051c5..405c2102 100644 --- a/test/resources/flow-archiveartifactsdependenciesmultiline.yaml +++ b/test/resources/flow-archiveartifactsdependenciesmultiline.yaml @@ -31,6 +31,5 @@ jobs: none all projectB - workflow-file-name: "flow-archiveartifactsdependenciesmultiline.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsdependenciesnone.yaml b/test/resources/flow-archiveartifactsdependenciesnone.yaml index 501b32a4..65381c7b 100644 --- a/test/resources/flow-archiveartifactsdependenciesnone.yaml +++ b/test/resources/flow-archiveartifactsdependenciesnone.yaml @@ -27,6 +27,5 @@ jobs: mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g archive-artifacts-path: "pathsx" archive-artifacts-dependencies: "none" - workflow-file-name: "flow-archiveartifactsdependenciesnone.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsdependenciesnopath.yaml b/test/resources/flow-archiveartifactsdependenciesnopath.yaml index d1f8ab16..8b818aad 100644 --- a/test/resources/flow-archiveartifactsdependenciesnopath.yaml +++ b/test/resources/flow-archiveartifactsdependenciesnopath.yaml @@ -26,6 +26,5 @@ jobs: mvn clean mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g archive-artifacts-dependencies: "projectA" - workflow-file-name: "flow-archiveartifactsdependenciesnopath.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsdependenciessingleline.yaml b/test/resources/flow-archiveartifactsdependenciessingleline.yaml index 104806da..5cf210c9 100644 --- a/test/resources/flow-archiveartifactsdependenciessingleline.yaml +++ b/test/resources/flow-archiveartifactsdependenciessingleline.yaml @@ -27,6 +27,5 @@ jobs: mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g archive-artifacts-path: "pathsx" archive-artifacts-dependencies: "projectA" - workflow-file-name: "flow-archiveartifactsdependenciessingleline.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-archiveartifactsnoname.yaml b/test/resources/flow-archiveartifactsnoname.yaml index ae95260a..a7a6c262 100644 --- a/test/resources/flow-archiveartifactsnoname.yaml +++ b/test/resources/flow-archiveartifactsnoname.yaml @@ -26,6 +26,5 @@ jobs: mvn clean mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g archive-artifacts-path: "pathsx" - workflow-file-name: "flow-archiveartifactsnoname.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-matrix.yaml b/test/resources/flow-matrix.yaml index d94f5400..f650ff85 100644 --- a/test/resources/flow-matrix.yaml +++ b/test/resources/flow-matrix.yaml @@ -32,6 +32,5 @@ jobs: matrix.version: ${{ matrix.version }} sourceBranch: ${{ matrix.sourceBranch }} matrix.targetBranch: ${{ matrix.sourceBranch }} - workflow-file-name: "flow-matrix.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-multiline-archive-on.yaml b/test/resources/flow-multiline-archive-on.yaml index b4d865ce..98863f02 100644 --- a/test/resources/flow-multiline-archive-on.yaml +++ b/test/resources/flow-multiline-archive-on.yaml @@ -33,6 +33,5 @@ jobs: !path/**/*.tmp2 !path/**/*.tmp3@not_existing archive-artifacts-if-no-files-found: "warn" - workflow-file-name: "flow-multiline-archive-on.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-multiline.yaml b/test/resources/flow-multiline.yaml index 0fe2358b..292f6c0c 100644 --- a/test/resources/flow-multiline.yaml +++ b/test/resources/flow-multiline.yaml @@ -31,6 +31,5 @@ jobs: path/output/test-results !path/**/*.tmp archive-artifacts-if-no-files-found: "warn" - workflow-file-name: "flow-multiline.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow-singleline-archive-on.yaml b/test/resources/flow-singleline-archive-on.yaml index 1ea4ae18..3e76c5f5 100644 --- a/test/resources/flow-singleline-archive-on.yaml +++ b/test/resources/flow-singleline-archive-on.yaml @@ -28,6 +28,5 @@ jobs: archive-artifacts-name: "namex" archive-artifacts-path: path/output/bin/@failure archive-artifacts-if-no-files-found: "warn" - workflow-file-name: "flow-singleline-archive-on.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/flow.yaml b/test/resources/flow.yaml index 3ef7aaab..9d4dc7af 100644 --- a/test/resources/flow.yaml +++ b/test/resources/flow.yaml @@ -25,6 +25,5 @@ jobs: build-command-downstream: | mvn clean mvn -e -nsu -fae -T1C clean install -Dfull -DskipTests -Dgwt.compiler.skip=true -Dgwt.skipCompilation=true -DjvmArgs=-Xmx4g - workflow-file-name: "flow.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows-flowFileJobId/child/.github/workflows/flow.yaml b/test/resources/hierarchyflows-flowFileJobId/child/.github/workflows/flow.yaml index a3bc0556..d019853c 100644 --- a/test/resources/hierarchyflows-flowFileJobId/child/.github/workflows/flow.yaml +++ b/test/resources/hierarchyflows-flowFileJobId/child/.github/workflows/flow.yaml @@ -11,6 +11,5 @@ jobs: with: parent-dependencies: "parent|flowx.yaml" build-command: 'echo "child"' - workflow-file-name: "flow.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows-flowFileJobId/parent-parent/.github/workflows/flowx.yaml b/test/resources/hierarchyflows-flowFileJobId/parent-parent/.github/workflows/flowx.yaml index c39e52d5..d7a7a5e3 100644 --- a/test/resources/hierarchyflows-flowFileJobId/parent-parent/.github/workflows/flowx.yaml +++ b/test/resources/hierarchyflows-flowFileJobId/parent-parent/.github/workflows/flowx.yaml @@ -11,6 +11,5 @@ jobs: with: child-dependencies: "parent" build-command: 'echo "parent-parent"' - workflow-file-name: "flowx.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows-flowFileJobId/parent/.github/workflows/flowx.yaml b/test/resources/hierarchyflows-flowFileJobId/parent/.github/workflows/flowx.yaml index 5c297de7..4530a32b 100644 --- a/test/resources/hierarchyflows-flowFileJobId/parent/.github/workflows/flowx.yaml +++ b/test/resources/hierarchyflows-flowFileJobId/parent/.github/workflows/flowx.yaml @@ -12,6 +12,5 @@ jobs: parent-dependencies: "parent-parent|:build-chain-2" child-dependencies: "child" build-command: 'echo "parent"' - workflow-file-name: "flowx.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows/child/.github/workflows/flow.yaml b/test/resources/hierarchyflows/child/.github/workflows/flow.yaml index c144c17f..01eaa846 100644 --- a/test/resources/hierarchyflows/child/.github/workflows/flow.yaml +++ b/test/resources/hierarchyflows/child/.github/workflows/flow.yaml @@ -11,6 +11,5 @@ jobs: with: parent-dependencies: "parent" build-command: 'echo "child"' - workflow-file-name: "flow.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows/parent-parent/.github/workflows/flow.yaml b/test/resources/hierarchyflows/parent-parent/.github/workflows/flow.yaml index aff72f52..3e1372e3 100644 --- a/test/resources/hierarchyflows/parent-parent/.github/workflows/flow.yaml +++ b/test/resources/hierarchyflows/parent-parent/.github/workflows/flow.yaml @@ -11,6 +11,5 @@ jobs: with: child-dependencies: "parent" build-command: 'echo "parent-parent"' - workflow-file-name: "flow.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" diff --git a/test/resources/hierarchyflows/parent/.github/workflows/flow.yaml b/test/resources/hierarchyflows/parent/.github/workflows/flow.yaml index db329914..c8a0c63a 100644 --- a/test/resources/hierarchyflows/parent/.github/workflows/flow.yaml +++ b/test/resources/hierarchyflows/parent/.github/workflows/flow.yaml @@ -12,6 +12,5 @@ jobs: parent-dependencies: "parent-parent" child-dependencies: "child" build-command: 'echo "parent"' - workflow-file-name: "flow.yaml" env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"