mirror of
https://github.com/Azure/k8s-deploy.git
synced 2026-06-24 13:39:27 +08:00
Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8249ba50bd | |||
| d1dd574643 | |||
| 87674d7272 | |||
| d7d5d3429f | |||
| 068b665bf3 | |||
| b5e9247a76 | |||
| 346e5b60f0 | |||
| 7ab8f38c56 | |||
| 9fa045d9cf | |||
| e4319ffe29 | |||
| aee2875fcd | |||
| 9458d67ac6 | |||
| 27085d52d5 | |||
| d953c709a5 | |||
| ba95de9cac | |||
| 34bbe17ae7 | |||
| 52883f3264 | |||
| ef8defce31 | |||
| 41514fca22 | |||
| d0f7e63ea0 | |||
| 77dd040b09 | |||
| 87732d1861 | |||
| d8b8394d0c | |||
| 764402d855 | |||
| db567f3869 | |||
| 79d7af7e76 | |||
| aa2e43b5c4 | |||
| 5f654c89dc | |||
| c3ad59d720 | |||
| faf09632f3 | |||
| bfca26e368 | |||
| b371791f3a | |||
| 7d00e7b645 | |||
| c578d50a12 | |||
| f9acc4f772 | |||
| 65e1224846 | |||
| 3a1c0b10eb | |||
| 3d1e46f18f | |||
| 3919a9ee22 | |||
| 48110f8b94 | |||
| 2c8e7a02f5 | |||
| b3381a2f94 | |||
| 7f721770f6 | |||
| af5108bc1c | |||
| 09a3895635 | |||
| 7da7f474fa | |||
| 43faecb5ec | |||
| 176baf94a2 | |||
| 2f7d1b9c8e | |||
| 010c39c72d | |||
| d28a9921ec | |||
| 75d14cf7f6 | |||
| 62f2b9a070 | |||
| fc977b0f8b | |||
| b9a4b99a0c | |||
| 468ae744db | |||
| 0cca7e9933 | |||
| 2dae567090 | |||
| cafbab6665 | |||
| 1cae8dfe8b | |||
| 69daec1568 | |||
| 1d151c72fa | |||
| 5094da45f0 | |||
| 717d6b1319 | |||
| 74b35d54c3 | |||
| bfb2fdfeba | |||
| 8050fad856 | |||
| caefba5a57 | |||
| 9c6e452f7d | |||
| 8a6dfb7253 | |||
| 91654ff2fe | |||
| 0451f7cf6e | |||
| d07b08fed0 | |||
| 1b6941228a | |||
| 8f53944957 |
@@ -1,32 +0,0 @@
|
|||||||
token=$1
|
|
||||||
commit=$2
|
|
||||||
repository=$3
|
|
||||||
prNumber=$4
|
|
||||||
frombranch=$5
|
|
||||||
tobranch=$6
|
|
||||||
|
|
||||||
getPayLoad() {
|
|
||||||
cat <<EOF
|
|
||||||
{
|
|
||||||
"event_type": "K8sDeployActionPR",
|
|
||||||
"client_payload":
|
|
||||||
{
|
|
||||||
"action": "CreateSecret",
|
|
||||||
"commit": "$commit",
|
|
||||||
"repository": "$repository",
|
|
||||||
"prNumber": "$prNumber",
|
|
||||||
"tobranch": "$tobranch",
|
|
||||||
"frombranch": "$frombranch"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
response=$(curl -X POST -H "Authorization: token $token" https://api.github.com/repos/Azure/azure-actions-integration-tests/dispatches --data "$(getPayLoad)")
|
|
||||||
|
|
||||||
if [ "$response" == "" ]; then
|
|
||||||
echo "Integration tests triggered successfully"
|
|
||||||
else
|
|
||||||
echo "Triggering integration tests failed with: '$response'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
name: "Code scanning - action"
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
schedule:
|
|
||||||
- cron: '0 19 * * 0'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
CodeQL-Build:
|
|
||||||
|
|
||||||
# CodeQL runs on ubuntu-latest and windows-latest
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
# We must fetch at least the immediate parents so that if this is
|
|
||||||
# a pull request then we can checkout the head.
|
|
||||||
fetch-depth: 2
|
|
||||||
|
|
||||||
# If this run was triggered by a pull request event, then checkout
|
|
||||||
# the head of the pull request instead of the merge commit.
|
|
||||||
- run: git checkout HEAD^2
|
|
||||||
if: ${{ github.event_name == 'pull_request' }}
|
|
||||||
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
|
||||||
- name: Initialize CodeQL
|
|
||||||
uses: github/codeql-action/init@v1
|
|
||||||
# Override language selection by uncommenting this and choosing your languages
|
|
||||||
# with:
|
|
||||||
# languages: go, javascript, csharp, python, cpp, java
|
|
||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
|
||||||
- name: Autobuild
|
|
||||||
uses: github/codeql-action/autobuild@v1
|
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
|
||||||
# 📚 https://git.io/JvXDl
|
|
||||||
|
|
||||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
|
||||||
# and modify them (or add more) to build your code if your project
|
|
||||||
# uses a compiled language
|
|
||||||
|
|
||||||
#- run: |
|
|
||||||
# make bootstrap
|
|
||||||
# make release
|
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
|
||||||
uses: github/codeql-action/analyze@v1
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
name: "Trigger Integration tests"
|
|
||||||
on:
|
|
||||||
# push:
|
|
||||||
# branches:
|
|
||||||
# - master
|
|
||||||
# - 'releases/*'
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- 'releases/*'
|
|
||||||
jobs:
|
|
||||||
trigger-integration-tests:
|
|
||||||
name: Trigger Integration tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out repository
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
path: IntegrationTests
|
|
||||||
|
|
||||||
- name: Trigger Test run
|
|
||||||
run: |
|
|
||||||
bash ./IntegrationTests/.github/workflows/TriggerIntegrationTests.sh ${{ secrets.L2_REPO_TOKEN }} ${{ github.event.pull_request.head.sha }} ${{ github.repository }} ${{ github.event.pull_request.number }} ${{ github.event.pull_request.head.ref }} ${{ github.event.pull_request.base.ref }}
|
|
||||||
@@ -1,232 +1,101 @@
|
|||||||
|
# Deploy manifest action for Kubernetes
|
||||||
|
Use this action to bake and deploy manifests to Kubernetes clusters.
|
||||||
|
|
||||||
# Deploy manifests action for Kubernetes
|
Assumes that the deployment target K8s cluster context was set earlier in the workflow by using either [`Azure/aks-set-context`](https://github.com/Azure/aks-set-context/tree/releases/v1) or [`Azure/k8s-set-context`](https://github.com/Azure/k8s-set-context/tree/releases/v1)
|
||||||
|
|
||||||
This action can be used to deploy manifests to Kubernetes clusters.
|
#### Artifact substitution
|
||||||
|
The deploy action takes as input a list of container images which can be specified along with their tags or digests. The same is substituted into the non-templatized version of manifest files before applying to the cluster to ensure that the right version of the image is pulled by the cluster nodes.
|
||||||
|
|
||||||
This action requires that the cluster context be set earlier in the workflow by using either the [Azure/aks-set-context](https://github.com/Azure/aks-set-context/tree/releases/v1) action or the [Azure/k8s-set-context](https://github.com/Azure/k8s-set-context/tree/releases/v1) action.
|
#### Manifest stability
|
||||||
|
Rollout status is checked for the Kubernetes objects deployed. This is done to incorporate stability checks while computing the task status as success/failure.
|
||||||
|
|
||||||
If you are looking to automate your workflows to deploy to [Azure Web Apps](https://azure.microsoft.com/en-us/services/app-service/web/) and [Azure Web App for Containers](https://azure.microsoft.com/en-us/services/app-service/containers/), consider using [`Azure/webapps-deploy`](https://github.com/Azure/webapps-deploy) action.
|
#### Secret handling
|
||||||
|
The manifest files specfied as inputs are augmented with appropriate imagePullSecrets before deploying to the cluster.
|
||||||
|
|
||||||
## Action capabilities
|
#### Sample YAML to run a basic deployment
|
||||||
|
|
||||||
Following are the key capabilities of this action:
|
|
||||||
|
|
||||||
- **Artifact substitution**: The deploy action takes as input a list of container images which can be specified along with their tags or digests. The same is substituted into the non-templatized version of manifest files before applying to the cluster to ensure that the right version of the image is pulled by the cluster nodes.
|
|
||||||
|
|
||||||
- **Object stability checks**: Rollout status is checked for the Kubernetes objects deployed. This is done to incorporate stability checks while computing the action status as success/failure.
|
|
||||||
|
|
||||||
- **Secret handling**: The secret names specified as inputs in the action are used to augment the input manifest files with imagePullSecrets values before deploying to the cluster. Also, checkout the [Azure/k8s-create-secret](https://github.com/Azure/k8s-create-secret) action for creation of generic or docker-registry secrets in the cluster.
|
|
||||||
|
|
||||||
- **Deployment strategy** The action supports canary and blue-green deployment strategies:
|
|
||||||
- **Canary strategy**: Choosing canary strategy with this action leads to creation of workloads suffixed with '-baseline' and '-canary'. There are two methods of traffic splitting supported in the action:
|
|
||||||
- **Service Mesh Interface**: Service Mesh Interface abstraction allows for plug-and-play configuration with service mesh providers such as Linkerd and Istio. Meanwhile, this action takes away the hard work of mapping SMI's TrafficSplit objects to the stable, baseline and canary services during the lifecycle of the deployment strategy. Service mesh based canary deployments using this action are more accurate as service mesh providers enable granular percentage traffic split (via service registry and sidecar containers injected into pods alongside application containers).
|
|
||||||
- **Only Kubernetes (no service mesh)**: In the absence of service mesh, while it may not be possible to achieve exact percentage split at the request level, it is still possible to perform canary deployments by deploying -baseline and -canary workload variants next to the stable variant. The service routes requests to pods of all three workload variants as the selector-label constraints are met (KubernetesManifest will honor these when creating -baseline and -canary variants). This achieves the intended effect of routing only a portion of total requests to the canary.
|
|
||||||
- **Blue-Green strategy**: Choosing blue-green strategy with this action leads to creation of workloads suffixed with '-green'. There are three route-methods supported in the action:
|
|
||||||
|
|
||||||
*Terminolgy: An **identified** service is one that is supplied as part of the input manifest(s) and targets a workload in the supplied manifest(s).
|
|
||||||
- **Service route-method**: **Identified** services are configured to target the green deployments.
|
|
||||||
- **Ingress route-method**: Along with deployments, new services are created with '-green' suffix (for **identified** services), and the ingresses are in turn updated to target the new services.
|
|
||||||
- **SMI route-method**: A new [TrafficSplit](https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md) object is created for each **identified** service. The TrafficSplit object is updated to target the new deployments. **Note** that this works only if SMI is set up in the cluster.
|
|
||||||
|
|
||||||
Traffic is routed to the new workloads only after the time provided as `version-switch-buffer` input has passed. `promote` action creates workloads and services with new configurations but without any suffix. `reject` action routes traffic back to the old workloads and deletes the '-green' workloads.
|
|
||||||
|
|
||||||
|
|
||||||
## Action inputs
|
|
||||||
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Action inputs</th>
|
|
||||||
<th>Description</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
<td><code>namespace</code><br/>Namespace</td>
|
|
||||||
<td>(Optional) Namespace within the cluster to deploy to.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>manifests</code><br/>Manifests</td>
|
|
||||||
<td>(Required) Path to the manifest files to be used for deployment</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>images</code><br/>Images</td>
|
|
||||||
<td>(Optional) Fully qualified resource URL of the image(s) to be used for substitutions on the manifest files. This multiline input accepts specifying multiple artifact substitutions in newline separated form. For example - <br>images: |<br>  contosodemo.azurecr.io/foo:test1<br>  contosodemo.azurecr.io/bar:test2<br>In this example, all references to contosodemo.azurecr.io/foo and contosodemo.azurecr.io/bar are searched for in the image field of the input manifest files. For the matches found, the tags test1 and test2 are substituted.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>imagepullsecrets</code><br/>Image pull secrets</td>
|
|
||||||
<td>(Optional) Multiline input where each line contains the name of a docker-registry secret that has already been setup within the cluster. Each of these secret names are added under imagePullSecrets field for the workloads found in the input manifest files</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>strategy</code><br/>Strategy</td>
|
|
||||||
<td>(Optional) Deployment strategy to be used while applying manifest files on the cluster. Acceptable values: none/canary/blue-green. none - No deployment strategy is used when deploying. canary - Canary deployment strategy is used when deploying to the cluster. blue-green - Blue-Green deployment strategy is used when deploying to cluster.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>traffic-split-method</code><br/>Traffic split method</td>
|
|
||||||
<td>(Optional) Acceptable values: pod/smi; Default value: pod <br>SMI: Percentage traffic split is done at request level using service mesh. Service mesh has to be setup by cluster admin. Orchestration of <a href="https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md" data-raw-source="TrafficSplit](https://github.com/deislabs/smi-spec/blob/master/traffic-split.md)">TrafficSplit</a> objects of SMI is handled by this action. <br>Pod: Percentage split not possible at request level in the absence of service mesh. So the percentage input is used to calculate the replicas for baseline and canary as a percentage of replicas specified in the input manifests for the stable variant.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>percentage</code><br/>Percentage</td>
|
|
||||||
<td>(Required if strategy == canary) Percentage used to compute the number of replicas of '-baseline' and '-canary' varaints of the workloads found in manifest files. For the specified percentage input, if (percentage * numberOfDesirerdReplicas)/100 is not a round number, the floor of this number is used while creating '-baseline' and '-canary'<br/>Example: If Deployment hello-world was found in the input manifest file with 'replicas: 4' and if 'strategy: canary' and 'percentage: 25' are given as inputs to the action, then the Deployments hello-world-baseline and hello-world-canary are created with 1 replica each. The '-baseline' variant is created with the same image and tag as the stable version (4 replica variant prior to deployment) while the '-canary' variant is created with the image and tag corresponding to the new changes being deployed</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>baseline-and-canary-replicas</code><br/>Baseline and canary replicas</td>
|
|
||||||
<td>(Optional; Relevant only if trafficSplitMethod == smi) When trafficSplitMethod == smi, as percentage traffic split is controlled in the service mesh plane, the actual number of replicas for canary and baseline variants could be controlled independently of the traffic split. For example, assume that the input Deployment manifest desired 30 replicas to be used for stable and that the following inputs were specified for the action - <br> strategy: canary<br> trafficSplitMethod: smi<br> percentage: 20<br> baselineAndCanaryReplicas: 1<br> In this case, stable variant will receive 80% traffic while baseline and canary variants will receive 10% each (20% split equally between baseline and canary). However, instead of creating baseline and canary with 3 replicas, the explicit count of baseline and canary replicas is honored. That is, only 1 replica each is created for baseline and canary variants.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>route-method</code><br/>Route Method</td>
|
|
||||||
<td>(Optional; Relevant only if strategy==blue-green) Default value: service. Acceptable values: service/ingress/smi. Traffic is routed based on this input.
|
|
||||||
<br>Service: Service selector labels are updated to target '-green' workloads.
|
|
||||||
<br>Ingress: Ingress backends are updated to target the new '-green' services which in turn target '-green' deployments.
|
|
||||||
<br>SMI: A <a href="https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md" data-raw-source="TrafficSplit](https://github.com/deislabs/smi-spec/blob/master/traffic-split.md)">TrafficSplit</a> object is created for each required service to route traffic to new workloads.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>version-switch-buffer</code><br/>Version Switch Buffer</td>
|
|
||||||
<td>(Optional; Relevant only if strategy==blue-green and action == deploy) Default value: 0. Acceptable values: 1-300. Waits for the given input in minutes before routing traffic to '-green' workloads.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>action</code><br/>Action</td>
|
|
||||||
<td>(Required) Default value: deploy. Acceptable values: deploy/promote/reject. Promote or reject actions are used to promote or reject canary/blue-green deployments. Sample YAML snippets are provided below for guidance on how to use the same.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>kubectl-version</code><br/>Kubectl version</td>
|
|
||||||
<td>(Optional) Version of kubectl client to be used for deploying the manifest to the cluster. If this input is left unspecified, latest version is used.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><code>force</code><br/>Force</td>
|
|
||||||
<td>(Optional) Deploy when a previous deployment already exists. If true then '--force' argument is added to the apply command. Using '--force' argument is not recommended in production.</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
## Examples YAML snippets
|
|
||||||
|
|
||||||
### Basic deployment (without any deployment strategy)
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: Azure/k8s-deploy@v1
|
- uses: Azure/k8s-deploy@v1
|
||||||
with:
|
with:
|
||||||
namespace: 'myapp'
|
namespace: 'myapp' # optional
|
||||||
manifests: |
|
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
|
||||||
imagepullsecrets: |
|
imagepullsecrets: |
|
||||||
image-pull-secret1
|
image-pull-secret1
|
||||||
image-pull-secret2
|
image-pull-secret2
|
||||||
kubectl-version: 'latest'
|
manifests: '/manifests/*.*'
|
||||||
|
kubectl-version: 'latest' # optional
|
||||||
```
|
```
|
||||||
|
|
||||||
### Deployment Strategies - Canary deployment without service mesh
|
### Deployment Strategies
|
||||||
|
|
||||||
|
#### Pod Canary
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: Azure/k8s-deploy@v1
|
- uses: Azure/k8s-deploy@v1
|
||||||
with:
|
with:
|
||||||
namespace: 'myapp'
|
namespace: 'myapp' # optional
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||||
imagepullsecrets: |
|
imagepullsecrets: |
|
||||||
image-pull-secret1
|
image-pull-secret1
|
||||||
image-pull-secret2
|
image-pull-secret2
|
||||||
manifests: |
|
manifests: '/manifests/*.*'
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
strategy: canary
|
strategy: canary
|
||||||
percentage: 20
|
percentage: 20
|
||||||
```
|
```
|
||||||
|
|
||||||
### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
|
Inorder to promote or reject your canary deployment use the following:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: Azure/k8s-deploy@v1
|
- uses: Azure/k8s-deploy@v1
|
||||||
with:
|
with:
|
||||||
namespace: 'myapp'
|
namespace: 'myapp' # optional
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||||
imagepullsecrets: |
|
imagepullsecrets: |
|
||||||
image-pull-secret1
|
image-pull-secret1
|
||||||
image-pull-secret2
|
image-pull-secret2
|
||||||
manifests: |
|
manifests: '/manifests/*.*'
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
strategy: canary
|
strategy: canary
|
||||||
action: promote # substitute reject if you want to reject
|
percentage: 20
|
||||||
|
action: promote # set to reject if you want to reject it
|
||||||
```
|
```
|
||||||
|
|
||||||
### Deployment Strategies - Canary deployment based on Service Mesh Interface
|
#### SMI Canary
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: Azure/k8s-deploy@v1
|
- uses: Azure/k8s-deploy@v1
|
||||||
with:
|
with:
|
||||||
namespace: 'myapp'
|
namespace: 'myapp' # optional
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||||
imagepullsecrets: |
|
imagepullsecrets: |
|
||||||
image-pull-secret1
|
image-pull-secret1
|
||||||
image-pull-secret2
|
image-pull-secret2
|
||||||
manifests: |
|
manifests: '/manifests/*.*'
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
strategy: canary
|
strategy: canary
|
||||||
traffic-split-method: smi
|
traffic-split-method: smi
|
||||||
percentage: 20
|
percentage: 20
|
||||||
baseline-and-canary-replicas: 1
|
baseline-and-canary-replicas: 1
|
||||||
```
|
```
|
||||||
### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
|
|
||||||
|
Inorder to promote or reject your canary deployment use the following:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- uses: Azure/k8s-deploy@v1
|
- uses: Azure/k8s-deploy@v1
|
||||||
with:
|
with:
|
||||||
namespace: 'myapp'
|
namespace: 'myapp' # optional
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||||
imagepullsecrets: |
|
imagepullsecrets: |
|
||||||
image-pull-secret1
|
image-pull-secret1
|
||||||
image-pull-secret2
|
image-pull-secret2
|
||||||
manifests: |
|
manifests: '/manifests/*.*'
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
strategy: canary
|
strategy: canary
|
||||||
traffic-split-method: smi
|
traffic-split-method: smi
|
||||||
action: reject # substitute reject if you want to reject
|
percentage: 20
|
||||||
```
|
baseline-and-canary-replicas: 1
|
||||||
### Deployment Strategies - Blue-Green deployment with different route methods
|
action: promote # set to reject if you want to reject it
|
||||||
|
|
||||||
```yaml
|
|
||||||
- uses: Azure/k8s-deploy@v1
|
|
||||||
with:
|
|
||||||
namespace: 'myapp'
|
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
|
||||||
imagepullsecrets: |
|
|
||||||
image-pull-secret1
|
|
||||||
image-pull-secret2
|
|
||||||
manifests: |
|
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
ingress.yml
|
|
||||||
strategy: blue-green
|
|
||||||
route-method: ingress # substitute with service/smi as per need
|
|
||||||
version-switch-buffer: 15
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### **To promote/reject the green workload created by the above snippet, the following YAML snippet could be used:**
|
Refer to the action metadata file for details about all the inputs https://github.com/Azure/k8s-deploy/blob/master/action.yml
|
||||||
|
|
||||||
```yaml
|
## End to end workflow for building container images and deploying to an Azure Kubernetes Service cluster
|
||||||
- uses: Azure/k8s-deploy@v1
|
|
||||||
with:
|
|
||||||
namespace: 'myapp'
|
|
||||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
|
||||||
imagepullsecrets: |
|
|
||||||
image-pull-secret1
|
|
||||||
image-pull-secret2
|
|
||||||
manifests: |
|
|
||||||
deployment.yaml
|
|
||||||
service.yaml
|
|
||||||
ingress-yml
|
|
||||||
strategy: blue-green
|
|
||||||
route-method: ingress # should be the same as the value when action was deploy
|
|
||||||
action: promote # substitute reject if you want to reject
|
|
||||||
```
|
|
||||||
|
|
||||||
## End to end workflows
|
|
||||||
|
|
||||||
Following are a few examples of not just this action, but how this action could be used along with other container and k8s related actions for building images and deploying objects onto k8s clusters:
|
|
||||||
|
|
||||||
### Build container image and deploy to Azure Kubernetes Service cluster
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
on: [push]
|
on: [push]
|
||||||
@@ -272,7 +141,7 @@ jobs:
|
|||||||
demo-k8s-secret
|
demo-k8s-secret
|
||||||
```
|
```
|
||||||
|
|
||||||
### Build container image and deploy to any Azure Kubernetes Service cluster
|
## End to end workflow for building container images and deploying to a Kubernetes cluster
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
on: [push]
|
on: [push]
|
||||||
|
|||||||
@@ -1,777 +0,0 @@
|
|||||||
import * as fs from 'fs';
|
|
||||||
import * as inputParam from '../src/input-parameters';
|
|
||||||
import * as fileHelper from '../src/utilities/files-helper';
|
|
||||||
import {
|
|
||||||
Kubectl,
|
|
||||||
} from '../src/kubectl-object-model';
|
|
||||||
import {
|
|
||||||
mocked
|
|
||||||
} from 'ts-jest/utils';
|
|
||||||
import * as kubectlUtils from '../src/utilities/kubectl-util';
|
|
||||||
|
|
||||||
var path = require('path');
|
|
||||||
const inputParamMock = mocked(inputParam, true);
|
|
||||||
var deploymentYaml = "";
|
|
||||||
|
|
||||||
import * as blueGreenHelper from '../src/utilities/strategy-helpers/blue-green-helper';
|
|
||||||
import * as blueGreenHelperService from '../src/utilities/strategy-helpers/service-blue-green-helper';
|
|
||||||
import * as blueGreenHelperIngress from '../src/utilities/strategy-helpers/ingress-blue-green-helper';
|
|
||||||
import * as blueGreenHelperSMI from '../src/utilities/strategy-helpers/smi-blue-green-helper';
|
|
||||||
|
|
||||||
beforeAll(() => {
|
|
||||||
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'bg.yml'), 'utf8');
|
|
||||||
process.env["KUBECONFIG"] = 'kubeConfig';
|
|
||||||
});
|
|
||||||
|
|
||||||
test("deployBlueGreen - checks if deployment can be done, then deploys", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
};
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperService.deployBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
|
|
||||||
"newFilePaths": "hello",
|
|
||||||
"result": ""
|
|
||||||
});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
expect(kubeCtl.apply).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenPromote - checks if in deployed state and then promotes", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "v1",
|
|
||||||
"kind": "Service",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"app": "testapp",
|
|
||||||
"k8s.deploy.color": "green"
|
|
||||||
},
|
|
||||||
"ports": [{
|
|
||||||
"protocol": "TCP",
|
|
||||||
"port": 80,
|
|
||||||
"targetPort": 80
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
//Invoke and assert
|
|
||||||
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
|
|
||||||
expect(blueGreenHelperService.promoteBlueGreenService(kubeCtl, manifestObjects)).toMatchObject({});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(kubeCtl.apply).toBeCalledWith("hello");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenReject - routes servcies to old deployment and deletes new deployment", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "apps/v1beta1",
|
|
||||||
"kind": "Deployment",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testapp",
|
|
||||||
"labels": {
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"matchLabels": {
|
|
||||||
"app": "testapp",
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"replicas": 1,
|
|
||||||
"template": {
|
|
||||||
"metadata": {
|
|
||||||
"labels": {
|
|
||||||
"app": "testapp",
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"containers": [{
|
|
||||||
"name": "testapp",
|
|
||||||
"image": "testcr.azurecr.io/testapp",
|
|
||||||
"ports": [{
|
|
||||||
"containerPort": 80
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
kubeCtl.delete = jest.fn().mockReturnValue('');
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenReject - deletes services if old deployment does not exist", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
};
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.delete = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("isIngressRoute() - returns true if route-method is ingress", () => {
|
|
||||||
// default is service
|
|
||||||
expect(blueGreenHelper.isIngressRoute()).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("isIngressRoute() - returns true if route-method is ingress", () => {
|
|
||||||
inputParamMock.routeMethod = 'ingress'
|
|
||||||
expect(blueGreenHelper.isIngressRoute()).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("deployBlueGreenIngress - creates deployments, services and other non ingress objects", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
};
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperIngress.deployBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
|
|
||||||
"newFilePaths": "hello",
|
|
||||||
"result": ""
|
|
||||||
});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(kubeCtl.apply).toBeCalledWith("hello");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenPromoteIngress - checks if in deployed state and then promotes ingress", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "networking.k8s.io/v1beta1",
|
|
||||||
"kind": "Ingress",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testingress",
|
|
||||||
"labels": {
|
|
||||||
"k8s.deploy.color": "green"
|
|
||||||
},
|
|
||||||
"annotations": {
|
|
||||||
"nginx.ingress.kubernetes.io/rewrite-target": "/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"rules": [{
|
|
||||||
"http": {
|
|
||||||
"paths": [{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "testservice-green",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperIngress.promoteBlueGreenIngress(kubeCtl, manifestObjects)).toMatchObject({});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(kubeCtl.apply).toBeCalledWith("hello");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenRejectIngress - routes ingress to stable services and deletes new deployments and services", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.delete = jest.fn().mockReturnValue('');
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperIngress.rejectBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("isSMIRoute() - returns true if route-method is smi", () => {
|
|
||||||
inputParamMock.routeMethod = 'smi'
|
|
||||||
expect(blueGreenHelper.isSMIRoute()).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("isSMIRoute() - returns true if route-method is smi", () => {
|
|
||||||
inputParamMock.routeMethod = 'ingress'
|
|
||||||
expect(blueGreenHelper.isSMIRoute()).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("deployBlueGreenSMI - checks if deployment can be done, then deploys along this auxiliary services and trafficsplit", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
};
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
const kubectlUtilsMock = mocked(kubectlUtils, true);
|
|
||||||
kubectlUtilsMock.getTrafficSplitAPIVersion = jest.fn().mockReturnValue('split.smi-spec.io/v1alpha2');
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.deployBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
|
|
||||||
"newFilePaths": "hello",
|
|
||||||
"result": ""
|
|
||||||
});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenPromoteSMI - checks weights of trafficsplit and then deploys", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "split.smi-spec.io/v1alpha2",
|
|
||||||
"kind": "TrafficSplit",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice-rollout"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"service": "testservice",
|
|
||||||
"backends": [{
|
|
||||||
"service": "testservice-stable",
|
|
||||||
"weight": 0
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"service": "testservice-green",
|
|
||||||
"weight": 100
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.promoteBlueGreenSMI(kubeCtl, manifestObjects)).toMatchObject({});
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenRejectSMI - routes servcies to old deployment and deletes new deployment, auxiliary services and trafficsplit", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "apps/v1beta1",
|
|
||||||
"kind": "Deployment",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testapp",
|
|
||||||
"labels": {
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"matchLabels": {
|
|
||||||
"app": "testapp",
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"replicas": 1,
|
|
||||||
"template": {
|
|
||||||
"metadata": {
|
|
||||||
"labels": {
|
|
||||||
"app": "testapp",
|
|
||||||
"k8s.deploy.color": "none"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"containers": [{
|
|
||||||
"name": "testapp",
|
|
||||||
"image": "testcr.azurecr.io/testapp",
|
|
||||||
"ports": [{
|
|
||||||
"containerPort": 80
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
kubeCtl.delete = jest.fn().mockReturnValue('');
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]);
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blueGreenRejectSMI - deletes service if stable deployment doesn't exist", () => {
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
};
|
|
||||||
kubeCtl.delete = jest.fn().mockReturnValue('');
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]);
|
|
||||||
expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]);
|
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
|
|
||||||
});
|
|
||||||
|
|
||||||
// other functions and branches
|
|
||||||
test("blueGreenRouteIngress - routes to green services in nextlabel is green", () => {
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
const fileHelperMock = mocked(fileHelper, true);
|
|
||||||
const ingEntList = [{
|
|
||||||
"apiVersion": "networking.k8s.io/v1beta1",
|
|
||||||
"kind": "Ingress",
|
|
||||||
"metadata": {
|
|
||||||
"name": "test-ingress",
|
|
||||||
"annotations": {
|
|
||||||
"nginx.ingress.kubernetes.io/rewrite-target": "/"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"rules": [{
|
|
||||||
"http": {
|
|
||||||
"paths": [{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "testservice",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "random",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"apiVersion": "networking.k8s.io/v1beta1",
|
|
||||||
"kind": "Ingress",
|
|
||||||
"metadata": {
|
|
||||||
"name": "test-ingress",
|
|
||||||
"annotations": {
|
|
||||||
"nginx.ingress.kubernetes.io/rewrite-target": "/"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"rules": [{
|
|
||||||
"http": {
|
|
||||||
"paths": [{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "random",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
const serEntList = [{
|
|
||||||
"apiVersion": "v1",
|
|
||||||
"kind": "Service",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"app": "testapp",
|
|
||||||
},
|
|
||||||
"ports": [{
|
|
||||||
"protocol": "TCP",
|
|
||||||
"port": 80,
|
|
||||||
"targetPort": 80
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
let serviceEntityMap = new Map<string, string>();
|
|
||||||
serviceEntityMap.set('testservice', 'testservice-green');
|
|
||||||
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
|
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue('');
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperIngress.routeBlueGreenIngress(kubeCtl, 'green', serviceEntityMap, ingEntList));
|
|
||||||
expect(kubeCtl.apply).toBeCalled();
|
|
||||||
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shouldWePromoteIngress - throws if routed ingress does not exist", () => {
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
const ingEntList = [{
|
|
||||||
"apiVersion": "networking.k8s.io/v1beta1",
|
|
||||||
"kind": "Ingress",
|
|
||||||
"metadata": {
|
|
||||||
"name": "test-ingress",
|
|
||||||
"annotations": {
|
|
||||||
"nginx.ingress.kubernetes.io/rewrite-target": "/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"rules": [{
|
|
||||||
"http": {
|
|
||||||
"paths": [{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "testservice",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
let serviceEntityMap = new Map<string, string>();
|
|
||||||
serviceEntityMap.set('testservice', 'testservice-green');
|
|
||||||
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperIngress.validateIngressesState(kubeCtl, ingEntList, serviceEntityMap)).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => {
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "split.smi-spec.io/v1alpha2",
|
|
||||||
"kind": "TrafficSplit",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice-trafficsplit"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"service": "testservice",
|
|
||||||
"backends": [{
|
|
||||||
"service": "testservice-stable",
|
|
||||||
"weight": 100
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"service": "testservice-green",
|
|
||||||
"weight": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const depEntList = [{
|
|
||||||
"apiVersion": "apps/v1beta1",
|
|
||||||
"kind": "Deployment",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testapp",
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"matchLabels": {
|
|
||||||
"app": "testapp",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"replicas": 1,
|
|
||||||
"template": {
|
|
||||||
"metadata": {
|
|
||||||
"labels": {
|
|
||||||
"app": "testapp",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"containers": [{
|
|
||||||
"name": "testapp",
|
|
||||||
"image": "testcr.azurecr.io/testapp",
|
|
||||||
"ports": [{
|
|
||||||
"containerPort": 80
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
const serEntList = [{
|
|
||||||
"apiVersion": "v1",
|
|
||||||
"kind": "Service",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"app": "testapp",
|
|
||||||
},
|
|
||||||
"ports": [{
|
|
||||||
"protocol": "TCP",
|
|
||||||
"port": 80,
|
|
||||||
"targetPort": 80
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => {
|
|
||||||
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
|
|
||||||
let temp = {
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
"apiVersion": "split.smi-spec.io/v1alpha2",
|
|
||||||
"kind": "TrafficSplit",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice-trafficsplit"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"service": "testservice",
|
|
||||||
"backends": [{
|
|
||||||
"service": "testservice-stable",
|
|
||||||
"weight": 0
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"service": "testservice-green",
|
|
||||||
"weight": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const depEntList = [{
|
|
||||||
"apiVersion": "apps/v1beta1",
|
|
||||||
"kind": "Deployment",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testapp",
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"matchLabels": {
|
|
||||||
"app": "testapp",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"replicas": 1,
|
|
||||||
"template": {
|
|
||||||
"metadata": {
|
|
||||||
"labels": {
|
|
||||||
"app": "testapp",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"containers": [{
|
|
||||||
"name": "testapp",
|
|
||||||
"image": "testcr.azurecr.io/testapp",
|
|
||||||
"ports": [{
|
|
||||||
"containerPort": 80
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
const serEntList = [{
|
|
||||||
"apiVersion": "v1",
|
|
||||||
"kind": "Service",
|
|
||||||
"metadata": {
|
|
||||||
"name": "testservice"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"app": "testapp",
|
|
||||||
},
|
|
||||||
"ports": [{
|
|
||||||
"protocol": "TCP",
|
|
||||||
"port": 80,
|
|
||||||
"targetPort": 80
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
|
|
||||||
|
|
||||||
//Invoke and assert
|
|
||||||
expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => {
|
|
||||||
expect(blueGreenHelper.getSuffix('green')).toBe('-green');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => {
|
|
||||||
expect(blueGreenHelper.getSuffix('random')).toBe('');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getServiceSpacLabel() - returns empty string if BLUE_GREEN_VERSION_LABEL in spec selector doesn't exist", () => {
|
|
||||||
let input = {
|
|
||||||
"apiVersion": "apps/v1",
|
|
||||||
"kind": "Deployment",
|
|
||||||
"metadata": {
|
|
||||||
"name": "sample-deployment"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"matchLabels": {
|
|
||||||
"app": "sample",
|
|
||||||
"k8s.deploy.color": "green"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"template": {
|
|
||||||
"metadata": {
|
|
||||||
"labels": {
|
|
||||||
"app": "sample"
|
|
||||||
},
|
|
||||||
"annotations": {
|
|
||||||
"prometheus.io/scrape": "true",
|
|
||||||
"prometheus.io/port": "8888"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"containers": [{
|
|
||||||
"name": "sample",
|
|
||||||
"image": "tsugunt/sample:v34",
|
|
||||||
"ports": [{
|
|
||||||
"containerPort": 8888
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(blueGreenHelperService.getServiceSpecLabel(input)).toBe('');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getDeploymentMatchLabels() - return false is input doesnt have matchLabels", () => {
|
|
||||||
let input = {
|
|
||||||
"apiVersion": "v1",
|
|
||||||
"kind": "Service",
|
|
||||||
"metadata": {
|
|
||||||
"name": "sample-service"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"selector": {
|
|
||||||
"app": "sample",
|
|
||||||
"k8s.deploy.color": "green"
|
|
||||||
},
|
|
||||||
"ports": [{
|
|
||||||
"protocol": "TCP",
|
|
||||||
"port": 80,
|
|
||||||
"targetPort": 8888,
|
|
||||||
"nodePort": 31002
|
|
||||||
}],
|
|
||||||
"type": "NodePort"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(blueGreenHelper.getDeploymentMatchLabels(input)).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getServiceSelector() - return false if spec selector does not exist", () => {
|
|
||||||
let input = {
|
|
||||||
"apiVersion": "networking.k8s.io/v1beta1",
|
|
||||||
"kind": "Ingress",
|
|
||||||
"metadata": {
|
|
||||||
"name": "test-ingress",
|
|
||||||
"annotations": {
|
|
||||||
"nginx.ingress.kubernetes.io/rewrite-target": "/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"rules": [{
|
|
||||||
"http": {
|
|
||||||
"paths": [{
|
|
||||||
"path": "/testpath",
|
|
||||||
"pathType": "Prefix",
|
|
||||||
"backend": {
|
|
||||||
"serviceName": "test",
|
|
||||||
"servicePort": 80
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(blueGreenHelper.getServiceSelector(input)).toBeFalsy();
|
|
||||||
});
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
apiVersion : apps/v1beta1
|
|
||||||
kind: Deployment
|
|
||||||
metadata:
|
|
||||||
name: testapp
|
|
||||||
spec:
|
|
||||||
selector:
|
|
||||||
matchLabels:
|
|
||||||
app: testapp
|
|
||||||
replicas: 1
|
|
||||||
template:
|
|
||||||
metadata:
|
|
||||||
labels:
|
|
||||||
app: testapp
|
|
||||||
spec:
|
|
||||||
containers:
|
|
||||||
- name: testapp
|
|
||||||
image: testcr.azurecr.io/testapp
|
|
||||||
ports:
|
|
||||||
- containerPort: 80
|
|
||||||
---
|
|
||||||
apiVersion: v1
|
|
||||||
kind: Service
|
|
||||||
metadata:
|
|
||||||
name: testservice
|
|
||||||
spec:
|
|
||||||
selector:
|
|
||||||
app: testapp
|
|
||||||
ports:
|
|
||||||
- protocol: TCP
|
|
||||||
port: 80
|
|
||||||
targetPort: 80
|
|
||||||
---
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
apiVersion : apps/v1beta1
|
|
||||||
kind: Deployment
|
|
||||||
metadata:
|
|
||||||
name: testapp
|
|
||||||
spec:
|
|
||||||
selector:
|
|
||||||
matchLabels:
|
|
||||||
app: testapp
|
|
||||||
replicas: 1
|
|
||||||
template:
|
|
||||||
metadata:
|
|
||||||
labels:
|
|
||||||
app: testapp
|
|
||||||
spec:
|
|
||||||
containers:
|
|
||||||
- name: testapp
|
|
||||||
image: testcr.azurecr.io/testapp
|
|
||||||
ports:
|
|
||||||
- containerPort: 80
|
|
||||||
---
|
|
||||||
apiVersion: v1
|
|
||||||
kind: Service
|
|
||||||
metadata:
|
|
||||||
name: testservice
|
|
||||||
spec:
|
|
||||||
selector:
|
|
||||||
app: testapp
|
|
||||||
ports:
|
|
||||||
- protocol: TCP
|
|
||||||
port: 80
|
|
||||||
targetPort: 80
|
|
||||||
---
|
|
||||||
apiVersion: networking.k8s.io/v1beta1
|
|
||||||
kind: Ingress
|
|
||||||
metadata:
|
|
||||||
name: testingress
|
|
||||||
annotations:
|
|
||||||
nginx.ingress.kubernetes.io/rewrite-target: /
|
|
||||||
spec:
|
|
||||||
rules:
|
|
||||||
- http:
|
|
||||||
paths:
|
|
||||||
- path: /testpath
|
|
||||||
pathType: Prefix
|
|
||||||
backend:
|
|
||||||
serviceName: testservice
|
|
||||||
servicePort: 80
|
|
||||||
---
|
|
||||||
apiVersion: v1
|
|
||||||
kind: ConfigMap
|
|
||||||
metadata:
|
|
||||||
name: testconfigmap
|
|
||||||
data:
|
|
||||||
# property-like keys; each key maps to a simple value
|
|
||||||
whats_this: "testing"
|
|
||||||
why_this: "testing"
|
|
||||||
---
|
|
||||||
apiVersion: v1
|
|
||||||
kind: Service
|
|
||||||
metadata:
|
|
||||||
name: testservice-2
|
|
||||||
spec:
|
|
||||||
selector:
|
|
||||||
app: testapp-2
|
|
||||||
ports:
|
|
||||||
- protocol: TCP
|
|
||||||
port: 80
|
|
||||||
targetPort: 80
|
|
||||||
---
|
|
||||||
apiVersion: networking.k8s.io/v1beta1
|
|
||||||
kind: Ingress
|
|
||||||
metadata:
|
|
||||||
name: testingress-1
|
|
||||||
annotations:
|
|
||||||
nginx.ingress.kubernetes.io/rewrite-target: /
|
|
||||||
spec:
|
|
||||||
rules:
|
|
||||||
- http:
|
|
||||||
paths:
|
|
||||||
- path: /testpath
|
|
||||||
pathType: Prefix
|
|
||||||
backend:
|
|
||||||
serviceName: testnotservice
|
|
||||||
servicePort: 80
|
|
||||||
---
|
|
||||||
+20
-26
@@ -6,7 +6,7 @@ import * as deployment from '../src/utilities/strategy-helpers/deployment-helper
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as io from '@actions/io';
|
import * as io from '@actions/io';
|
||||||
import * as toolCache from '@actions/tool-cache';
|
import * as toolCache from '@actions/tool-cache';
|
||||||
import * as glob from 'glob';
|
import * as fileHelper from '../src/utilities/files-helper';
|
||||||
import { getWorkflowAnnotationKeyLabel, getWorkflowAnnotationsJson } from '../src/constants';
|
import { getWorkflowAnnotationKeyLabel, getWorkflowAnnotationsJson } from '../src/constants';
|
||||||
import * as inputParam from '../src/input-parameters';
|
import * as inputParam from '../src/input-parameters';
|
||||||
|
|
||||||
@@ -26,7 +26,6 @@ const inputParamMock = mocked(inputParam, true);
|
|||||||
|
|
||||||
const toolCacheMock = mocked(toolCache, true);
|
const toolCacheMock = mocked(toolCache, true);
|
||||||
const fileUtility = mocked(fs, true);
|
const fileUtility = mocked(fs, true);
|
||||||
const globMock = mocked(glob, true);
|
|
||||||
|
|
||||||
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
|
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
|
||||||
|
|
||||||
@@ -39,7 +38,7 @@ const getAllPodsMock = {
|
|||||||
|
|
||||||
const getNamespaceMock = {
|
const getNamespaceMock = {
|
||||||
'code': 0,
|
'code': 0,
|
||||||
'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"githubWorkflow_c11401b9d232942bac19cbc5bc32b42d": "{\'run\': \'202489005\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflow1\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202489005\',\'commit\': \'currentCommit\',\'lastSuccessRunCommit\': \'lastCommit\',\'branch\': \'refs/heads/branch-rename\',\'deployTimestamp\': \'1597062957973\',\'provider\': \'GitHub\'}","githubWorkflow_21fd7a597282ca5adc05ba99018b3706": "{\'run\': \'202504411\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflowMaster\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202504411\',\'commit\': \'currentCommit1\',\'lastSuccessRunCommit\': \'NA\',\'branch\': \'refs/heads/master\',\'deployTimestamp\': \'1597063919873\',\'provider\': \'GitHub\'}"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}'
|
'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"githubWorkflow_c11401b9d232942bac19cbc5bc32b42d": "{\'run\': \'202489005\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflow1\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202489005\',\'commit\': \'currentCommit\',\'lastSuccessRunCommit\': \'lastCommit\',\'branch\': \'refs/heads/branch-rename\',\'deployTimestamp\': \'1597062957973\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}","githubWorkflow_21fd7a597282ca5adc05ba99018b3706": "{\'run\': \'202504411\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflowMaster\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202504411\',\'commit\': \'currentCommit1\',\'lastSuccessRunCommit\': \'NA\',\'branch\': \'refs/heads/master\',\'deployTimestamp\': \'1597063919873\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}'
|
||||||
};
|
};
|
||||||
|
|
||||||
const getWorkflowsUrlResponse = {
|
const getWorkflowsUrlResponse = {
|
||||||
@@ -80,7 +79,6 @@ const resources: Resource[] = [{ type: "Deployment", name: "AppName" }];
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8');
|
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8');
|
||||||
jest.spyOn(Date, 'now').mockImplementation(() => 1234561234567);
|
jest.spyOn(Date, 'now').mockImplementation(() => 1234561234567);
|
||||||
globMock.hasMagic = jest.fn().mockReturnValue(false);
|
|
||||||
|
|
||||||
process.env["KUBECONFIG"] = 'kubeConfig';
|
process.env["KUBECONFIG"] = 'kubeConfig';
|
||||||
process.env['GITHUB_RUN_ID'] = '12345';
|
process.env['GITHUB_RUN_ID'] = '12345';
|
||||||
@@ -112,7 +110,7 @@ test("setKubectlPath() - install a latest version", async () => {
|
|||||||
const kubectlVersion = 'latest'
|
const kubectlVersion = 'latest'
|
||||||
//Mocks
|
//Mocks
|
||||||
coreMock.getInput = jest.fn().mockReturnValue(kubectlVersion);
|
coreMock.getInput = jest.fn().mockReturnValue(kubectlVersion);
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => "");
|
jest.spyOn(fs, 'readFileSync').mockImplementation(() => "");
|
||||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||||
toolCacheMock.downloadTool = jest.fn().mockResolvedValue('');
|
toolCacheMock.downloadTool = jest.fn().mockResolvedValue('');
|
||||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||||
@@ -122,7 +120,7 @@ test("setKubectlPath() - install a latest version", async () => {
|
|||||||
await expect(action.run()).resolves.not.toThrow();
|
await expect(action.run()).resolves.not.toThrow();
|
||||||
expect(toolCacheMock.find).toBeCalledWith('kubectl', kubectlVersion);
|
expect(toolCacheMock.find).toBeCalledWith('kubectl', kubectlVersion);
|
||||||
expect(toolCacheMock.downloadTool).toBeCalledWith(stableVersionUrl);
|
expect(toolCacheMock.downloadTool).toBeCalledWith(stableVersionUrl);
|
||||||
readFileSpy.mockRestore();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("setKubectlPath() - kubectl version already avilable", async () => {
|
test("setKubectlPath() - kubectl version already avilable", async () => {
|
||||||
@@ -254,7 +252,6 @@ test("deployment - deploy() - Invokes with manifestfiles", async () => {
|
|||||||
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
||||||
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
|
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
|
||||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||||
inputParamMock.containers = ['testcr.azurecr.io/testapp:2.0'];
|
|
||||||
|
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
||||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
||||||
@@ -263,8 +260,6 @@ test("deployment - deploy() - Invokes with manifestfiles", async () => {
|
|||||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||||
expect(readFileSpy).toBeCalledWith("manifests/deployment.yaml");
|
expect(readFileSpy).toBeCalledWith("manifests/deployment.yaml");
|
||||||
expect(kubeCtl.getResource).toBeCalledWith("ingress", "AppName");
|
expect(kubeCtl.getResource).toBeCalledWith("ingress", "AppName");
|
||||||
readFileSpy.mockRestore();
|
|
||||||
inputParamMock.containers = [];
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("deployment - deploy() - deploy force flag on", async () => {
|
test("deployment - deploy() - deploy force flag on", async () => {
|
||||||
@@ -298,15 +293,16 @@ test("deployment - deploy() - deploy force flag on", async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("deployment - deploy() - Annotate & label resources", async () => {
|
test("deployment - deploy() - Annotate & label resources", async () => {
|
||||||
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('currentCommit', '.github/workflows/workflow.yml');
|
let deploymentConfig = { manifestFilePaths :['manifests/deployment.yaml'], helmChartFilePaths : [], dockerfilePaths :{}} ;
|
||||||
|
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('currentCommit', '.github/workflows/workflow.yml', deploymentConfig);
|
||||||
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
||||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||||
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
||||||
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
||||||
const fsMock = (mocked(fs, true));
|
const fileHelperMock = mocked(fileHelper, true);
|
||||||
fsMock.writeFileSync =jest.fn().mockReturnValue("");
|
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue(["~/Deployment_testapp_currentTimestamp"]);
|
||||||
jest.spyOn(utility, 'getWorkflowFilePath').mockImplementation(() => Promise.resolve(process.env.GITHUB_WORKFLOW));
|
jest.spyOn(utility, 'getWorkflowFilePath').mockImplementation(() => Promise.resolve(process.env.GITHUB_WORKFLOW));
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
jest.spyOn(utility, 'getDeploymentConfig').mockImplementation(()=> Promise.resolve(deploymentConfig));
|
||||||
|
|
||||||
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue("");
|
kubeCtl.apply = jest.fn().mockReturnValue("");
|
||||||
@@ -319,24 +315,23 @@ test("deployment - deploy() - Annotate & label resources", async () => {
|
|||||||
//Invoke and assert
|
//Invoke and assert
|
||||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||||
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
||||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["manifests/deployment.yaml"], annotationKeyValStr);
|
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"], annotationKeyValStr);
|
||||||
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
||||||
expect(kubeCtl.labelFiles).toBeCalledWith(["manifests/deployment.yaml"],
|
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"],
|
||||||
[`workflowFriendlyName=workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
[`workflowFriendlyName=workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
||||||
readFileSpy.mockRestore();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("deployment - deploy() - Annotate & label resources for a new workflow", async () => {
|
test("deployment - deploy() - Annotate & label resources for a new workflow", async () => {
|
||||||
process.env.GITHUB_WORKFLOW = '.github/workflows/New Workflow.yml';
|
process.env.GITHUB_WORKFLOW = '.github/workflows/NewWorkflow.yml';
|
||||||
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('NA', '.github/workflows/New Workflow.yml');
|
let deploymentConfig = { manifestFilePaths :['manifests/deployment.yaml'], helmChartFilePaths : [], dockerfilePaths :{}} ;
|
||||||
|
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('NA', '.github/workflows/NewWorkflow.yml', deploymentConfig);
|
||||||
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
||||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||||
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
||||||
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
||||||
const fsMock = (mocked(fs, true));
|
const fileHelperMock = mocked(fileHelper, true);
|
||||||
fsMock.writeFileSync =jest.fn().mockReturnValue("");
|
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue(["~/Deployment_testapp_currentTimestamp"]);
|
||||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
||||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
|
||||||
|
|
||||||
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
||||||
kubeCtl.apply = jest.fn().mockReturnValue("");
|
kubeCtl.apply = jest.fn().mockReturnValue("");
|
||||||
@@ -349,11 +344,10 @@ test("deployment - deploy() - Annotate & label resources for a new workflow", as
|
|||||||
//Invoke and assert
|
//Invoke and assert
|
||||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||||
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
||||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["manifests/deployment.yaml"], annotationKeyValStr);
|
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"], annotationKeyValStr);
|
||||||
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
||||||
expect(kubeCtl.labelFiles).toBeCalledWith(["manifests/deployment.yaml"],
|
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"],
|
||||||
[`workflowFriendlyName=New_Workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
[`workflowFriendlyName=NewWorkflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
||||||
readFileSpy.mockRestore();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("deployment - deploy() - Annotate resources failed", async () => {
|
test("deployment - deploy() - Annotate resources failed", async () => {
|
||||||
@@ -381,7 +375,7 @@ test("deployment - deploy() - Annotate resources failed", async () => {
|
|||||||
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
|
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
|
||||||
//Invoke and assert
|
//Invoke and assert
|
||||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||||
expect(consoleOutputSpy).toHaveBeenNthCalledWith(1, '::warning::kubectl annotate failed' + os.EOL)
|
expect(consoleOutputSpy).toHaveBeenNthCalledWith(2, '::warning::kubectl annotate failed' + os.EOL)
|
||||||
});
|
});
|
||||||
|
|
||||||
test("utility - getWorkflowFilePath() - Get workflow file path under API failure", async () => {
|
test("utility - getWorkflowFilePath() - Get workflow file path under API failure", async () => {
|
||||||
|
|||||||
+2
-10
@@ -19,17 +19,9 @@ inputs:
|
|||||||
description: 'Version of kubectl. Installs a specific version of kubectl binary'
|
description: 'Version of kubectl. Installs a specific version of kubectl binary'
|
||||||
required: false
|
required: false
|
||||||
strategy:
|
strategy:
|
||||||
description: 'Deployment strategy to be used. Allowed values are none, canary and blue-green'
|
description: 'Deployment strategy to be used. Allowed values are none, canary'
|
||||||
required: false
|
required: false
|
||||||
default: 'none'
|
default: 'none'
|
||||||
route-method:
|
|
||||||
description: 'Route based on service, ingress or SMI for blue-green strategy'
|
|
||||||
required: false
|
|
||||||
default: 'service'
|
|
||||||
version-switch-buffer:
|
|
||||||
description: 'Indicates the buffer time in minutes before the switch is made to the green version (max is 300 min ie. 5hrs)'
|
|
||||||
required: false
|
|
||||||
default: 0
|
|
||||||
traffic-split-method:
|
traffic-split-method:
|
||||||
description: "Traffic split method to be used. Allowed values are pod, smi"
|
description: "Traffic split method to be used. Allowed values are pod, smi"
|
||||||
required: false
|
required: false
|
||||||
@@ -50,7 +42,7 @@ inputs:
|
|||||||
required: true
|
required: true
|
||||||
default: 'deploy'
|
default: 'deploy'
|
||||||
force:
|
force:
|
||||||
description: 'Deploy when a previous deployment already exists. If true then --force argument is added to the apply command'
|
description: 'Deploy when a previous deployment already exists. If true then --force argument is added to the apply command.'
|
||||||
required: false
|
required: false
|
||||||
default: false
|
default: false
|
||||||
token:
|
token:
|
||||||
|
|||||||
+5
-60
@@ -16,34 +16,14 @@ const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-dep
|
|||||||
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
||||||
const utils = require("../utilities/manifest-utilities");
|
const utils = require("../utilities/manifest-utilities");
|
||||||
const TaskInputParameters = require("../input-parameters");
|
const TaskInputParameters = require("../input-parameters");
|
||||||
const manifest_utilities_1 = require("../utilities/manifest-utilities");
|
|
||||||
const KubernetesObjectUtility = require("../utilities/resource-object-utility");
|
|
||||||
const models = require("../constants");
|
|
||||||
const KubernetesManifestUtility = require("../utilities/manifest-stability-utility");
|
|
||||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
|
||||||
const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper");
|
|
||||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
|
||||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
|
||||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
|
||||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||||
function promote() {
|
function promote(ignoreSslErrors) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, ignoreSslErrors);
|
||||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
if (!canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||||
yield promoteCanary(kubectl);
|
core.debug('Strategy is not canary deployment. Invalid request.');
|
||||||
}
|
|
||||||
else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) {
|
|
||||||
yield promoteBlueGreen(kubectl);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
|
||||||
throw ('InvalidPromotetActionDeploymentStrategy');
|
throw ('InvalidPromotetActionDeploymentStrategy');
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.promote = promote;
|
|
||||||
function promoteCanary(kubectl) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let includeServices = false;
|
let includeServices = false;
|
||||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||||
includeServices = true;
|
includeServices = true;
|
||||||
@@ -69,39 +49,4 @@ function promoteCanary(kubectl) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function promoteBlueGreen(kubectl) {
|
exports.promote = promote;
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// updated container images and pull secrets
|
|
||||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests);
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles);
|
|
||||||
core.debug('deleting old deployment and making new ones');
|
|
||||||
let result;
|
|
||||||
if (blue_green_helper_2.isIngressRoute()) {
|
|
||||||
result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects);
|
|
||||||
}
|
|
||||||
else if (blue_green_helper_2.isSMIRoute()) {
|
|
||||||
result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects);
|
|
||||||
}
|
|
||||||
// checking stability of newly created deployments
|
|
||||||
const deployedManifestFiles = result.newFilePaths;
|
|
||||||
const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service]));
|
|
||||||
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
|
|
||||||
core.debug('routing to new deployments');
|
|
||||||
if (blue_green_helper_2.isIngressRoute()) {
|
|
||||||
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
|
|
||||||
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
|
|
||||||
}
|
|
||||||
else if (blue_green_helper_2.isSMIRoute()) {
|
|
||||||
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
|
||||||
smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
+6
-35
@@ -16,29 +16,13 @@ const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-can
|
|||||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||||
const utils = require("../utilities/manifest-utilities");
|
const utils = require("../utilities/manifest-utilities");
|
||||||
const TaskInputParameters = require("../input-parameters");
|
const TaskInputParameters = require("../input-parameters");
|
||||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
function reject(ignoreSslErrors) {
|
||||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
|
||||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
|
||||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
|
||||||
const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper");
|
|
||||||
function reject() {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, ignoreSslErrors);
|
||||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
if (!canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||||
yield rejectCanary(kubectl);
|
core.debug('Strategy is not canary deployment. Invalid request.');
|
||||||
|
throw ('InvalidRejectActionDeploymentStrategy');
|
||||||
}
|
}
|
||||||
else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
|
||||||
yield rejectBlueGreen(kubectl);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
|
||||||
throw ('InvalidDeletetActionDeploymentStrategy');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.reject = reject;
|
|
||||||
function rejectCanary(kubectl) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let includeServices = false;
|
let includeServices = false;
|
||||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||||
core.debug('Reject deployment with SMI canary strategy');
|
core.debug('Reject deployment with SMI canary strategy');
|
||||||
@@ -49,17 +33,4 @@ function rejectCanary(kubectl) {
|
|||||||
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function rejectBlueGreen(kubectl) {
|
exports.reject = reject;
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests);
|
|
||||||
if (blue_green_helper_1.isIngressRoute()) {
|
|
||||||
yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles);
|
|
||||||
}
|
|
||||||
else if (blue_green_helper_1.isSMIRoute()) {
|
|
||||||
yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
+18
-15
@@ -25,21 +25,24 @@ ServiceTypes.clusterIP = 'ClusterIP';
|
|||||||
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
|
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
|
||||||
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||||
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
|
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
|
||||||
function getWorkflowAnnotationsJson(lastSuccessRunSha, workflowFilePath) {
|
function getWorkflowAnnotationsJson(lastSuccessRunSha, workflowFilePath, deploymentConfig) {
|
||||||
return `{`
|
let annotationObject = {};
|
||||||
+ `'run': '${process.env.GITHUB_RUN_ID}',`
|
annotationObject["run"] = process.env.GITHUB_RUN_ID;
|
||||||
+ `'repository': '${process.env.GITHUB_REPOSITORY}',`
|
annotationObject["repository"] = process.env.GITHUB_REPOSITORY;
|
||||||
+ `'workflow': '${process.env.GITHUB_WORKFLOW}',`
|
annotationObject["workflow"] = process.env.GITHUB_WORKFLOW;
|
||||||
+ `'workflowFileName': '${workflowFilePath.replace(".github/workflows/", "")}',`
|
annotationObject["workflowFileName"] = workflowFilePath.replace(".github/workflows/", "");
|
||||||
+ `'jobName': '${process.env.GITHUB_JOB}',`
|
annotationObject["jobName"] = process.env.GITHUB_JOB;
|
||||||
+ `'createdBy': '${process.env.GITHUB_ACTOR}',`
|
annotationObject["createdBy"] = process.env.GITHUB_ACTOR;
|
||||||
+ `'runUri': 'https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}',`
|
annotationObject["runUri"] = `https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
|
||||||
+ `'commit': '${process.env.GITHUB_SHA}',`
|
annotationObject["commit"] = process.env.GITHUB_SHA;
|
||||||
+ `'lastSuccessRunCommit': '${lastSuccessRunSha}',`
|
annotationObject["lastSuccessRunCommit"] = lastSuccessRunSha;
|
||||||
+ `'branch': '${process.env.GITHUB_REF}',`
|
annotationObject["branch"] = process.env.GITHUB_REF;
|
||||||
+ `'deployTimestamp': '${Date.now()}',`
|
annotationObject["deployTimestamp"] = Date.now();
|
||||||
+ `'provider': 'GitHub'`
|
annotationObject["dockerfilePaths"] = deploymentConfig.dockerfilePaths;
|
||||||
+ `}`;
|
annotationObject["manifestsPaths"] = deploymentConfig.manifestFilePaths;
|
||||||
|
annotationObject["helmChartPaths"] = deploymentConfig.helmChartFilePaths;
|
||||||
|
annotationObject["provider"] = "GitHub";
|
||||||
|
return JSON.stringify(annotationObject);
|
||||||
}
|
}
|
||||||
exports.getWorkflowAnnotationsJson = getWorkflowAnnotationsJson;
|
exports.getWorkflowAnnotationsJson = getWorkflowAnnotationsJson;
|
||||||
function getWorkflowAnnotationKeyLabel(workflowFilePath) {
|
function getWorkflowAnnotationKeyLabel(workflowFilePath) {
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.DockerExec = void 0;
|
||||||
|
const tool_runner_1 = require("./utilities/tool-runner");
|
||||||
|
class DockerExec {
|
||||||
|
constructor(dockerPath) {
|
||||||
|
this.dockerPath = dockerPath;
|
||||||
|
}
|
||||||
|
;
|
||||||
|
pull(image, args, silent) {
|
||||||
|
args = ['pull', image, ...args];
|
||||||
|
let result = this.execute(args, silent);
|
||||||
|
if (result.stderr != '' && result.code != 0) {
|
||||||
|
throw new Error(`docker images pull failed with: ${result.error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inspect(image, args, silent) {
|
||||||
|
args = ['inspect', image, ...args];
|
||||||
|
let result = this.execute(args, silent);
|
||||||
|
if (result.stderr != '' && result.code != 0) {
|
||||||
|
throw new Error(`docker inspect call failed with: ${result.error}`);
|
||||||
|
}
|
||||||
|
return result.stdout;
|
||||||
|
}
|
||||||
|
execute(args, silent) {
|
||||||
|
const command = new tool_runner_1.ToolRunner(this.dockerPath);
|
||||||
|
command.arg(args);
|
||||||
|
return command.execSync({ silent: !!silent });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.DockerExec = DockerExec;
|
||||||
+3
-18
@@ -1,18 +1,14 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.githubToken = exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
|
exports.githubToken = exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
|
||||||
const core = require("@actions/core");
|
const core = require("@actions/core");
|
||||||
const utility_1 = require("./utilities/utility");
|
|
||||||
exports.namespace = core.getInput('namespace');
|
exports.namespace = core.getInput('namespace');
|
||||||
exports.containers = core.getInput('images').split('\n').filter(image => image.trim().length > 0);
|
exports.containers = core.getInput('images').split('\n');
|
||||||
;
|
|
||||||
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
|
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
|
||||||
exports.manifests = utility_1.resolveGlobPatterns(core.getInput('manifests'));
|
exports.manifests = core.getInput('manifests').split('\n');
|
||||||
exports.canaryPercentage = core.getInput('percentage');
|
exports.canaryPercentage = core.getInput('percentage');
|
||||||
exports.deploymentStrategy = core.getInput('strategy');
|
exports.deploymentStrategy = core.getInput('strategy');
|
||||||
exports.trafficSplitMethod = core.getInput('traffic-split-method');
|
exports.trafficSplitMethod = core.getInput('traffic-split-method');
|
||||||
exports.routeMethod = core.getInput('route-method');
|
|
||||||
exports.versionSwitchBuffer = core.getInput('version-switch-buffer');
|
|
||||||
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
|
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
|
||||||
exports.args = core.getInput('arguments');
|
exports.args = core.getInput('arguments');
|
||||||
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
|
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
|
||||||
@@ -46,14 +42,3 @@ catch (ex) {
|
|||||||
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
|
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
const pe = parseInt(exports.versionSwitchBuffer);
|
|
||||||
if (pe < 0 || pe > 300) {
|
|
||||||
core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (ex) {
|
|
||||||
core.setFailed("Enter a valid 'version-switch-buffer' integer value");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|||||||
+4
-4
@@ -53,7 +53,7 @@ function installKubectl(version) {
|
|||||||
}
|
}
|
||||||
function checkClusterContext() {
|
function checkClusterContext() {
|
||||||
if (!process.env["KUBECONFIG"]) {
|
if (!process.env["KUBECONFIG"]) {
|
||||||
throw new Error('Cluster context not set. Use k8ssetcontext action to set cluster context');
|
core.warning('KUBECONFIG env is not explicitly set. Ensure cluster context is set by using k8s-set-context / aks-set-context action.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function run() {
|
function run() {
|
||||||
@@ -70,17 +70,17 @@ function run() {
|
|||||||
namespace = 'default';
|
namespace = 'default';
|
||||||
}
|
}
|
||||||
let action = core.getInput('action');
|
let action = core.getInput('action');
|
||||||
|
let manifests = manifestsInput.split('\n');
|
||||||
if (action === 'deploy') {
|
if (action === 'deploy') {
|
||||||
let strategy = core.getInput('strategy');
|
let strategy = core.getInput('strategy');
|
||||||
console.log("strategy: ", strategy);
|
console.log("strategy: ", strategy);
|
||||||
let manifests = utility_1.resolveGlobPatterns(manifestsInput);
|
|
||||||
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
|
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
|
||||||
}
|
}
|
||||||
else if (action === 'promote') {
|
else if (action === 'promote') {
|
||||||
yield promote_1.promote();
|
yield promote_1.promote(true);
|
||||||
}
|
}
|
||||||
else if (action === 'reject') {
|
else if (action === 'reject') {
|
||||||
yield reject_1.reject();
|
yield reject_1.reject(true);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
|
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
|
||||||
|
|||||||
@@ -9,16 +9,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
|
exports.isWorkloadEntity = exports.updateImagePullSecrets = exports.updateContainerImagesInManifestFiles = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
|
||||||
const core = require("@actions/core");
|
const core = require("@actions/core");
|
||||||
const fs = require("fs");
|
|
||||||
const yaml = require("js-yaml");
|
|
||||||
const kubectlutility = require("./kubectl-util");
|
const kubectlutility = require("./kubectl-util");
|
||||||
const io = require("@actions/io");
|
const io = require("@actions/io");
|
||||||
const utility_1 = require("./utility");
|
const utility_1 = require("./utility");
|
||||||
const fileHelper = require("./files-helper");
|
|
||||||
const KubernetesObjectUtility = require("./resource-object-utility");
|
|
||||||
const TaskInputParameters = require("../input-parameters");
|
|
||||||
function getManifestFiles(manifestFilePaths) {
|
function getManifestFiles(manifestFilePaths) {
|
||||||
if (!manifestFilePaths) {
|
if (!manifestFilePaths) {
|
||||||
core.debug('file input is not present');
|
core.debug('file input is not present');
|
||||||
@@ -72,6 +67,30 @@ exports.getDeleteCmdArgs = getDeleteCmdArgs;
|
|||||||
This substituteImageNameInSpecFile function would return
|
This substituteImageNameInSpecFile function would return
|
||||||
return Value: `image: "example/example-image:identifiertag"`
|
return Value: `image: "example/example-image:identifiertag"`
|
||||||
*/
|
*/
|
||||||
|
function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) {
|
||||||
|
if (currentString.indexOf(imageName) < 0) {
|
||||||
|
core.debug(`No occurence of replacement token: ${imageName} found`);
|
||||||
|
return currentString;
|
||||||
|
}
|
||||||
|
return currentString.split('\n').reduce((acc, line) => {
|
||||||
|
const imageKeyword = line.match(/^ *image:/);
|
||||||
|
if (imageKeyword) {
|
||||||
|
let [currentImageName, currentImageTag] = line
|
||||||
|
.substring(imageKeyword[0].length) // consume the line from keyword onwards
|
||||||
|
.trim()
|
||||||
|
.replace(/[',"]/g, '') // replace allowed quotes with nothing
|
||||||
|
.split(':');
|
||||||
|
if (!currentImageTag && currentImageName.indexOf(' ') > 0) {
|
||||||
|
currentImageName = currentImageName.split(' ')[0]; // Stripping off comments
|
||||||
|
}
|
||||||
|
if (currentImageName === imageName) {
|
||||||
|
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return acc + line + '\n';
|
||||||
|
}, '');
|
||||||
|
}
|
||||||
|
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
|
||||||
function createInlineArray(str) {
|
function createInlineArray(str) {
|
||||||
if (typeof str === 'string') {
|
if (typeof str === 'string') {
|
||||||
return str;
|
return str;
|
||||||
@@ -170,6 +189,21 @@ function substituteImageNameInSpecContent(currentString, imageName, imageNameWit
|
|||||||
return acc + line + '\n';
|
return acc + line + '\n';
|
||||||
}, '');
|
}, '');
|
||||||
}
|
}
|
||||||
|
function updateContainerImagesInManifestFiles(contents, containers) {
|
||||||
|
if (!!containers && containers.length > 0) {
|
||||||
|
containers.forEach((container) => {
|
||||||
|
let imageName = container.split(':')[0];
|
||||||
|
if (imageName.indexOf('@') > 0) {
|
||||||
|
imageName = imageName.split('@')[0];
|
||||||
|
}
|
||||||
|
if (contents.indexOf(imageName) > 0) {
|
||||||
|
contents = substituteImageNameInSpecContent(contents, imageName, container);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return contents;
|
||||||
|
}
|
||||||
|
exports.updateContainerImagesInManifestFiles = updateContainerImagesInManifestFiles;
|
||||||
function updateImagePullSecrets(inputObject, newImagePullSecrets) {
|
function updateImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||||
return;
|
return;
|
||||||
@@ -189,54 +223,6 @@ function updateImagePullSecrets(inputObject, newImagePullSecrets) {
|
|||||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||||
}
|
}
|
||||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||||
function updateResourceObjects(filePaths, imagePullSecrets, containers) {
|
|
||||||
if ((!!imagePullSecrets && imagePullSecrets.length > 0) || (!!containers && containers.length > 0)) {
|
|
||||||
let newObjectsList = [];
|
|
||||||
filePaths.forEach((filePath) => {
|
|
||||||
const fileContents = fs.readFileSync(filePath).toString();
|
|
||||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
|
||||||
if (!!inputObject && !!inputObject.kind) {
|
|
||||||
const kind = inputObject.kind;
|
|
||||||
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
|
|
||||||
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
|
|
||||||
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
|
|
||||||
}
|
|
||||||
if (!!containers && containers.length > 0) {
|
|
||||||
KubernetesObjectUtility.substituteImageNameInSpecFile(inputObject, containers);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (utility_1.isEqual(kind, 'list', true)) {
|
|
||||||
let items = inputObject.items;
|
|
||||||
if (items.length > 0) {
|
|
||||||
items.forEach((item) => {
|
|
||||||
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
|
|
||||||
KubernetesObjectUtility.updateImagePullSecrets(item, imagePullSecrets, false);
|
|
||||||
}
|
|
||||||
if (!!containers && containers.length > 0) {
|
|
||||||
KubernetesObjectUtility.substituteImageNameInSpecFile(item, containers);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
newObjectsList.push(inputObject);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
core.debug('New K8s objects after adding imagePullSecrets and updating container images are :' + JSON.stringify(newObjectsList));
|
|
||||||
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
return newFilePaths;
|
|
||||||
}
|
|
||||||
return filePaths;
|
|
||||||
}
|
|
||||||
function getUpdatedManifestFiles(manifestFilePaths) {
|
|
||||||
let inputManifestFiles = getManifestFiles(manifestFilePaths);
|
|
||||||
if (!inputManifestFiles || inputManifestFiles.length === 0) {
|
|
||||||
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
|
|
||||||
}
|
|
||||||
inputManifestFiles = updateResourceObjects(inputManifestFiles, TaskInputParameters.imagePullSecrets, TaskInputParameters.containers);
|
|
||||||
return inputManifestFiles;
|
|
||||||
}
|
|
||||||
exports.getUpdatedManifestFiles = getUpdatedManifestFiles;
|
|
||||||
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||||
function isWorkloadEntity(kind) {
|
function isWorkloadEntity(kind) {
|
||||||
if (!kind) {
|
if (!kind) {
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.substituteImageNameInSpecFile = exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
|
exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImageDetails = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const core = require("@actions/core");
|
const core = require("@actions/core");
|
||||||
const yaml = require("js-yaml");
|
const yaml = require("js-yaml");
|
||||||
const constants_1 = require("../constants");
|
const constants_1 = require("../constants");
|
||||||
const string_comparison_1 = require("./string-comparison");
|
const string_comparison_1 = require("./string-comparison");
|
||||||
const INGRESS = "Ingress";
|
|
||||||
function isDeploymentEntity(kind) {
|
function isDeploymentEntity(kind) {
|
||||||
if (!kind) {
|
if (!kind) {
|
||||||
throw ('ResourceKindNotDefined');
|
throw ('ResourceKindNotDefined');
|
||||||
@@ -32,13 +31,6 @@ function isServiceEntity(kind) {
|
|||||||
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
exports.isServiceEntity = isServiceEntity;
|
exports.isServiceEntity = isServiceEntity;
|
||||||
function isIngressEntity(kind) {
|
|
||||||
if (!kind) {
|
|
||||||
throw ('ResourceKindNotDefined');
|
|
||||||
}
|
|
||||||
return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
|
||||||
}
|
|
||||||
exports.isIngressEntity = isIngressEntity;
|
|
||||||
function getReplicaCount(inputObject) {
|
function getReplicaCount(inputObject) {
|
||||||
if (!inputObject) {
|
if (!inputObject) {
|
||||||
throw ('NullInputObject');
|
throw ('NullInputObject');
|
||||||
@@ -121,6 +113,61 @@ function updateImagePullSecrets(inputObject, newImagePullSecrets, override) {
|
|||||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||||
}
|
}
|
||||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||||
|
function updateImageDetails(inputObject, containers) {
|
||||||
|
if (!inputObject || !inputObject.spec || !containers) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||||
|
if (inputObject.spec.template.spec.containers) {
|
||||||
|
updateContainers(inputObject.spec.template.spec.containers, containers);
|
||||||
|
}
|
||||||
|
if (inputObject.spec.template.spec.initContainers) {
|
||||||
|
updateContainers(inputObject.spec.template.spec.initContainers, containers);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (inputObject.spec.jobTemplate && inputObject.spec.jobTemplate.spec && inputObject.spec.jobTemplate.spec.template && inputObject.spec.jobTemplate.spec.template.spec) {
|
||||||
|
if (inputObject.spec.jobTemplate.spec.template.spec.containers) {
|
||||||
|
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.containers, containers);
|
||||||
|
}
|
||||||
|
if (inputObject.spec.jobTemplate.spec.template.spec.initContainers) {
|
||||||
|
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.initContainers, containers);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (inputObject.spec.containers) {
|
||||||
|
updateContainers(inputObject.spec.containers, containers);
|
||||||
|
}
|
||||||
|
if (inputObject.spec.initContainers) {
|
||||||
|
updateContainers(inputObject.spec.initContainers, containers);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.updateImageDetails = updateImageDetails;
|
||||||
|
function updateContainers(containers, images) {
|
||||||
|
if (!containers || containers.length === 0) {
|
||||||
|
return containers;
|
||||||
|
}
|
||||||
|
containers.forEach((container) => {
|
||||||
|
const imageName = extractImageName(container.image.trim());
|
||||||
|
images.forEach(image => {
|
||||||
|
if (extractImageName(image) === imageName) {
|
||||||
|
container.image = image;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function extractImageName(imageName) {
|
||||||
|
let img = '';
|
||||||
|
if (imageName.indexOf('/') > 0) {
|
||||||
|
const registry = imageName.substring(0, imageName.indexOf('/'));
|
||||||
|
const imgName = imageName.substring(imageName.indexOf('/') + 1).split(':')[0];
|
||||||
|
img = `${registry}/${imgName}`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
img = imageName.split(':')[0];
|
||||||
|
}
|
||||||
|
return img;
|
||||||
|
}
|
||||||
function updateSpecLabels(inputObject, newLabels, override) {
|
function updateSpecLabels(inputObject, newLabels, override) {
|
||||||
if (!inputObject) {
|
if (!inputObject) {
|
||||||
throw ('NullInputObject');
|
throw ('NullInputObject');
|
||||||
@@ -195,61 +242,6 @@ function getResources(filePaths, filterResourceTypes) {
|
|||||||
return resources;
|
return resources;
|
||||||
}
|
}
|
||||||
exports.getResources = getResources;
|
exports.getResources = getResources;
|
||||||
function substituteImageNameInSpecFile(inputObject, containers) {
|
|
||||||
if (!inputObject || !inputObject.spec || !containers) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (inputObject.spec.template && !!inputObject.spec.template.spec) {
|
|
||||||
if (inputObject.spec.template.spec.containers) {
|
|
||||||
updateContainers(inputObject.spec.template.spec.containers, containers);
|
|
||||||
}
|
|
||||||
if (inputObject.spec.template.spec.initContainers) {
|
|
||||||
updateContainers(inputObject.spec.template.spec.initContainers, containers);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (inputObject.spec.jobTemplate && inputObject.spec.jobTemplate.spec && inputObject.spec.jobTemplate.spec.template && inputObject.spec.jobTemplate.spec.template.spec) {
|
|
||||||
if (inputObject.spec.jobTemplate.spec.template.spec.containers) {
|
|
||||||
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.containers, containers);
|
|
||||||
}
|
|
||||||
if (inputObject.spec.jobTemplate.spec.template.spec.initContainers) {
|
|
||||||
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.initContainers, containers);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (inputObject.spec.containers) {
|
|
||||||
updateContainers(inputObject.spec.containers, containers);
|
|
||||||
}
|
|
||||||
if (inputObject.spec.initContainers) {
|
|
||||||
updateContainers(inputObject.spec.initContainers, containers);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
|
|
||||||
function updateContainers(inputContainers, images) {
|
|
||||||
if (!inputContainers || inputContainers.length === 0) {
|
|
||||||
return inputContainers;
|
|
||||||
}
|
|
||||||
inputContainers.forEach((inputContainer) => {
|
|
||||||
const imageName = extractImageName(inputContainer.image.trim());
|
|
||||||
images.forEach(image => {
|
|
||||||
if (extractImageName(image) === imageName) {
|
|
||||||
inputContainer.image = image;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function extractImageName(imageName) {
|
|
||||||
let img = '';
|
|
||||||
if (imageName.indexOf('/') > 0) {
|
|
||||||
const registry = imageName.substring(0, imageName.indexOf('/'));
|
|
||||||
const imgName = imageName.substring(imageName.indexOf('/') + 1).split(':')[0];
|
|
||||||
img = `${registry}/${imgName}`;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
img = imageName.split(':')[0];
|
|
||||||
}
|
|
||||||
return img;
|
|
||||||
}
|
|
||||||
function getSpecLabels(inputObject) {
|
function getSpecLabels(inputObject) {
|
||||||
if (!inputObject) {
|
if (!inputObject) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,305 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.fetchResource = exports.isServiceSelectorSubsetOfMatchLabel = exports.getServiceSelector = exports.getDeploymentMatchLabels = exports.getBlueGreenResourceName = exports.addBlueGreenLabelsAndAnnotations = exports.getNewBlueGreenObject = exports.createWorkloadsWithLabel = exports.isServiceRouted = exports.getManifestObjects = exports.getSuffix = exports.deleteObjects = exports.deleteWorkloadsAndServicesWithLabel = exports.deleteWorkloadsWithLabel = exports.routeBlueGreen = exports.isSMIRoute = exports.isIngressRoute = exports.isBlueGreenDeploymentStrategy = exports.STABLE_SUFFIX = exports.GREEN_SUFFIX = exports.BLUE_GREEN_VERSION_LABEL = exports.NONE_LABEL_VALUE = exports.GREEN_LABEL_VALUE = exports.BLUE_GREEN_DEPLOYMENT_STRATEGY = void 0;
|
|
||||||
const core = require("@actions/core");
|
|
||||||
const fs = require("fs");
|
|
||||||
const yaml = require("js-yaml");
|
|
||||||
const utility_1 = require("../utility");
|
|
||||||
const constants_1 = require("../../constants");
|
|
||||||
const fileHelper = require("../files-helper");
|
|
||||||
const helper = require("../resource-object-utility");
|
|
||||||
const TaskInputParameters = require("../../input-parameters");
|
|
||||||
const service_blue_green_helper_1 = require("./service-blue-green-helper");
|
|
||||||
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
|
|
||||||
const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
|
|
||||||
exports.BLUE_GREEN_DEPLOYMENT_STRATEGY = 'BLUE-GREEN';
|
|
||||||
exports.GREEN_LABEL_VALUE = 'green';
|
|
||||||
exports.NONE_LABEL_VALUE = 'None';
|
|
||||||
exports.BLUE_GREEN_VERSION_LABEL = 'k8s.deploy.color';
|
|
||||||
exports.GREEN_SUFFIX = '-green';
|
|
||||||
exports.STABLE_SUFFIX = '-stable';
|
|
||||||
const INGRESS_ROUTE = 'INGRESS';
|
|
||||||
const SMI_ROUTE = 'SMI';
|
|
||||||
function isBlueGreenDeploymentStrategy() {
|
|
||||||
const deploymentStrategy = TaskInputParameters.deploymentStrategy;
|
|
||||||
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.BLUE_GREEN_DEPLOYMENT_STRATEGY;
|
|
||||||
}
|
|
||||||
exports.isBlueGreenDeploymentStrategy = isBlueGreenDeploymentStrategy;
|
|
||||||
function isIngressRoute() {
|
|
||||||
const routeMethod = TaskInputParameters.routeMethod;
|
|
||||||
return routeMethod && routeMethod.toUpperCase() === INGRESS_ROUTE;
|
|
||||||
}
|
|
||||||
exports.isIngressRoute = isIngressRoute;
|
|
||||||
function isSMIRoute() {
|
|
||||||
const routeMethod = TaskInputParameters.routeMethod;
|
|
||||||
return routeMethod && routeMethod.toUpperCase() === SMI_ROUTE;
|
|
||||||
}
|
|
||||||
exports.isSMIRoute = isSMIRoute;
|
|
||||||
function routeBlueGreen(kubectl, inputManifestFiles) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// get buffer time
|
|
||||||
let bufferTime = parseInt(TaskInputParameters.versionSwitchBuffer);
|
|
||||||
//logging start of buffer time
|
|
||||||
let dateNow = new Date();
|
|
||||||
console.log(`Starting buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`);
|
|
||||||
// waiting
|
|
||||||
yield utility_1.sleep(bufferTime * 1000 * 60);
|
|
||||||
// logging end of buffer time
|
|
||||||
dateNow = new Date();
|
|
||||||
console.log(`Stopping buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`);
|
|
||||||
const manifestObjects = getManifestObjects(inputManifestFiles);
|
|
||||||
// routing to new deployments
|
|
||||||
if (isIngressRoute()) {
|
|
||||||
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
|
|
||||||
}
|
|
||||||
else if (isSMIRoute()) {
|
|
||||||
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
service_blue_green_helper_1.routeBlueGreenService(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.routeBlueGreen = routeBlueGreen;
|
|
||||||
function deleteWorkloadsWithLabel(kubectl, deleteLabel, deploymentEntityList) {
|
|
||||||
let resourcesToDelete = [];
|
|
||||||
deploymentEntityList.forEach((inputObject) => {
|
|
||||||
const name = inputObject.metadata.name;
|
|
||||||
const kind = inputObject.kind;
|
|
||||||
if (deleteLabel === exports.NONE_LABEL_VALUE) {
|
|
||||||
// if dellabel is none, deletes stable deployments
|
|
||||||
const resourceToDelete = { name: name, kind: kind };
|
|
||||||
resourcesToDelete.push(resourceToDelete);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// if dellabel is not none, then deletes new green deployments
|
|
||||||
const resourceToDelete = { name: getBlueGreenResourceName(name, exports.GREEN_SUFFIX), kind: kind };
|
|
||||||
resourcesToDelete.push(resourceToDelete);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// deletes the deployments
|
|
||||||
deleteObjects(kubectl, resourcesToDelete);
|
|
||||||
}
|
|
||||||
exports.deleteWorkloadsWithLabel = deleteWorkloadsWithLabel;
|
|
||||||
function deleteWorkloadsAndServicesWithLabel(kubectl, deleteLabel, deploymentEntityList, serviceEntityList) {
|
|
||||||
// need to delete services and deployments
|
|
||||||
const deletionEntitiesList = deploymentEntityList.concat(serviceEntityList);
|
|
||||||
let resourcesToDelete = [];
|
|
||||||
deletionEntitiesList.forEach((inputObject) => {
|
|
||||||
const name = inputObject.metadata.name;
|
|
||||||
const kind = inputObject.kind;
|
|
||||||
if (deleteLabel === exports.NONE_LABEL_VALUE) {
|
|
||||||
// if not dellabel, delete stable objects
|
|
||||||
const resourceToDelete = { name: name, kind: kind };
|
|
||||||
resourcesToDelete.push(resourceToDelete);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// else delete green labels
|
|
||||||
const resourceToDelete = { name: getBlueGreenResourceName(name, exports.GREEN_SUFFIX), kind: kind };
|
|
||||||
resourcesToDelete.push(resourceToDelete);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
deleteObjects(kubectl, resourcesToDelete);
|
|
||||||
}
|
|
||||||
exports.deleteWorkloadsAndServicesWithLabel = deleteWorkloadsAndServicesWithLabel;
|
|
||||||
function deleteObjects(kubectl, deleteList) {
|
|
||||||
// delete services and deployments
|
|
||||||
deleteList.forEach((delObject) => {
|
|
||||||
try {
|
|
||||||
const result = kubectl.delete([delObject.kind, delObject.name]);
|
|
||||||
utility_1.checkForErrors([result]);
|
|
||||||
}
|
|
||||||
catch (ex) {
|
|
||||||
// Ignore failures of delete if doesn't exist
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.deleteObjects = deleteObjects;
|
|
||||||
function getSuffix(label) {
|
|
||||||
if (label === exports.GREEN_LABEL_VALUE) {
|
|
||||||
return exports.GREEN_SUFFIX;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.getSuffix = getSuffix;
|
|
||||||
// other common functions
|
|
||||||
function getManifestObjects(filePaths) {
|
|
||||||
const deploymentEntityList = [];
|
|
||||||
const routedServiceEntityList = [];
|
|
||||||
const unroutedServiceEntityList = [];
|
|
||||||
const ingressEntityList = [];
|
|
||||||
const otherEntitiesList = [];
|
|
||||||
let serviceNameMap = new Map();
|
|
||||||
filePaths.forEach((filePath) => {
|
|
||||||
const fileContents = fs.readFileSync(filePath);
|
|
||||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
|
||||||
if (!!inputObject) {
|
|
||||||
const kind = inputObject.kind;
|
|
||||||
const name = inputObject.metadata.name;
|
|
||||||
if (helper.isDeploymentEntity(kind)) {
|
|
||||||
deploymentEntityList.push(inputObject);
|
|
||||||
}
|
|
||||||
else if (helper.isServiceEntity(kind)) {
|
|
||||||
if (isServiceRouted(inputObject, deploymentEntityList)) {
|
|
||||||
routedServiceEntityList.push(inputObject);
|
|
||||||
serviceNameMap.set(name, getBlueGreenResourceName(name, exports.GREEN_SUFFIX));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
unroutedServiceEntityList.push(inputObject);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (helper.isIngressEntity(kind)) {
|
|
||||||
ingressEntityList.push(inputObject);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
otherEntitiesList.push(inputObject);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return { serviceEntityList: routedServiceEntityList, serviceNameMap: serviceNameMap, unroutedServiceEntityList: unroutedServiceEntityList, deploymentEntityList: deploymentEntityList, ingressEntityList: ingressEntityList, otherObjects: otherEntitiesList };
|
|
||||||
}
|
|
||||||
exports.getManifestObjects = getManifestObjects;
|
|
||||||
function isServiceRouted(serviceObject, deploymentEntityList) {
|
|
||||||
let shouldBeRouted = false;
|
|
||||||
const serviceSelector = getServiceSelector(serviceObject);
|
|
||||||
if (!!serviceSelector) {
|
|
||||||
if (deploymentEntityList.some((depObject) => {
|
|
||||||
// finding if there is a deployment in the given manifests the service targets
|
|
||||||
const matchLabels = getDeploymentMatchLabels(depObject);
|
|
||||||
return (!!matchLabels && isServiceSelectorSubsetOfMatchLabel(serviceSelector, matchLabels));
|
|
||||||
})) {
|
|
||||||
shouldBeRouted = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return shouldBeRouted;
|
|
||||||
}
|
|
||||||
exports.isServiceRouted = isServiceRouted;
|
|
||||||
function createWorkloadsWithLabel(kubectl, deploymentObjectList, nextLabel) {
|
|
||||||
const newObjectsList = [];
|
|
||||||
deploymentObjectList.forEach((inputObject) => {
|
|
||||||
// creating deployment with label
|
|
||||||
const newBlueGreenObject = getNewBlueGreenObject(inputObject, nextLabel);
|
|
||||||
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
|
|
||||||
newObjectsList.push(newBlueGreenObject);
|
|
||||||
});
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
const result = kubectl.apply(manifestFiles);
|
|
||||||
return { 'result': result, 'newFilePaths': manifestFiles };
|
|
||||||
}
|
|
||||||
exports.createWorkloadsWithLabel = createWorkloadsWithLabel;
|
|
||||||
function getNewBlueGreenObject(inputObject, labelValue) {
|
|
||||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
|
||||||
// Updating name only if label is green label is given
|
|
||||||
if (labelValue === exports.GREEN_LABEL_VALUE) {
|
|
||||||
newObject.metadata.name = getBlueGreenResourceName(inputObject.metadata.name, exports.GREEN_SUFFIX);
|
|
||||||
}
|
|
||||||
// Adding labels and annotations
|
|
||||||
addBlueGreenLabelsAndAnnotations(newObject, labelValue);
|
|
||||||
return newObject;
|
|
||||||
}
|
|
||||||
exports.getNewBlueGreenObject = getNewBlueGreenObject;
|
|
||||||
function addBlueGreenLabelsAndAnnotations(inputObject, labelValue) {
|
|
||||||
//creating the k8s.deploy.color label
|
|
||||||
const newLabels = new Map();
|
|
||||||
newLabels[exports.BLUE_GREEN_VERSION_LABEL] = labelValue;
|
|
||||||
// updating object labels and selector labels
|
|
||||||
helper.updateObjectLabels(inputObject, newLabels, false);
|
|
||||||
helper.updateSelectorLabels(inputObject, newLabels, false);
|
|
||||||
// updating spec labels if it is a service
|
|
||||||
if (!helper.isServiceEntity(inputObject.kind)) {
|
|
||||||
helper.updateSpecLabels(inputObject, newLabels, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.addBlueGreenLabelsAndAnnotations = addBlueGreenLabelsAndAnnotations;
|
|
||||||
function getBlueGreenResourceName(name, suffix) {
|
|
||||||
return `${name}${suffix}`;
|
|
||||||
}
|
|
||||||
exports.getBlueGreenResourceName = getBlueGreenResourceName;
|
|
||||||
function getDeploymentMatchLabels(deploymentObject) {
|
|
||||||
if (!!deploymentObject && deploymentObject.kind.toUpperCase() == constants_1.KubernetesWorkload.pod.toUpperCase() && !!deploymentObject.metadata && !!deploymentObject.metadata.labels) {
|
|
||||||
return deploymentObject.metadata.labels;
|
|
||||||
}
|
|
||||||
else if (!!deploymentObject && deploymentObject.spec && deploymentObject.spec.selector && deploymentObject.spec.selector.matchLabels) {
|
|
||||||
return deploymentObject.spec.selector.matchLabels;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
exports.getDeploymentMatchLabels = getDeploymentMatchLabels;
|
|
||||||
function getServiceSelector(serviceObject) {
|
|
||||||
if (!!serviceObject && serviceObject.spec && serviceObject.spec.selector) {
|
|
||||||
return serviceObject.spec.selector;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
exports.getServiceSelector = getServiceSelector;
|
|
||||||
function isServiceSelectorSubsetOfMatchLabel(serviceSelector, matchLabels) {
|
|
||||||
let serviceSelectorMap = new Map();
|
|
||||||
let matchLabelsMap = new Map();
|
|
||||||
JSON.parse(JSON.stringify(serviceSelector), (key, value) => {
|
|
||||||
serviceSelectorMap.set(key, value);
|
|
||||||
});
|
|
||||||
JSON.parse(JSON.stringify(matchLabels), (key, value) => {
|
|
||||||
matchLabelsMap.set(key, value);
|
|
||||||
});
|
|
||||||
let isMatch = true;
|
|
||||||
serviceSelectorMap.forEach((value, key) => {
|
|
||||||
if (!!key && (!matchLabelsMap.has(key) || matchLabelsMap.get(key)) != value) {
|
|
||||||
isMatch = false;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return isMatch;
|
|
||||||
}
|
|
||||||
exports.isServiceSelectorSubsetOfMatchLabel = isServiceSelectorSubsetOfMatchLabel;
|
|
||||||
function fetchResource(kubectl, kind, name) {
|
|
||||||
const result = kubectl.getResource(kind, name);
|
|
||||||
if (result == null || !!result.stderr) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (!!result.stdout) {
|
|
||||||
const resource = JSON.parse(result.stdout);
|
|
||||||
try {
|
|
||||||
UnsetsClusterSpecficDetails(resource);
|
|
||||||
return resource;
|
|
||||||
}
|
|
||||||
catch (ex) {
|
|
||||||
core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
|
|
||||||
core.debug(`Exception:${ex}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
exports.fetchResource = fetchResource;
|
|
||||||
function UnsetsClusterSpecficDetails(resource) {
|
|
||||||
if (resource == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Unsets the cluster specific details in the object
|
|
||||||
if (!!resource) {
|
|
||||||
const metadata = resource.metadata;
|
|
||||||
const status = resource.status;
|
|
||||||
if (!!metadata) {
|
|
||||||
const newMetadata = {
|
|
||||||
'annotations': metadata.annotations,
|
|
||||||
'labels': metadata.labels,
|
|
||||||
'name': metadata.name
|
|
||||||
};
|
|
||||||
resource.metadata = newMetadata;
|
|
||||||
}
|
|
||||||
if (!!status) {
|
|
||||||
resource.status = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.getManifestFiles = exports.deploy = void 0;
|
exports.deploy = void 0;
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const core = require("@actions/core");
|
const core = require("@actions/core");
|
||||||
const yaml = require("js-yaml");
|
const yaml = require("js-yaml");
|
||||||
@@ -21,27 +21,21 @@ const fileHelper = require("../files-helper");
|
|||||||
const utils = require("../manifest-utilities");
|
const utils = require("../manifest-utilities");
|
||||||
const KubernetesManifestUtility = require("../manifest-stability-utility");
|
const KubernetesManifestUtility = require("../manifest-stability-utility");
|
||||||
const KubernetesConstants = require("../../constants");
|
const KubernetesConstants = require("../../constants");
|
||||||
const manifest_utilities_1 = require("../manifest-utilities");
|
const string_comparison_1 = require("./../string-comparison");
|
||||||
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
|
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
|
||||||
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
|
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
|
||||||
const utility_1 = require("../utility");
|
const utility_1 = require("../utility");
|
||||||
const blue_green_helper_1 = require("./blue-green-helper");
|
|
||||||
const service_blue_green_helper_1 = require("./service-blue-green-helper");
|
|
||||||
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
|
|
||||||
const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
|
|
||||||
function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
|
function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
// get manifest files
|
// get manifest files
|
||||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths);
|
let inputManifestFiles = getManifestFiles(manifestFilePaths);
|
||||||
|
// artifact substitution
|
||||||
|
inputManifestFiles = updateResourceObjects(inputManifestFiles, TaskInputParameters.imagePullSecrets, TaskInputParameters.containers);
|
||||||
// deployment
|
// deployment
|
||||||
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy());
|
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy));
|
||||||
// check manifest stability
|
// check manifest stability
|
||||||
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
|
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
|
||||||
yield checkManifestStability(kubectl, resourceTypes);
|
yield checkManifestStability(kubectl, resourceTypes);
|
||||||
// route blue-green deployments
|
|
||||||
if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
|
||||||
yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles);
|
|
||||||
}
|
|
||||||
// print ingress resources
|
// print ingress resources
|
||||||
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
|
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
|
||||||
ingressResources.forEach(ingressResource => {
|
ingressResources.forEach(ingressResource => {
|
||||||
@@ -66,8 +60,7 @@ function getManifestFiles(manifestFilePaths) {
|
|||||||
}
|
}
|
||||||
return files;
|
return files;
|
||||||
}
|
}
|
||||||
exports.getManifestFiles = getManifestFiles;
|
function deployManifests(files, kubectl, isCanaryDeploymentStrategy) {
|
||||||
function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) {
|
|
||||||
let result;
|
let result;
|
||||||
if (isCanaryDeploymentStrategy) {
|
if (isCanaryDeploymentStrategy) {
|
||||||
let canaryDeploymentOutput;
|
let canaryDeploymentOutput;
|
||||||
@@ -80,20 +73,6 @@ function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreen
|
|||||||
result = canaryDeploymentOutput.result;
|
result = canaryDeploymentOutput.result;
|
||||||
files = canaryDeploymentOutput.newFilePaths;
|
files = canaryDeploymentOutput.newFilePaths;
|
||||||
}
|
}
|
||||||
else if (isBlueGreenDeploymentStrategy) {
|
|
||||||
let blueGreenDeploymentOutput;
|
|
||||||
if (blue_green_helper_1.isIngressRoute()) {
|
|
||||||
blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files);
|
|
||||||
}
|
|
||||||
else if (blue_green_helper_1.isSMIRoute()) {
|
|
||||||
blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files);
|
|
||||||
}
|
|
||||||
result = blueGreenDeploymentOutput.result;
|
|
||||||
files = blueGreenDeploymentOutput.newFilePaths;
|
|
||||||
}
|
|
||||||
else {
|
else {
|
||||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||||
const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
|
const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
|
||||||
@@ -134,15 +113,16 @@ function checkManifestStability(kubectl, resources) {
|
|||||||
function annotateAndLabelResources(files, kubectl, resourceTypes, allPods) {
|
function annotateAndLabelResources(files, kubectl, resourceTypes, allPods) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const workflowFilePath = yield utility_1.getWorkflowFilePath(TaskInputParameters.githubToken);
|
const workflowFilePath = yield utility_1.getWorkflowFilePath(TaskInputParameters.githubToken);
|
||||||
|
const deploymentConfig = yield utility_1.getDeploymentConfig();
|
||||||
const annotationKeyLabel = models.getWorkflowAnnotationKeyLabel(workflowFilePath);
|
const annotationKeyLabel = models.getWorkflowAnnotationKeyLabel(workflowFilePath);
|
||||||
annotateResources(files, kubectl, resourceTypes, allPods, annotationKeyLabel, workflowFilePath);
|
annotateResources(files, kubectl, resourceTypes, allPods, annotationKeyLabel, workflowFilePath, deploymentConfig);
|
||||||
labelResources(files, kubectl, annotationKeyLabel);
|
labelResources(files, kubectl, annotationKeyLabel);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function annotateResources(files, kubectl, resourceTypes, allPods, annotationKey, workflowFilePath) {
|
function annotateResources(files, kubectl, resourceTypes, allPods, annotationKey, workflowFilePath, deploymentConfig) {
|
||||||
const annotateResults = [];
|
const annotateResults = [];
|
||||||
const lastSuccessSha = utility_1.getLastSuccessfulRunSha(kubectl, TaskInputParameters.namespace, annotationKey);
|
const lastSuccessSha = utility_1.getLastSuccessfulRunSha(kubectl, TaskInputParameters.namespace, annotationKey);
|
||||||
let annotationKeyValStr = annotationKey + '=' + models.getWorkflowAnnotationsJson(lastSuccessSha, workflowFilePath);
|
let annotationKeyValStr = annotationKey + '=' + models.getWorkflowAnnotationsJson(lastSuccessSha, workflowFilePath, deploymentConfig);
|
||||||
annotateResults.push(kubectl.annotate('namespace', TaskInputParameters.namespace, annotationKeyValStr));
|
annotateResults.push(kubectl.annotate('namespace', TaskInputParameters.namespace, annotationKeyValStr));
|
||||||
annotateResults.push(kubectl.annotateFiles(files, annotationKeyValStr));
|
annotateResults.push(kubectl.annotateFiles(files, annotationKeyValStr));
|
||||||
resourceTypes.forEach(resource => {
|
resourceTypes.forEach(resource => {
|
||||||
@@ -154,9 +134,44 @@ function annotateResources(files, kubectl, resourceTypes, allPods, annotationKey
|
|||||||
utility_1.checkForErrors(annotateResults, true);
|
utility_1.checkForErrors(annotateResults, true);
|
||||||
}
|
}
|
||||||
function labelResources(files, kubectl, label) {
|
function labelResources(files, kubectl, label) {
|
||||||
const labels = [`workflowFriendlyName=${utility_1.normaliseWorkflowStrLabel(process.env.GITHUB_WORKFLOW)}`, `workflow=${label}`];
|
let workflowName = process.env.GITHUB_WORKFLOW;
|
||||||
|
workflowName = workflowName.startsWith('.github/workflows/') ?
|
||||||
|
workflowName.replace(".github/workflows/", "") : workflowName;
|
||||||
|
const labels = [`workflowFriendlyName=${workflowName}`, `workflow=${label}`];
|
||||||
utility_1.checkForErrors([kubectl.labelFiles(files, labels)], true);
|
utility_1.checkForErrors([kubectl.labelFiles(files, labels)], true);
|
||||||
}
|
}
|
||||||
|
function updateResourceObjects(filePaths, imagePullSecrets, containers) {
|
||||||
|
const newObjectsList = [];
|
||||||
|
const updateResourceObject = (inputObject) => {
|
||||||
|
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
|
||||||
|
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
|
||||||
|
}
|
||||||
|
if (!!containers && containers.length > 0) {
|
||||||
|
KubernetesObjectUtility.updateImageDetails(inputObject, containers);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
filePaths.forEach((filePath) => {
|
||||||
|
const fileContents = fs.readFileSync(filePath).toString();
|
||||||
|
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||||
|
if (inputObject && inputObject.kind) {
|
||||||
|
const kind = inputObject.kind;
|
||||||
|
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
|
||||||
|
updateResourceObject(inputObject);
|
||||||
|
}
|
||||||
|
else if (string_comparison_1.isEqual(kind, 'list', string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||||
|
let items = inputObject.items;
|
||||||
|
if (items.length > 0) {
|
||||||
|
items.forEach((item) => updateResourceObject(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newObjectsList.push(inputObject);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList));
|
||||||
|
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
|
||||||
|
return newFilePaths;
|
||||||
|
}
|
||||||
function isCanaryDeploymentStrategy(deploymentStrategy) {
|
function isCanaryDeploymentStrategy(deploymentStrategy) {
|
||||||
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
|
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.updateIngressBackend = exports.getUpdatedBlueGreenIngress = exports.validateIngressesState = exports.routeBlueGreenIngress = exports.rejectBlueGreenIngress = exports.promoteBlueGreenIngress = exports.deployBlueGreenIngress = void 0;
|
|
||||||
const core = require("@actions/core");
|
|
||||||
const fileHelper = require("../files-helper");
|
|
||||||
const blue_green_helper_1 = require("./blue-green-helper");
|
|
||||||
const blue_green_helper_2 = require("./blue-green-helper");
|
|
||||||
const BACKEND = 'BACKEND';
|
|
||||||
function deployBlueGreenIngress(kubectl, filePaths) {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// create deployments with green label value
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
// create new services and other objects
|
|
||||||
let newObjectsList = [];
|
|
||||||
manifestObjects.serviceEntityList.forEach(inputObject => {
|
|
||||||
const newBlueGreenObject = blue_green_helper_1.getNewBlueGreenObject(inputObject, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
;
|
|
||||||
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
|
|
||||||
newObjectsList.push(newBlueGreenObject);
|
|
||||||
});
|
|
||||||
newObjectsList = newObjectsList.concat(manifestObjects.otherObjects).concat(manifestObjects.unroutedServiceEntityList);
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
// return results to check for manifest stability
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
exports.deployBlueGreenIngress = deployBlueGreenIngress;
|
|
||||||
function promoteBlueGreenIngress(kubectl, manifestObjects) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
//checking if anything to promote
|
|
||||||
if (!validateIngressesState(kubectl, manifestObjects.ingressEntityList, manifestObjects.serviceNameMap)) {
|
|
||||||
throw ('NotInPromoteStateIngress');
|
|
||||||
}
|
|
||||||
// create stable deployments with new configuration
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
// create stable services with new configuration
|
|
||||||
const newObjectsList = [];
|
|
||||||
manifestObjects.serviceEntityList.forEach((inputObject) => {
|
|
||||||
const newBlueGreenObject = blue_green_helper_1.getNewBlueGreenObject(inputObject, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
|
|
||||||
newObjectsList.push(newBlueGreenObject);
|
|
||||||
});
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
// returning deployments to check for rollout stability
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.promoteBlueGreenIngress = promoteBlueGreenIngress;
|
|
||||||
function rejectBlueGreenIngress(kubectl, filePaths) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// routing ingress to stables services
|
|
||||||
routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
|
|
||||||
// deleting green services and deployments
|
|
||||||
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.rejectBlueGreenIngress = rejectBlueGreenIngress;
|
|
||||||
function routeBlueGreenIngress(kubectl, nextLabel, serviceNameMap, ingressEntityList) {
|
|
||||||
let newObjectsList = [];
|
|
||||||
if (!nextLabel) {
|
|
||||||
newObjectsList = ingressEntityList.filter(ingress => isIngressRouted(ingress, serviceNameMap));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
ingressEntityList.forEach((inputObject) => {
|
|
||||||
if (isIngressRouted(inputObject, serviceNameMap)) {
|
|
||||||
const newBlueGreenIngressObject = getUpdatedBlueGreenIngress(inputObject, serviceNameMap, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
newObjectsList.push(newBlueGreenIngressObject);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
newObjectsList.push(inputObject);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
}
|
|
||||||
exports.routeBlueGreenIngress = routeBlueGreenIngress;
|
|
||||||
function validateIngressesState(kubectl, ingressEntityList, serviceNameMap) {
|
|
||||||
let areIngressesTargetingNewServices = true;
|
|
||||||
ingressEntityList.forEach((inputObject) => {
|
|
||||||
if (isIngressRouted(inputObject, serviceNameMap)) {
|
|
||||||
//querying existing ingress
|
|
||||||
let existingIngress = blue_green_helper_1.fetchResource(kubectl, inputObject.kind, inputObject.metadata.name);
|
|
||||||
if (!!existingIngress) {
|
|
||||||
let currentLabel;
|
|
||||||
// checking its label
|
|
||||||
try {
|
|
||||||
currentLabel = existingIngress.metadata.labels[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL];
|
|
||||||
}
|
|
||||||
catch (_a) {
|
|
||||||
// if no label exists, then not an ingress targeting green deployments
|
|
||||||
areIngressesTargetingNewServices = false;
|
|
||||||
}
|
|
||||||
if (currentLabel != blue_green_helper_2.GREEN_LABEL_VALUE) {
|
|
||||||
// if not green label, then wrong configuration
|
|
||||||
areIngressesTargetingNewServices = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// no ingress at all, so nothing to promote
|
|
||||||
areIngressesTargetingNewServices = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return areIngressesTargetingNewServices;
|
|
||||||
}
|
|
||||||
exports.validateIngressesState = validateIngressesState;
|
|
||||||
function isIngressRouted(ingressObject, serviceNameMap) {
|
|
||||||
let isIngressRouted = false;
|
|
||||||
// sees if ingress targets a service in the given manifests
|
|
||||||
JSON.parse(JSON.stringify(ingressObject), (key, value) => {
|
|
||||||
if (key === 'serviceName' && serviceNameMap.has(value)) {
|
|
||||||
isIngressRouted = true;
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
return isIngressRouted;
|
|
||||||
}
|
|
||||||
function getUpdatedBlueGreenIngress(inputObject, serviceNameMap, type) {
|
|
||||||
if (!type) {
|
|
||||||
// returning original with no modifications
|
|
||||||
return inputObject;
|
|
||||||
}
|
|
||||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
|
||||||
// adding green labels and values
|
|
||||||
blue_green_helper_1.addBlueGreenLabelsAndAnnotations(newObject, type);
|
|
||||||
// Updating ingress labels
|
|
||||||
let finalObject = updateIngressBackend(newObject, serviceNameMap);
|
|
||||||
return finalObject;
|
|
||||||
}
|
|
||||||
exports.getUpdatedBlueGreenIngress = getUpdatedBlueGreenIngress;
|
|
||||||
function updateIngressBackend(inputObject, serviceNameMap) {
|
|
||||||
inputObject = JSON.parse(JSON.stringify(inputObject), (key, value) => {
|
|
||||||
if (key.toUpperCase() === BACKEND) {
|
|
||||||
let serviceName = value.serviceName;
|
|
||||||
if (serviceNameMap.has(serviceName)) {
|
|
||||||
// updating service name with corresponding bluegreen name only if service is provied in given manifests
|
|
||||||
value.serviceName = serviceNameMap.get(serviceName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
return inputObject;
|
|
||||||
}
|
|
||||||
exports.updateIngressBackend = updateIngressBackend;
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.getServiceSpecLabel = exports.validateServicesState = exports.routeBlueGreenService = exports.rejectBlueGreenService = exports.promoteBlueGreenService = exports.deployBlueGreenService = void 0;
|
|
||||||
const fileHelper = require("../files-helper");
|
|
||||||
const blue_green_helper_1 = require("./blue-green-helper");
|
|
||||||
const blue_green_helper_2 = require("./blue-green-helper");
|
|
||||||
function deployBlueGreenService(kubectl, filePaths) {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// create deployments with green label value
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
// create other non deployment and non service entities
|
|
||||||
const newObjectsList = manifestObjects.otherObjects.concat(manifestObjects.ingressEntityList).concat(manifestObjects.unroutedServiceEntityList);
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
// returning deployment details to check for rollout stability
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
exports.deployBlueGreenService = deployBlueGreenService;
|
|
||||||
function promoteBlueGreenService(kubectl, manifestObjects) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// checking if services are in the right state ie. targeting green deployments
|
|
||||||
if (!validateServicesState(kubectl, manifestObjects.serviceEntityList)) {
|
|
||||||
throw ('NotInPromoteState');
|
|
||||||
}
|
|
||||||
// creating stable deployments with new configurations
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
// returning deployment details to check for rollout stability
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.promoteBlueGreenService = promoteBlueGreenService;
|
|
||||||
function rejectBlueGreenService(kubectl, filePaths) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// routing to stable objects
|
|
||||||
routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
// deleting the new deployments with green suffix
|
|
||||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.rejectBlueGreenService = rejectBlueGreenService;
|
|
||||||
function routeBlueGreenService(kubectl, nextLabel, serviceEntityList) {
|
|
||||||
const newObjectsList = [];
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
const newBlueGreenServiceObject = getUpdatedBlueGreenService(serviceObject, nextLabel);
|
|
||||||
newObjectsList.push(newBlueGreenServiceObject);
|
|
||||||
});
|
|
||||||
// configures the services
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
}
|
|
||||||
exports.routeBlueGreenService = routeBlueGreenService;
|
|
||||||
// adding green labels to configure existing service
|
|
||||||
function getUpdatedBlueGreenService(inputObject, labelValue) {
|
|
||||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
|
||||||
// Adding labels and annotations.
|
|
||||||
blue_green_helper_1.addBlueGreenLabelsAndAnnotations(newObject, labelValue);
|
|
||||||
return newObject;
|
|
||||||
}
|
|
||||||
function validateServicesState(kubectl, serviceEntityList) {
|
|
||||||
let areServicesGreen = true;
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
// finding the existing routed service
|
|
||||||
const existingService = blue_green_helper_1.fetchResource(kubectl, serviceObject.kind, serviceObject.metadata.name);
|
|
||||||
if (!!existingService) {
|
|
||||||
let currentLabel = getServiceSpecLabel(existingService);
|
|
||||||
if (currentLabel != blue_green_helper_2.GREEN_LABEL_VALUE) {
|
|
||||||
// service should be targeting deployments with green label
|
|
||||||
areServicesGreen = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// service targeting deployment doesn't exist
|
|
||||||
areServicesGreen = false;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return areServicesGreen;
|
|
||||||
}
|
|
||||||
exports.validateServicesState = validateServicesState;
|
|
||||||
function getServiceSpecLabel(inputObject) {
|
|
||||||
if (!!inputObject && inputObject.spec && inputObject.spec.selector && inputObject.spec.selector[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL]) {
|
|
||||||
return inputObject.spec.selector[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL];
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
exports.getServiceSpecLabel = getServiceSpecLabel;
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.cleanupSMI = exports.validateTrafficSplitsState = exports.routeBlueGreenSMI = exports.getSMIServiceResource = exports.setupSMI = exports.rejectBlueGreenSMI = exports.promoteBlueGreenSMI = exports.deployBlueGreenSMI = void 0;
|
|
||||||
const kubectlUtils = require("../kubectl-util");
|
|
||||||
const fileHelper = require("../files-helper");
|
|
||||||
const blue_green_helper_1 = require("./blue-green-helper");
|
|
||||||
const blue_green_helper_2 = require("./blue-green-helper");
|
|
||||||
let trafficSplitAPIVersion = "";
|
|
||||||
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-trafficsplit';
|
|
||||||
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
|
|
||||||
const MIN_VAL = '0';
|
|
||||||
const MAX_VAL = '100';
|
|
||||||
function deployBlueGreenSMI(kubectl, filePaths) {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// creating services and other objects
|
|
||||||
const newObjectsList = manifestObjects.otherObjects.concat(manifestObjects.serviceEntityList).concat(manifestObjects.ingressEntityList).concat(manifestObjects.unroutedServiceEntityList);
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
// make extraservices and trafficsplit
|
|
||||||
setupSMI(kubectl, manifestObjects.serviceEntityList);
|
|
||||||
// create new deloyments
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
// return results to check for manifest stability
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
exports.deployBlueGreenSMI = deployBlueGreenSMI;
|
|
||||||
function promoteBlueGreenSMI(kubectl, manifestObjects) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// checking if there is something to promote
|
|
||||||
if (!validateTrafficSplitsState(kubectl, manifestObjects.serviceEntityList)) {
|
|
||||||
throw ('NotInPromoteStateSMI');
|
|
||||||
}
|
|
||||||
// create stable deployments with new configuration
|
|
||||||
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
// return result to check for stability
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.promoteBlueGreenSMI = promoteBlueGreenSMI;
|
|
||||||
function rejectBlueGreenSMI(kubectl, filePaths) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// get all kubernetes objects defined in manifest files
|
|
||||||
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
|
|
||||||
// routing trafficsplit to stable deploymetns
|
|
||||||
routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
|
||||||
// deleting rejected new bluegreen deplyments
|
|
||||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
|
||||||
//deleting trafficsplit and extra services
|
|
||||||
cleanupSMI(kubectl, manifestObjects.serviceEntityList);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.rejectBlueGreenSMI = rejectBlueGreenSMI;
|
|
||||||
function setupSMI(kubectl, serviceEntityList) {
|
|
||||||
const newObjectsList = [];
|
|
||||||
const trafficObjectList = [];
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
// create a trafficsplit for service
|
|
||||||
trafficObjectList.push(serviceObject);
|
|
||||||
// setting up the services for trafficsplit
|
|
||||||
const newStableService = getSMIServiceResource(serviceObject, blue_green_helper_2.STABLE_SUFFIX);
|
|
||||||
const newGreenService = getSMIServiceResource(serviceObject, blue_green_helper_2.GREEN_SUFFIX);
|
|
||||||
newObjectsList.push(newStableService);
|
|
||||||
newObjectsList.push(newGreenService);
|
|
||||||
});
|
|
||||||
// creating services
|
|
||||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
|
||||||
kubectl.apply(manifestFiles);
|
|
||||||
// route to stable service
|
|
||||||
trafficObjectList.forEach((inputObject) => {
|
|
||||||
createTrafficSplitObject(kubectl, inputObject.metadata.name, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.setupSMI = setupSMI;
|
|
||||||
function createTrafficSplitObject(kubectl, name, nextLabel) {
|
|
||||||
// getting smi spec api version
|
|
||||||
if (!trafficSplitAPIVersion) {
|
|
||||||
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
|
|
||||||
}
|
|
||||||
// deciding weights based on nextlabel
|
|
||||||
let stableWeight;
|
|
||||||
let greenWeight;
|
|
||||||
if (nextLabel === blue_green_helper_2.GREEN_LABEL_VALUE) {
|
|
||||||
stableWeight = parseInt(MIN_VAL);
|
|
||||||
greenWeight = parseInt(MAX_VAL);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
stableWeight = parseInt(MAX_VAL);
|
|
||||||
greenWeight = parseInt(MIN_VAL);
|
|
||||||
}
|
|
||||||
//traffic split json
|
|
||||||
const trafficSplitObject = `{
|
|
||||||
"apiVersion": "${trafficSplitAPIVersion}",
|
|
||||||
"kind": "TrafficSplit",
|
|
||||||
"metadata": {
|
|
||||||
"name": "${blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX)}"
|
|
||||||
},
|
|
||||||
"spec": {
|
|
||||||
"service": "${name}",
|
|
||||||
"backends": [
|
|
||||||
{
|
|
||||||
"service": "${blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.STABLE_SUFFIX)}",
|
|
||||||
"weight": ${stableWeight}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"service": "${blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.GREEN_SUFFIX)}",
|
|
||||||
"weight": ${greenWeight}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}`;
|
|
||||||
// creating trafficplit object
|
|
||||||
const trafficSplitManifestFile = fileHelper.writeManifestToFile(trafficSplitObject, TRAFFIC_SPLIT_OBJECT, blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX));
|
|
||||||
kubectl.apply(trafficSplitManifestFile);
|
|
||||||
}
|
|
||||||
function getSMIServiceResource(inputObject, suffix) {
|
|
||||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
|
||||||
if (suffix === blue_green_helper_2.STABLE_SUFFIX) {
|
|
||||||
// adding stable suffix to service name
|
|
||||||
newObject.metadata.name = blue_green_helper_1.getBlueGreenResourceName(inputObject.metadata.name, blue_green_helper_2.STABLE_SUFFIX);
|
|
||||||
return blue_green_helper_1.getNewBlueGreenObject(newObject, blue_green_helper_2.NONE_LABEL_VALUE);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// green label will be added for these
|
|
||||||
return blue_green_helper_1.getNewBlueGreenObject(newObject, blue_green_helper_2.GREEN_LABEL_VALUE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.getSMIServiceResource = getSMIServiceResource;
|
|
||||||
function routeBlueGreenSMI(kubectl, nextLabel, serviceEntityList) {
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
// routing trafficsplit to given label
|
|
||||||
createTrafficSplitObject(kubectl, serviceObject.metadata.name, nextLabel);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.routeBlueGreenSMI = routeBlueGreenSMI;
|
|
||||||
function validateTrafficSplitsState(kubectl, serviceEntityList) {
|
|
||||||
let areTrafficSplitsInRightState = true;
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
const name = serviceObject.metadata.name;
|
|
||||||
let trafficSplitObject = blue_green_helper_1.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX));
|
|
||||||
if (!trafficSplitObject) {
|
|
||||||
// no trafficplit exits
|
|
||||||
areTrafficSplitsInRightState = false;
|
|
||||||
}
|
|
||||||
trafficSplitObject = JSON.parse(JSON.stringify(trafficSplitObject));
|
|
||||||
trafficSplitObject.spec.backends.forEach(element => {
|
|
||||||
// checking if trafficsplit in right state to deploy
|
|
||||||
if (element.service === blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.GREEN_SUFFIX)) {
|
|
||||||
if (element.weight != MAX_VAL) {
|
|
||||||
// green service should have max weight
|
|
||||||
areTrafficSplitsInRightState = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (element.service === blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.STABLE_SUFFIX)) {
|
|
||||||
if (element.weight != MIN_VAL) {
|
|
||||||
// stable service should have 0 weight
|
|
||||||
areTrafficSplitsInRightState = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return areTrafficSplitsInRightState;
|
|
||||||
}
|
|
||||||
exports.validateTrafficSplitsState = validateTrafficSplitsState;
|
|
||||||
function cleanupSMI(kubectl, serviceEntityList) {
|
|
||||||
const deleteList = [];
|
|
||||||
serviceEntityList.forEach((serviceObject) => {
|
|
||||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX), kind: TRAFFIC_SPLIT_OBJECT });
|
|
||||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.GREEN_SUFFIX), kind: serviceObject.kind });
|
|
||||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.STABLE_SUFFIX), kind: serviceObject.kind });
|
|
||||||
});
|
|
||||||
// deleting all objects
|
|
||||||
blue_green_helper_1.deleteObjects(kubectl, deleteList);
|
|
||||||
}
|
|
||||||
exports.cleanupSMI = cleanupSMI;
|
|
||||||
+69
-29
@@ -9,12 +9,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
exports.resolveGlobPatterns = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.normaliseWorkflowStrLabel = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
|
exports.getNormalizedPath = exports.isHttpUrl = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.getDeploymentConfig = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
|
||||||
const os = require("os");
|
const os = require("os");
|
||||||
const core = require("@actions/core");
|
const core = require("@actions/core");
|
||||||
const glob = require("glob");
|
|
||||||
const githubClient_1 = require("../githubClient");
|
const githubClient_1 = require("../githubClient");
|
||||||
const httpClient_1 = require("./httpClient");
|
const httpClient_1 = require("./httpClient");
|
||||||
|
const inputParams = require("../input-parameters");
|
||||||
|
const docker_object_model_1 = require("../docker-object-model");
|
||||||
|
const io = require("@actions/io");
|
||||||
function getExecutableExtension() {
|
function getExecutableExtension() {
|
||||||
if (os.type().match(/^Win/)) {
|
if (os.type().match(/^Win/)) {
|
||||||
return '.exe';
|
return '.exe';
|
||||||
@@ -127,24 +129,45 @@ function annotateChildPods(kubectl, resourceType, resourceName, annotationKeyVal
|
|||||||
allPods.items.forEach((pod) => {
|
allPods.items.forEach((pod) => {
|
||||||
const owners = pod.metadata.ownerReferences;
|
const owners = pod.metadata.ownerReferences;
|
||||||
if (owners) {
|
if (owners) {
|
||||||
for (let ownerRef of owners) {
|
owners.forEach(ownerRef => {
|
||||||
if (ownerRef.name === owner) {
|
if (ownerRef.name === owner) {
|
||||||
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr));
|
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr));
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return commandExecutionResults;
|
return commandExecutionResults;
|
||||||
}
|
}
|
||||||
exports.annotateChildPods = annotateChildPods;
|
exports.annotateChildPods = annotateChildPods;
|
||||||
function normaliseWorkflowStrLabel(workflowName) {
|
function getDeploymentConfig() {
|
||||||
workflowName = workflowName.startsWith('.github/workflows/') ?
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
workflowName.replace(".github/workflows/", "") : workflowName;
|
let helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split(';').filter(path => path != "")) || [];
|
||||||
return workflowName.replace(/ /g, "_");
|
helmChartPaths = helmChartPaths.map(helmchart => getNormalizedPath(helmchart.trim()));
|
||||||
|
let inputManifestFiles = inputParams.manifests || [];
|
||||||
|
if (!helmChartPaths.length) {
|
||||||
|
inputManifestFiles = inputManifestFiles.map(manifestFile => getNormalizedPath(manifestFile));
|
||||||
|
}
|
||||||
|
const imageNames = inputParams.containers || [];
|
||||||
|
let imageDockerfilePathMap = {};
|
||||||
|
//Fetching from image label if available
|
||||||
|
for (const image of imageNames) {
|
||||||
|
try {
|
||||||
|
imageDockerfilePathMap[image] = yield getDockerfilePath(image);
|
||||||
|
}
|
||||||
|
catch (ex) {
|
||||||
|
core.warning(`Failed to get dockerfile path for image ${image.toString()} | ` + ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const deploymentConfig = {
|
||||||
|
manifestFilePaths: inputManifestFiles,
|
||||||
|
helmChartFilePaths: helmChartPaths,
|
||||||
|
dockerfilePaths: imageDockerfilePathMap
|
||||||
|
};
|
||||||
|
return Promise.resolve(deploymentConfig);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
exports.normaliseWorkflowStrLabel = normaliseWorkflowStrLabel;
|
exports.getDeploymentConfig = getDeploymentConfig;
|
||||||
function sleep(timeout) {
|
function sleep(timeout) {
|
||||||
return new Promise(resolve => setTimeout(resolve, timeout));
|
return new Promise(resolve => setTimeout(resolve, timeout));
|
||||||
}
|
}
|
||||||
@@ -157,25 +180,42 @@ function getCurrentTime() {
|
|||||||
return new Date().getTime();
|
return new Date().getTime();
|
||||||
}
|
}
|
||||||
exports.getCurrentTime = getCurrentTime;
|
exports.getCurrentTime = getCurrentTime;
|
||||||
function resolveGlobPatterns(manifests) {
|
function checkDockerPath() {
|
||||||
if (!manifests) {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
core.setFailed('No manifests supplied to deploy');
|
let dockerPath = yield io.which('docker', false);
|
||||||
return;
|
if (!dockerPath) {
|
||||||
}
|
throw new Error('Docker is not installed.');
|
||||||
let unresolvedManifests = manifests.split("\n");
|
|
||||||
let resolvedManifests = [];
|
|
||||||
unresolvedManifests.forEach((manifestPath) => {
|
|
||||||
if (glob.hasMagic(manifestPath)) {
|
|
||||||
resolvedManifests = resolvedManifests.concat(glob.sync(manifestPath));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
resolvedManifests.push(manifestPath);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (!resolvedManifests) {
|
|
||||||
core.setFailed('No manifests supplied to deploy');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
return resolvedManifests;
|
|
||||||
}
|
}
|
||||||
exports.resolveGlobPatterns = resolveGlobPatterns;
|
function getDockerfilePath(image) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
let imageConfig, imageInspectResult;
|
||||||
|
var dockerExec = new docker_object_model_1.DockerExec('docker');
|
||||||
|
yield checkDockerPath();
|
||||||
|
dockerExec.pull(image, [], true);
|
||||||
|
imageInspectResult = dockerExec.inspect(image, [], true);
|
||||||
|
imageConfig = JSON.parse(imageInspectResult)[0];
|
||||||
|
const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path';
|
||||||
|
let pathValue = '';
|
||||||
|
if (imageConfig) {
|
||||||
|
if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) {
|
||||||
|
const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY];
|
||||||
|
pathValue = getNormalizedPath(pathLabel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pathValue;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function isHttpUrl(url) {
|
||||||
|
const HTTP_REGEX = /^https?:\/\/.*$/;
|
||||||
|
return HTTP_REGEX.test(url);
|
||||||
|
}
|
||||||
|
exports.isHttpUrl = isHttpUrl;
|
||||||
|
function getNormalizedPath(pathValue) {
|
||||||
|
if (!isHttpUrl(pathValue)) { //if it is not an http url then convert to link from current repo and commit
|
||||||
|
return `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${pathValue}`;
|
||||||
|
}
|
||||||
|
return pathValue;
|
||||||
|
}
|
||||||
|
exports.getNormalizedPath = getNormalizedPath;
|
||||||
|
|||||||
-1
@@ -1 +0,0 @@
|
|||||||
../esprima/bin/esparse.js
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
"$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
else
|
||||||
|
node "$basedir/../esprima/bin/esparse.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
fi
|
||||||
|
exit $ret
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
|
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esparse.js" %*
|
||||||
|
) ELSE (
|
||||||
|
@SETLOCAL
|
||||||
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
node "%~dp0\..\esprima\bin\esparse.js" %*
|
||||||
|
)
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
../esprima/bin/esvalidate.js
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
"$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
else
|
||||||
|
node "$basedir/../esprima/bin/esvalidate.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
fi
|
||||||
|
exit $ret
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
|
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esvalidate.js" %*
|
||||||
|
) ELSE (
|
||||||
|
@SETLOCAL
|
||||||
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
node "%~dp0\..\esprima\bin\esvalidate.js" %*
|
||||||
|
)
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
../js-yaml/bin/js-yaml.js
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
"$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
else
|
||||||
|
node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
fi
|
||||||
|
exit $ret
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
|
"%~dp0\node.exe" "%~dp0\..\js-yaml\bin\js-yaml.js" %*
|
||||||
|
) ELSE (
|
||||||
|
@SETLOCAL
|
||||||
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
node "%~dp0\..\js-yaml\bin\js-yaml.js" %*
|
||||||
|
)
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
../semver/bin/semver.js
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
"$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
else
|
||||||
|
node "$basedir/../semver/bin/semver.js" "$@"
|
||||||
|
ret=$?
|
||||||
|
fi
|
||||||
|
exit $ret
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
|
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver.js" %*
|
||||||
|
) ELSE (
|
||||||
|
@SETLOCAL
|
||||||
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
node "%~dp0\..\semver\bin\semver.js" %*
|
||||||
|
)
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
../uuid/bin/uuid
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
"$basedir/node" "$basedir/../uuid/bin/uuid" "$@"
|
||||||
|
ret=$?
|
||||||
|
else
|
||||||
|
node "$basedir/../uuid/bin/uuid" "$@"
|
||||||
|
ret=$?
|
||||||
|
fi
|
||||||
|
exit $ret
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
|
"%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %*
|
||||||
|
) ELSE (
|
||||||
|
@SETLOCAL
|
||||||
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
node "%~dp0\..\uuid\bin\uuid" %*
|
||||||
|
)
|
||||||
+7
-8
@@ -1,30 +1,29 @@
|
|||||||
{
|
{
|
||||||
"_from": "@actions/core@1.2.6",
|
"_from": "@actions/core@^1.2.6",
|
||||||
"_id": "@actions/core@1.2.6",
|
"_id": "@actions/core@1.2.6",
|
||||||
"_inBundle": false,
|
"_inBundle": false,
|
||||||
"_integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA==",
|
"_integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA==",
|
||||||
"_location": "/@actions/core",
|
"_location": "/@actions/core",
|
||||||
"_phantomChildren": {},
|
"_phantomChildren": {},
|
||||||
"_requested": {
|
"_requested": {
|
||||||
"type": "version",
|
"type": "range",
|
||||||
"registry": true,
|
"registry": true,
|
||||||
"raw": "@actions/core@1.2.6",
|
"raw": "@actions/core@^1.2.6",
|
||||||
"name": "@actions/core",
|
"name": "@actions/core",
|
||||||
"escapedName": "@actions%2fcore",
|
"escapedName": "@actions%2fcore",
|
||||||
"scope": "@actions",
|
"scope": "@actions",
|
||||||
"rawSpec": "1.2.6",
|
"rawSpec": "^1.2.6",
|
||||||
"saveSpec": null,
|
"saveSpec": null,
|
||||||
"fetchSpec": "1.2.6"
|
"fetchSpec": "^1.2.6"
|
||||||
},
|
},
|
||||||
"_requiredBy": [
|
"_requiredBy": [
|
||||||
"#USER",
|
|
||||||
"/",
|
"/",
|
||||||
"/@actions/tool-cache"
|
"/@actions/tool-cache"
|
||||||
],
|
],
|
||||||
"_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz",
|
"_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz",
|
||||||
"_shasum": "a78d49f41a4def18e88ce47c2cac615d5694bf09",
|
"_shasum": "a78d49f41a4def18e88ce47c2cac615d5694bf09",
|
||||||
"_spec": "@actions/core@1.2.6",
|
"_spec": "@actions/core@^1.2.6",
|
||||||
"_where": "D:\\Work\\Actions\\k8s-deploy",
|
"_where": "C:\\Users\\kodey\\workspace\\github-actions\\k8s-deploy",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
"url": "https://github.com/actions/toolkit/issues"
|
||||||
},
|
},
|
||||||
|
|||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
Copyright 2019 GitHub
|
||||||
|
|
||||||
|
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.
|
||||||
+6
-3
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
#### Basic
|
#### Basic
|
||||||
|
|
||||||
You can use this package to execute tools in a cross platform way:
|
You can use this package to execute your tools on the command line in a cross platform way:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
@@ -48,10 +48,13 @@ await exec.exec('node', ['index.js', 'foo=bar'], options);
|
|||||||
|
|
||||||
#### Exec tools not in the PATH
|
#### Exec tools not in the PATH
|
||||||
|
|
||||||
You can specify the full path for tools not in the PATH:
|
You can use it in conjunction with the `which` function from `@actions/io` to execute tools that are not in the PATH:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
|
const io = require('@actions/io');
|
||||||
|
|
||||||
await exec.exec('"/path/to/my-tool"', ['arg1']);
|
const pythonPath: string = await io.which('python', true)
|
||||||
|
|
||||||
|
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
||||||
```
|
```
|
||||||
|
|||||||
+2
-3
@@ -1,5 +1,4 @@
|
|||||||
import { ExecOptions } from './interfaces';
|
import * as im from './interfaces';
|
||||||
export { ExecOptions };
|
|
||||||
/**
|
/**
|
||||||
* Exec a command.
|
* Exec a command.
|
||||||
* Output will be streamed to the live console.
|
* Output will be streamed to the live console.
|
||||||
@@ -10,4 +9,4 @@ export { ExecOptions };
|
|||||||
* @param options optional exec options. See ExecOptions
|
* @param options optional exec options. See ExecOptions
|
||||||
* @returns Promise<number> exit code
|
* @returns Promise<number> exit code
|
||||||
*/
|
*/
|
||||||
export declare function exec(commandLine: string, args?: string[], options?: ExecOptions): Promise<number>;
|
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>;
|
||||||
|
|||||||
+1
-8
@@ -8,15 +8,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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 });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const tr = __importStar(require("./toolrunner"));
|
const tr = require("./toolrunner");
|
||||||
/**
|
/**
|
||||||
* Exec a command.
|
* Exec a command.
|
||||||
* Output will be streamed to the live console.
|
* Output will be streamed to the live console.
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,iDAAkC;AAIlC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAqB;;QAErB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"}
|
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,mCAAkC;AAElC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAwB;;QAExB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"}
|
||||||
-2
@@ -24,8 +24,6 @@ export interface ExecOptions {
|
|||||||
ignoreReturnCode?: boolean;
|
ignoreReturnCode?: boolean;
|
||||||
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
||||||
delay?: number;
|
delay?: number;
|
||||||
/** optional. input to write to the process on STDIN. */
|
|
||||||
input?: Buffer;
|
|
||||||
/** optional. Listeners for output. Callback functions that will be called on these events */
|
/** optional. Listeners for output. Callback functions that will be called on these events */
|
||||||
listeners?: {
|
listeners?: {
|
||||||
stdout?: (data: Buffer) => void;
|
stdout?: (data: Buffer) => void;
|
||||||
|
|||||||
+3
-29
@@ -8,20 +8,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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 });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const os = __importStar(require("os"));
|
const os = require("os");
|
||||||
const events = __importStar(require("events"));
|
const events = require("events");
|
||||||
const child = __importStar(require("child_process"));
|
const child = require("child_process");
|
||||||
const path = __importStar(require("path"));
|
|
||||||
const io = __importStar(require("@actions/io"));
|
|
||||||
const ioUtil = __importStar(require("@actions/io/lib/io-util"));
|
|
||||||
/* eslint-disable @typescript-eslint/unbound-method */
|
/* eslint-disable @typescript-eslint/unbound-method */
|
||||||
const IS_WINDOWS = process.platform === 'win32';
|
const IS_WINDOWS = process.platform === 'win32';
|
||||||
/*
|
/*
|
||||||
@@ -367,16 +357,6 @@ class ToolRunner extends events.EventEmitter {
|
|||||||
*/
|
*/
|
||||||
exec() {
|
exec() {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
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) => {
|
return new Promise((resolve, reject) => {
|
||||||
this._debug(`exec tool: ${this.toolPath}`);
|
this._debug(`exec tool: ${this.toolPath}`);
|
||||||
this._debug('arguments:');
|
this._debug('arguments:');
|
||||||
@@ -465,12 +445,6 @@ class ToolRunner extends events.EventEmitter {
|
|||||||
resolve(exitCode);
|
resolve(exitCode);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (this.options.input) {
|
|
||||||
if (!cp.stdin) {
|
|
||||||
throw new Error('child process missing stdin');
|
|
||||||
}
|
|
||||||
cp.stdin.end(this.options.input);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
File diff suppressed because one or more lines are too long
+20
-19
@@ -1,38 +1,41 @@
|
|||||||
{
|
{
|
||||||
"_from": "@actions/exec@1.0.4",
|
"_args": [
|
||||||
"_id": "@actions/exec@1.0.4",
|
[
|
||||||
|
"@actions/exec@1.0.1",
|
||||||
|
"E:\\k8s-actions\\deploy\\k8s-deploy"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"_from": "@actions/exec@1.0.1",
|
||||||
|
"_id": "@actions/exec@1.0.1",
|
||||||
"_inBundle": false,
|
"_inBundle": false,
|
||||||
"_integrity": "sha512-4DPChWow9yc9W3WqEbUj8Nr86xkpyE29ZzWjXucHItclLbEW6jr80Zx4nqv18QL6KK65+cifiQZXvnqgTV6oHw==",
|
"_integrity": "sha512-nvFkxwiicvpzNiCBF4wFBDfnBvi7xp/as7LE1hBxBxKG2L29+gkIPBiLKMVORL+Hg3JNf07AKRfl0V5djoypjQ==",
|
||||||
"_location": "/@actions/exec",
|
"_location": "/@actions/exec",
|
||||||
"_phantomChildren": {},
|
"_phantomChildren": {},
|
||||||
"_requested": {
|
"_requested": {
|
||||||
"type": "version",
|
"type": "version",
|
||||||
"registry": true,
|
"registry": true,
|
||||||
"raw": "@actions/exec@1.0.4",
|
"raw": "@actions/exec@1.0.1",
|
||||||
"name": "@actions/exec",
|
"name": "@actions/exec",
|
||||||
"escapedName": "@actions%2fexec",
|
"escapedName": "@actions%2fexec",
|
||||||
"scope": "@actions",
|
"scope": "@actions",
|
||||||
"rawSpec": "1.0.4",
|
"rawSpec": "1.0.1",
|
||||||
"saveSpec": null,
|
"saveSpec": null,
|
||||||
"fetchSpec": "1.0.4"
|
"fetchSpec": "1.0.1"
|
||||||
},
|
},
|
||||||
"_requiredBy": [
|
"_requiredBy": [
|
||||||
"/",
|
"/",
|
||||||
"/@actions/tool-cache"
|
"/@actions/tool-cache"
|
||||||
],
|
],
|
||||||
"_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.4.tgz",
|
"_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.1.tgz",
|
||||||
"_shasum": "99d75310e62e59fc37d2ee6dcff6d4bffadd3a5d",
|
"_spec": "1.0.1",
|
||||||
"_spec": "@actions/exec@1.0.4",
|
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy",
|
||||||
"_where": "/Users/aj/repos/k8s-deploy",
|
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
"url": "https://github.com/actions/toolkit/issues"
|
||||||
},
|
},
|
||||||
"bundleDependencies": false,
|
"description": "Actions exec lib",
|
||||||
"dependencies": {
|
"devDependencies": {
|
||||||
"@actions/io": "^1.0.1"
|
"@actions/io": "^1.0.1"
|
||||||
},
|
},
|
||||||
"deprecated": false,
|
|
||||||
"description": "Actions exec lib",
|
|
||||||
"directories": {
|
"directories": {
|
||||||
"lib": "lib",
|
"lib": "lib",
|
||||||
"test": "__tests__"
|
"test": "__tests__"
|
||||||
@@ -40,6 +43,7 @@
|
|||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
],
|
],
|
||||||
|
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52",
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"github",
|
"github",
|
||||||
@@ -54,14 +58,11 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
"url": "git+https://github.com/actions/toolkit.git"
|
||||||
"directory": "packages/exec"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||||
"tsc": "tsc"
|
"tsc": "tsc"
|
||||||
},
|
},
|
||||||
"types": "lib/exec.d.ts",
|
"version": "1.0.1"
|
||||||
"version": "1.0.4"
|
|
||||||
}
|
}
|
||||||
|
|||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
Actions Http Client for Node.js
|
|
||||||
|
|
||||||
Copyright (c) GitHub, Inc.
|
|
||||||
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
MIT License
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
||||||
associated documentation files (the "Software"), to deal in the Software without restriction,
|
|
||||||
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
|
|
||||||
subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
||||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
|
||||||
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
||||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="actions.png">
|
|
||||||
</p>
|
|
||||||
|
|
||||||
# Actions Http-Client
|
|
||||||
|
|
||||||
[](https://github.com/actions/http-client/actions)
|
|
||||||
|
|
||||||
A lightweight HTTP client optimized for use with actions, TypeScript with generics and async await.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- HTTP client with TypeScript generics and async/await/Promises
|
|
||||||
- Typings included so no need to acquire separately (great for intellisense and no versioning drift)
|
|
||||||
- [Proxy support](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/about-self-hosted-runners#using-a-proxy-server-with-self-hosted-runners) just works with actions and the runner
|
|
||||||
- Targets ES2019 (runner runs actions with node 12+). Only supported on node 12+.
|
|
||||||
- Basic, Bearer and PAT Support out of the box. Extensible handlers for others.
|
|
||||||
- Redirects supported
|
|
||||||
|
|
||||||
Features and releases [here](./RELEASES.md)
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```
|
|
||||||
npm install @actions/http-client --save
|
|
||||||
```
|
|
||||||
|
|
||||||
## Samples
|
|
||||||
|
|
||||||
See the [HTTP](./__tests__) tests for detailed examples.
|
|
||||||
|
|
||||||
## Errors
|
|
||||||
|
|
||||||
### HTTP
|
|
||||||
|
|
||||||
The HTTP client does not throw unless truly exceptional.
|
|
||||||
|
|
||||||
* A request that successfully executes resulting in a 404, 500 etc... will return a response object with a status code and a body.
|
|
||||||
* Redirects (3xx) will be followed by default.
|
|
||||||
|
|
||||||
See [HTTP tests](./__tests__) for detailed examples.
|
|
||||||
|
|
||||||
## Debugging
|
|
||||||
|
|
||||||
To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible:
|
|
||||||
|
|
||||||
```
|
|
||||||
export NODE_DEBUG=http
|
|
||||||
```
|
|
||||||
|
|
||||||
## Node support
|
|
||||||
|
|
||||||
The http-client is built using the latest LTS version of Node 12. It may work on previous node LTS versions but it's tested and officially supported on Node12+.
|
|
||||||
|
|
||||||
## Support and Versioning
|
|
||||||
|
|
||||||
We follow semver and will hold compatibility between major versions and increment the minor version with new features and capabilities (while holding compat).
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
We welcome PRs. Please create an issue and if applicable, a design before proceeding with code.
|
|
||||||
|
|
||||||
once:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ npm install
|
|
||||||
```
|
|
||||||
|
|
||||||
To build:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
To run all tests:
|
|
||||||
```bash
|
|
||||||
$ npm test
|
|
||||||
```
|
|
||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
## Releases
|
|
||||||
|
|
||||||
## 1.0.7
|
|
||||||
Update NPM dependencies and add 429 to the list of HttpCodes
|
|
||||||
|
|
||||||
## 1.0.6
|
|
||||||
Automatically sends Content-Type and Accept application/json headers for \<verb>Json() helper methods if not set in the client or parameters.
|
|
||||||
|
|
||||||
## 1.0.5
|
|
||||||
Adds \<verb>Json() helper methods for json over http scenarios.
|
|
||||||
|
|
||||||
## 1.0.4
|
|
||||||
Started to add \<verb>Json() helper methods. Do not use this release for that. Use >= 1.0.5 since there was an issue with types.
|
|
||||||
|
|
||||||
## 1.0.1 to 1.0.3
|
|
||||||
Adds proxy support.
|
|
||||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 33 KiB |
-23
@@ -1,23 +0,0 @@
|
|||||||
import ifm = require('./interfaces');
|
|
||||||
export declare class BasicCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
username: string;
|
|
||||||
password: string;
|
|
||||||
constructor(username: string, password: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export declare class BearerCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
token: string;
|
|
||||||
constructor(token: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export declare class PersonalAccessTokenCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
token: string;
|
|
||||||
constructor(token: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
-58
@@ -1,58 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
class BasicCredentialHandler {
|
|
||||||
constructor(username, password) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
handleAuthentication(httpClient, requestInfo, objs) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
|
|
||||||
-119
@@ -1,119 +0,0 @@
|
|||||||
/// <reference types="node" />
|
|
||||||
import http = require('http');
|
|
||||||
import ifm = require('./interfaces');
|
|
||||||
export declare enum HttpCodes {
|
|
||||||
OK = 200,
|
|
||||||
MultipleChoices = 300,
|
|
||||||
MovedPermanently = 301,
|
|
||||||
ResourceMoved = 302,
|
|
||||||
SeeOther = 303,
|
|
||||||
NotModified = 304,
|
|
||||||
UseProxy = 305,
|
|
||||||
SwitchProxy = 306,
|
|
||||||
TemporaryRedirect = 307,
|
|
||||||
PermanentRedirect = 308,
|
|
||||||
BadRequest = 400,
|
|
||||||
Unauthorized = 401,
|
|
||||||
PaymentRequired = 402,
|
|
||||||
Forbidden = 403,
|
|
||||||
NotFound = 404,
|
|
||||||
MethodNotAllowed = 405,
|
|
||||||
NotAcceptable = 406,
|
|
||||||
ProxyAuthenticationRequired = 407,
|
|
||||||
RequestTimeout = 408,
|
|
||||||
Conflict = 409,
|
|
||||||
Gone = 410,
|
|
||||||
TooManyRequests = 429,
|
|
||||||
InternalServerError = 500,
|
|
||||||
NotImplemented = 501,
|
|
||||||
BadGateway = 502,
|
|
||||||
ServiceUnavailable = 503,
|
|
||||||
GatewayTimeout = 504
|
|
||||||
}
|
|
||||||
export declare enum Headers {
|
|
||||||
Accept = "accept",
|
|
||||||
ContentType = "content-type"
|
|
||||||
}
|
|
||||||
export declare enum MediaTypes {
|
|
||||||
ApplicationJson = "application/json"
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
*/
|
|
||||||
export declare function getProxyUrl(serverUrl: string): string;
|
|
||||||
export declare class HttpClientResponse implements ifm.IHttpClientResponse {
|
|
||||||
constructor(message: http.IncomingMessage);
|
|
||||||
message: http.IncomingMessage;
|
|
||||||
readBody(): Promise<string>;
|
|
||||||
}
|
|
||||||
export declare function isHttps(requestUrl: string): boolean;
|
|
||||||
export declare class HttpClient {
|
|
||||||
userAgent: string | undefined;
|
|
||||||
handlers: ifm.IRequestHandler[];
|
|
||||||
requestOptions: ifm.IRequestOptions;
|
|
||||||
private _ignoreSslError;
|
|
||||||
private _socketTimeout;
|
|
||||||
private _allowRedirects;
|
|
||||||
private _allowRedirectDowngrade;
|
|
||||||
private _maxRedirects;
|
|
||||||
private _allowRetries;
|
|
||||||
private _maxRetries;
|
|
||||||
private _agent;
|
|
||||||
private _proxyAgent;
|
|
||||||
private _keepAlive;
|
|
||||||
private _disposed;
|
|
||||||
constructor(userAgent?: string, handlers?: ifm.IRequestHandler[], requestOptions?: ifm.IRequestOptions);
|
|
||||||
options(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
get(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
del(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
post(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
patch(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
put(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
head(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Gets a typed object from an endpoint
|
|
||||||
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
|
|
||||||
*/
|
|
||||||
getJson<T>(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
|
|
||||||
postJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
|
|
||||||
putJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
|
|
||||||
patchJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
|
|
||||||
/**
|
|
||||||
* Makes a raw http request.
|
|
||||||
* All other methods such as get, post, patch, and request ultimately call this.
|
|
||||||
* Prefer get, del, post and patch
|
|
||||||
*/
|
|
||||||
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Needs to be called if keepAlive is set to true in request options.
|
|
||||||
*/
|
|
||||||
dispose(): void;
|
|
||||||
/**
|
|
||||||
* Raw request.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
*/
|
|
||||||
requestRaw(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Raw request with callback.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
* @param onResult
|
|
||||||
*/
|
|
||||||
requestRawWithCallback(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: ifm.IHttpClientResponse) => void): void;
|
|
||||||
/**
|
|
||||||
* 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: string): http.Agent;
|
|
||||||
private _prepareRequest;
|
|
||||||
private _mergeHeaders;
|
|
||||||
private _getExistingOrDefaultHeader;
|
|
||||||
private _getAgent;
|
|
||||||
private _performExponentialBackoff;
|
|
||||||
private static dateTimeDeserializer;
|
|
||||||
private _processResponse;
|
|
||||||
}
|
|
||||||
-531
@@ -1,531 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const url = require("url");
|
|
||||||
const http = require("http");
|
|
||||||
const https = require("https");
|
|
||||||
const pm = require("./proxy");
|
|
||||||
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 : '';
|
|
||||||
}
|
|
||||||
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 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());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.HttpClientResponse = HttpClientResponse;
|
|
||||||
function isHttps(requestUrl) {
|
|
||||||
let parsedUrl = url.parse(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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
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.');
|
|
||||||
}
|
|
||||||
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 = require('tunnel');
|
|
||||||
}
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.HttpClient = HttpClient;
|
|
||||||
-50
@@ -1,50 +0,0 @@
|
|||||||
/// <reference types="node" />
|
|
||||||
import http = require('http');
|
|
||||||
import url = require('url');
|
|
||||||
export interface IHeaders {
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
export interface IHttpClient {
|
|
||||||
options(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
get(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
del(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
post(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
patch(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
put(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
requestRaw(info: IRequestInfo, data: string | NodeJS.ReadableStream): Promise<IHttpClientResponse>;
|
|
||||||
requestRawWithCallback(info: IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: IHttpClientResponse) => void): void;
|
|
||||||
}
|
|
||||||
export interface IRequestHandler {
|
|
||||||
prepareRequest(options: http.RequestOptions): void;
|
|
||||||
canHandleAuthentication(response: IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: IHttpClient, requestInfo: IRequestInfo, objs: any): Promise<IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export interface IHttpClientResponse {
|
|
||||||
message: http.IncomingMessage;
|
|
||||||
readBody(): Promise<string>;
|
|
||||||
}
|
|
||||||
export interface IRequestInfo {
|
|
||||||
options: http.RequestOptions;
|
|
||||||
parsedUrl: url.Url;
|
|
||||||
httpModule: any;
|
|
||||||
}
|
|
||||||
export interface IRequestOptions {
|
|
||||||
headers?: IHeaders;
|
|
||||||
socketTimeout?: number;
|
|
||||||
ignoreSslError?: boolean;
|
|
||||||
allowRedirects?: boolean;
|
|
||||||
allowRedirectDowngrade?: boolean;
|
|
||||||
maxRedirects?: number;
|
|
||||||
maxSockets?: number;
|
|
||||||
keepAlive?: boolean;
|
|
||||||
deserializeDates?: boolean;
|
|
||||||
allowRetries?: boolean;
|
|
||||||
maxRetries?: number;
|
|
||||||
}
|
|
||||||
export interface ITypedResponse<T> {
|
|
||||||
statusCode: number;
|
|
||||||
result: T | null;
|
|
||||||
headers: Object;
|
|
||||||
}
|
|
||||||
-2
@@ -1,2 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
-67
@@ -1,67 +0,0 @@
|
|||||||
{
|
|
||||||
"_from": "@actions/http-client@^1.0.8",
|
|
||||||
"_id": "@actions/http-client@1.0.8",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-G4JjJ6f9Hb3Zvejj+ewLLKLf99ZC+9v+yCxoYf9vSyH+WkzPLB2LuUtRMGNkooMqdugGBFStIKXOuvH1W+EctA==",
|
|
||||||
"_location": "/@actions/http-client",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "range",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "@actions/http-client@^1.0.8",
|
|
||||||
"name": "@actions/http-client",
|
|
||||||
"escapedName": "@actions%2fhttp-client",
|
|
||||||
"scope": "@actions",
|
|
||||||
"rawSpec": "^1.0.8",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "^1.0.8"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@actions/tool-cache"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.8.tgz",
|
|
||||||
"_shasum": "8bd76e8eca89dc8bcf619aa128eba85f7a39af45",
|
|
||||||
"_spec": "@actions/http-client@^1.0.8",
|
|
||||||
"_where": "/Users/aj/repos/k8s-deploy/node_modules/@actions/tool-cache",
|
|
||||||
"author": {
|
|
||||||
"name": "GitHub, Inc."
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/http-client/issues"
|
|
||||||
},
|
|
||||||
"bundleDependencies": false,
|
|
||||||
"dependencies": {
|
|
||||||
"tunnel": "0.0.6"
|
|
||||||
},
|
|
||||||
"deprecated": false,
|
|
||||||
"description": "Actions Http Client",
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/jest": "^25.1.4",
|
|
||||||
"@types/node": "^12.12.31",
|
|
||||||
"jest": "^25.1.0",
|
|
||||||
"prettier": "^2.0.4",
|
|
||||||
"proxy": "^1.0.1",
|
|
||||||
"ts-jest": "^25.2.1",
|
|
||||||
"typescript": "^3.8.3"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/actions/http-client#readme",
|
|
||||||
"keywords": [
|
|
||||||
"Actions",
|
|
||||||
"Http"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "index.js",
|
|
||||||
"name": "@actions/http-client",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/http-client.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"audit-check": "npm audit --audit-level=moderate",
|
|
||||||
"build": "rm -Rf ./_out && tsc && cp package*.json ./_out && cp *.md ./_out && cp LICENSE ./_out && cp actions.png ./_out",
|
|
||||||
"format": "prettier --write *.ts && prettier --write **/*.ts",
|
|
||||||
"format-check": "prettier --check *.ts && prettier --check **/*.ts",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"version": "1.0.8"
|
|
||||||
}
|
|
||||||
-4
@@ -1,4 +0,0 @@
|
|||||||
/// <reference types="node" />
|
|
||||||
import * as url from 'url';
|
|
||||||
export declare function getProxyUrl(reqUrl: url.Url): url.Url | undefined;
|
|
||||||
export declare function checkBypass(reqUrl: url.Url): boolean;
|
|
||||||
-58
@@ -1,58 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const url = require("url");
|
|
||||||
function getProxyUrl(reqUrl) {
|
|
||||||
let usingSsl = reqUrl.protocol === 'https:';
|
|
||||||
let proxyUrl;
|
|
||||||
if (checkBypass(reqUrl)) {
|
|
||||||
return proxyUrl;
|
|
||||||
}
|
|
||||||
let proxyVar;
|
|
||||||
if (usingSsl) {
|
|
||||||
proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
|
|
||||||
}
|
|
||||||
if (proxyVar) {
|
|
||||||
proxyUrl = url.parse(proxyVar);
|
|
||||||
}
|
|
||||||
return proxyUrl;
|
|
||||||
}
|
|
||||||
exports.getProxyUrl = getProxyUrl;
|
|
||||||
function checkBypass(reqUrl) {
|
|
||||||
if (!reqUrl.hostname) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
|
|
||||||
if (!noProxy) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Determine the request port
|
|
||||||
let reqPort;
|
|
||||||
if (reqUrl.port) {
|
|
||||||
reqPort = Number(reqUrl.port);
|
|
||||||
}
|
|
||||||
else if (reqUrl.protocol === 'http:') {
|
|
||||||
reqPort = 80;
|
|
||||||
}
|
|
||||||
else if (reqUrl.protocol === 'https:') {
|
|
||||||
reqPort = 443;
|
|
||||||
}
|
|
||||||
// Format the request hostname and hostname with port
|
|
||||||
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
|
|
||||||
if (typeof reqPort === 'number') {
|
|
||||||
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
|
|
||||||
}
|
|
||||||
// Compare request host against noproxy
|
|
||||||
for (let upperNoProxyItem of noProxy
|
|
||||||
.split(',')
|
|
||||||
.map(x => x.trim().toUpperCase())
|
|
||||||
.filter(x => x)) {
|
|
||||||
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
exports.checkBypass = checkBypass;
|
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
Copyright 2019 GitHub
|
||||||
|
|
||||||
|
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.
|
||||||
+18
-18
@@ -1,35 +1,37 @@
|
|||||||
{
|
{
|
||||||
"_from": "@actions/io@1.0.2",
|
"_args": [
|
||||||
"_id": "@actions/io@1.0.2",
|
[
|
||||||
|
"@actions/io@1.0.1",
|
||||||
|
"E:\\k8s-actions\\deploy\\k8s-deploy"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"_from": "@actions/io@1.0.1",
|
||||||
|
"_id": "@actions/io@1.0.1",
|
||||||
"_inBundle": false,
|
"_inBundle": false,
|
||||||
"_integrity": "sha512-J8KuFqVPr3p6U8W93DOXlXW6zFvrQAJANdS+vw0YhusLIq+bszW8zmK2Fh1C2kDPX8FMvwIl1OUcFgvJoXLbAg==",
|
"_integrity": "sha512-rhq+tfZukbtaus7xyUtwKfuiCRXd1hWSfmJNEpFgBQJ4woqPEpsBw04awicjwz9tyG2/MVhAEMfVn664Cri5zA==",
|
||||||
"_location": "/@actions/io",
|
"_location": "/@actions/io",
|
||||||
"_phantomChildren": {},
|
"_phantomChildren": {},
|
||||||
"_requested": {
|
"_requested": {
|
||||||
"type": "version",
|
"type": "version",
|
||||||
"registry": true,
|
"registry": true,
|
||||||
"raw": "@actions/io@1.0.2",
|
"raw": "@actions/io@1.0.1",
|
||||||
"name": "@actions/io",
|
"name": "@actions/io",
|
||||||
"escapedName": "@actions%2fio",
|
"escapedName": "@actions%2fio",
|
||||||
"scope": "@actions",
|
"scope": "@actions",
|
||||||
"rawSpec": "1.0.2",
|
"rawSpec": "1.0.1",
|
||||||
"saveSpec": null,
|
"saveSpec": null,
|
||||||
"fetchSpec": "1.0.2"
|
"fetchSpec": "1.0.1"
|
||||||
},
|
},
|
||||||
"_requiredBy": [
|
"_requiredBy": [
|
||||||
"/",
|
"/",
|
||||||
"/@actions/exec",
|
|
||||||
"/@actions/tool-cache"
|
"/@actions/tool-cache"
|
||||||
],
|
],
|
||||||
"_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.2.tgz",
|
"_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.1.tgz",
|
||||||
"_shasum": "2f614b6e69ce14d191180451eb38e6576a6e6b27",
|
"_spec": "1.0.1",
|
||||||
"_spec": "@actions/io@1.0.2",
|
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy",
|
||||||
"_where": "/Users/aj/repos/k8s-deploy",
|
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
"url": "https://github.com/actions/toolkit/issues"
|
||||||
},
|
},
|
||||||
"bundleDependencies": false,
|
|
||||||
"deprecated": false,
|
|
||||||
"description": "Actions io lib",
|
"description": "Actions io lib",
|
||||||
"directories": {
|
"directories": {
|
||||||
"lib": "lib",
|
"lib": "lib",
|
||||||
@@ -38,6 +40,7 @@
|
|||||||
"files": [
|
"files": [
|
||||||
"lib"
|
"lib"
|
||||||
],
|
],
|
||||||
|
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52",
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/io",
|
"homepage": "https://github.com/actions/toolkit/tree/master/packages/io",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"github",
|
"github",
|
||||||
@@ -52,14 +55,11 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
"url": "git+https://github.com/actions/toolkit.git"
|
||||||
"directory": "packages/io"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||||
"tsc": "tsc"
|
"tsc": "tsc"
|
||||||
},
|
},
|
||||||
"types": "lib/io.d.ts",
|
"version": "1.0.1"
|
||||||
"version": "1.0.2"
|
|
||||||
}
|
}
|
||||||
|
|||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
Copyright 2019 GitHub
|
||||||
|
|
||||||
|
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.
|
||||||
+7
-11
@@ -11,7 +11,7 @@ You can use this to download tools (or other files) from a download URL:
|
|||||||
```js
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Extract
|
#### Extract
|
||||||
@@ -22,26 +22,22 @@ These can then be extracted in platform specific ways:
|
|||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
const node12Path = tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
||||||
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
||||||
|
|
||||||
// Or alternately
|
// Or alternately
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
const node12Path = tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
||||||
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
||||||
}
|
}
|
||||||
else if (process.platform === 'darwin') {
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0.pkg');
|
|
||||||
const node12ExtractedFolder = await tc.extractXar(node12Path, 'path/to/extract/to');
|
|
||||||
}
|
|
||||||
else {
|
else {
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Cache
|
#### Cache
|
||||||
|
|
||||||
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for self-hosted runners.
|
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap).
|
||||||
|
|
||||||
You'll often want to add it to the path as part of this step:
|
You'll often want to add it to the path as part of this step:
|
||||||
|
|
||||||
@@ -49,7 +45,7 @@ You'll often want to add it to the path as part of this step:
|
|||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
const core = require('@actions/core');
|
const core = require('@actions/core');
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||||
|
|
||||||
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
||||||
@@ -61,7 +57,7 @@ You can also cache files for reuse.
|
|||||||
```js
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
const cachedPath = await tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Find
|
#### Find
|
||||||
|
|||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
export interface IToolReleaseFile {
|
|
||||||
filename: string;
|
|
||||||
platform: string;
|
|
||||||
platform_version?: string;
|
|
||||||
arch: string;
|
|
||||||
download_url: string;
|
|
||||||
}
|
|
||||||
export interface IToolRelease {
|
|
||||||
version: string;
|
|
||||||
stable: boolean;
|
|
||||||
release_url: string;
|
|
||||||
files: IToolReleaseFile[];
|
|
||||||
}
|
|
||||||
export declare function _findMatch(versionSpec: string, stable: boolean, candidates: IToolRelease[], archFilter: string): Promise<IToolRelease | undefined>;
|
|
||||||
export declare function _getOsVersion(): string;
|
|
||||||
export declare function _readLinuxVersionFile(): string;
|
|
||||||
-106
@@ -1,106 +0,0 @@
|
|||||||
"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 semver = __importStar(require("semver"));
|
|
||||||
const core_1 = require("@actions/core");
|
|
||||||
// needs to be require for core node modules to be mocked
|
|
||||||
/* eslint @typescript-eslint/no-require-imports: 0 */
|
|
||||||
const os = require("os");
|
|
||||||
const cp = require("child_process");
|
|
||||||
const fs = require("fs");
|
|
||||||
function _findMatch(versionSpec, stable, candidates, archFilter) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const platFilter = os.platform();
|
|
||||||
let result;
|
|
||||||
let match;
|
|
||||||
let file;
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
const version = candidate.version;
|
|
||||||
core_1.debug(`check ${version} satisfies ${versionSpec}`);
|
|
||||||
if (semver.satisfies(version, versionSpec) &&
|
|
||||||
(!stable || candidate.stable === stable)) {
|
|
||||||
file = candidate.files.find(item => {
|
|
||||||
core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
|
|
||||||
let chk = item.arch === archFilter && item.platform === platFilter;
|
|
||||||
if (chk && item.platform_version) {
|
|
||||||
const osVersion = module.exports._getOsVersion();
|
|
||||||
if (osVersion === item.platform_version) {
|
|
||||||
chk = true;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
chk = semver.satisfies(osVersion, item.platform_version);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return chk;
|
|
||||||
});
|
|
||||||
if (file) {
|
|
||||||
core_1.debug(`matched ${candidate.version}`);
|
|
||||||
match = candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (match && file) {
|
|
||||||
// clone since we're mutating the file list to be only the file that matches
|
|
||||||
result = Object.assign({}, match);
|
|
||||||
result.files = [file];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports._findMatch = _findMatch;
|
|
||||||
function _getOsVersion() {
|
|
||||||
// TODO: add windows and other linux, arm variants
|
|
||||||
// right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python)
|
|
||||||
const plat = os.platform();
|
|
||||||
let version = '';
|
|
||||||
if (plat === 'darwin') {
|
|
||||||
version = cp.execSync('sw_vers -productVersion').toString();
|
|
||||||
}
|
|
||||||
else if (plat === 'linux') {
|
|
||||||
// lsb_release process not in some containers, readfile
|
|
||||||
// Run cat /etc/lsb-release
|
|
||||||
// DISTRIB_ID=Ubuntu
|
|
||||||
// DISTRIB_RELEASE=18.04
|
|
||||||
// DISTRIB_CODENAME=bionic
|
|
||||||
// DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS"
|
|
||||||
const lsbContents = module.exports._readLinuxVersionFile();
|
|
||||||
if (lsbContents) {
|
|
||||||
const lines = lsbContents.split('\n');
|
|
||||||
for (const line of lines) {
|
|
||||||
const parts = line.split('=');
|
|
||||||
if (parts.length === 2 && parts[0].trim() === 'DISTRIB_RELEASE') {
|
|
||||||
version = parts[1].trim();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return version;
|
|
||||||
}
|
|
||||||
exports._getOsVersion = _getOsVersion;
|
|
||||||
function _readLinuxVersionFile() {
|
|
||||||
const lsbFile = '/etc/lsb-release';
|
|
||||||
let contents = '';
|
|
||||||
if (fs.existsSync(lsbFile)) {
|
|
||||||
contents = fs.readFileSync(lsbFile).toString();
|
|
||||||
}
|
|
||||||
return contents;
|
|
||||||
}
|
|
||||||
exports._readLinuxVersionFile = _readLinuxVersionFile;
|
|
||||||
//# sourceMappingURL=manifest.js.map
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAChC,wCAAmC;AAEnC,yDAAyD;AACzD,qDAAqD;AAErD,yBAAyB;AACzB,oCAAoC;AACpC,yBAAyB;AAqDzB,SAAsB,UAAU,CAC9B,WAAmB,EACnB,MAAe,EACf,UAA0B,EAC1B,UAAkB;;QAElB,MAAM,UAAU,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAA;QAEhC,IAAI,MAAgC,CAAA;QACpC,IAAI,KAA+B,CAAA;QAEnC,IAAI,IAAkC,CAAA;QACtC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAA;YAEjC,YAAK,CAAC,SAAS,OAAO,cAAc,WAAW,EAAE,CAAC,CAAA;YAClD,IACE,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC;gBACtC,CAAC,CAAC,MAAM,IAAI,SAAS,CAAC,MAAM,KAAK,MAAM,CAAC,EACxC;gBACA,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;oBACjC,YAAK,CACH,GAAG,IAAI,CAAC,IAAI,MAAM,UAAU,OAAO,IAAI,CAAC,QAAQ,MAAM,UAAU,EAAE,CACnE,CAAA;oBAED,IAAI,GAAG,GAAG,IAAI,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAA;oBAClE,IAAI,GAAG,IAAI,IAAI,CAAC,gBAAgB,EAAE;wBAChC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAA;wBAEhD,IAAI,SAAS,KAAK,IAAI,CAAC,gBAAgB,EAAE;4BACvC,GAAG,GAAG,IAAI,CAAA;yBACX;6BAAM;4BACL,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAA;yBACzD;qBACF;oBAED,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBAEF,IAAI,IAAI,EAAE;oBACR,YAAK,CAAC,WAAW,SAAS,CAAC,OAAO,EAAE,CAAC,CAAA;oBACrC,KAAK,GAAG,SAAS,CAAA;oBACjB,MAAK;iBACN;aACF;SACF;QAED,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,4EAA4E;YAC5E,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;YACjC,MAAM,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,CAAA;SACtB;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAtDD,gCAsDC;AAED,SAAgB,aAAa;IAC3B,kDAAkD;IAClD,6GAA6G;IAC7G,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAA;IAC1B,IAAI,OAAO,GAAG,EAAE,CAAA;IAEhB,IAAI,IAAI,KAAK,QAAQ,EAAE;QACrB,OAAO,GAAG,EAAE,CAAC,QAAQ,CAAC,yBAAyB,CAAC,CAAC,QAAQ,EAAE,CAAA;KAC5D;SAAM,IAAI,IAAI,KAAK,OAAO,EAAE;QAC3B,uDAAuD;QACvD,2BAA2B;QAC3B,oBAAoB;QACpB,wBAAwB;QACxB,0BAA0B;QAC1B,2CAA2C;QAC3C,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAA;QAC1D,IAAI,WAAW,EAAE;YACf,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;YACrC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;gBACxB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;gBAC7B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,iBAAiB,EAAE;oBAC/D,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;oBACzB,MAAK;iBACN;aACF;SACF;KACF;IAED,OAAO,OAAO,CAAA;AAChB,CAAC;AA7BD,sCA6BC;AAED,SAAgB,qBAAqB;IACnC,MAAM,OAAO,GAAG,kBAAkB,CAAA;IAClC,IAAI,QAAQ,GAAG,EAAE,CAAA;IAEjB,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;QAC1B,QAAQ,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;KAC/C;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC;AATD,sDASC"}
|
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
/**
|
|
||||||
* Internal class for retries
|
|
||||||
*/
|
|
||||||
export declare class RetryHelper {
|
|
||||||
private maxAttempts;
|
|
||||||
private minSeconds;
|
|
||||||
private maxSeconds;
|
|
||||||
constructor(maxAttempts: number, minSeconds: number, maxSeconds: number);
|
|
||||||
execute<T>(action: () => Promise<T>, isRetryable?: (e: Error) => boolean): Promise<T>;
|
|
||||||
private getSleepAmount;
|
|
||||||
private sleep;
|
|
||||||
}
|
|
||||||
-70
@@ -1,70 +0,0 @@
|
|||||||
"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(require("@actions/core"));
|
|
||||||
/**
|
|
||||||
* Internal class for retries
|
|
||||||
*/
|
|
||||||
class RetryHelper {
|
|
||||||
constructor(maxAttempts, minSeconds, maxSeconds) {
|
|
||||||
if (maxAttempts < 1) {
|
|
||||||
throw new Error('max attempts should be greater than or equal to 1');
|
|
||||||
}
|
|
||||||
this.maxAttempts = maxAttempts;
|
|
||||||
this.minSeconds = Math.floor(minSeconds);
|
|
||||||
this.maxSeconds = Math.floor(maxSeconds);
|
|
||||||
if (this.minSeconds > this.maxSeconds) {
|
|
||||||
throw new Error('min seconds should be less than or equal to max seconds');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
execute(action, isRetryable) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let attempt = 1;
|
|
||||||
while (attempt < this.maxAttempts) {
|
|
||||||
// Try
|
|
||||||
try {
|
|
||||||
return yield action();
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
if (isRetryable && !isRetryable(err)) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
core.info(err.message);
|
|
||||||
}
|
|
||||||
// Sleep
|
|
||||||
const seconds = this.getSleepAmount();
|
|
||||||
core.info(`Waiting ${seconds} seconds before trying again`);
|
|
||||||
yield this.sleep(seconds);
|
|
||||||
attempt++;
|
|
||||||
}
|
|
||||||
// Last attempt
|
|
||||||
return yield action();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
getSleepAmount() {
|
|
||||||
return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) +
|
|
||||||
this.minSeconds);
|
|
||||||
}
|
|
||||||
sleep(seconds) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.RetryHelper = RetryHelper;
|
|
||||||
//# sourceMappingURL=retry-helper.js.map
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
{"version":3,"file":"retry-helper.js","sourceRoot":"","sources":["../src/retry-helper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC;;GAEG;AACH,MAAa,WAAW;IAKtB,YAAY,WAAmB,EAAE,UAAkB,EAAE,UAAkB;QACrE,IAAI,WAAW,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;SACrE;QAED,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;IACH,CAAC;IAEK,OAAO,CACX,MAAwB,EACxB,WAAmC;;YAEnC,IAAI,OAAO,GAAG,CAAC,CAAA;YACf,OAAO,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE;gBACjC,MAAM;gBACN,IAAI;oBACF,OAAO,MAAM,MAAM,EAAE,CAAA;iBACtB;gBAAC,OAAO,GAAG,EAAE;oBACZ,IAAI,WAAW,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE;wBACpC,MAAM,GAAG,CAAA;qBACV;oBAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;iBACvB;gBAED,QAAQ;gBACR,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,EAAE,CAAA;gBACrC,IAAI,CAAC,IAAI,CAAC,WAAW,OAAO,8BAA8B,CAAC,CAAA;gBAC3D,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;gBACzB,OAAO,EAAE,CAAA;aACV;YAED,eAAe;YACf,OAAO,MAAM,MAAM,EAAE,CAAA;QACvB,CAAC;KAAA;IAEO,cAAc;QACpB,OAAO,CACL,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;YACnE,IAAI,CAAC,UAAU,CAChB,CAAA;IACH,CAAC;IAEa,KAAK,CAAC,OAAe;;YACjC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAA;QACpE,CAAC;KAAA;CACF;AAxDD,kCAwDC"}
|
|
||||||
+4
-20
@@ -1,4 +1,3 @@
|
|||||||
import * as mm from './manifest';
|
|
||||||
export declare class HTTPError extends Error {
|
export declare class HTTPError extends Error {
|
||||||
readonly httpStatusCode: number | undefined;
|
readonly httpStatusCode: number | undefined;
|
||||||
constructor(httpStatusCode: number | undefined);
|
constructor(httpStatusCode: number | undefined);
|
||||||
@@ -7,11 +6,9 @@ export declare class HTTPError extends Error {
|
|||||||
* Download a tool from an url and stream it into a file
|
* Download a tool from an url and stream it into a file
|
||||||
*
|
*
|
||||||
* @param url url of tool to download
|
* @param url url of tool to download
|
||||||
* @param dest path to download tool
|
|
||||||
* @param auth authorization header
|
|
||||||
* @returns path to downloaded tool
|
* @returns path to downloaded tool
|
||||||
*/
|
*/
|
||||||
export declare function downloadTool(url: string, dest?: string, auth?: string): Promise<string>;
|
export declare function downloadTool(url: string): Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Extract a .7z file
|
* Extract a .7z file
|
||||||
*
|
*
|
||||||
@@ -29,23 +26,14 @@ export declare function downloadTool(url: string, dest?: string, auth?: string):
|
|||||||
*/
|
*/
|
||||||
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Extract a compressed tar archive
|
* Extract a tar
|
||||||
*
|
*
|
||||||
* @param file path to the tar
|
* @param file path to the tar
|
||||||
* @param dest destination directory. Optional.
|
* @param dest destination directory. Optional.
|
||||||
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
|
* @param flags flags for the tar. Optional.
|
||||||
* @returns path to the destination directory
|
* @returns path to the destination directory
|
||||||
*/
|
*/
|
||||||
export declare function extractTar(file: string, dest?: string, flags?: string | string[]): Promise<string>;
|
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>;
|
||||||
/**
|
|
||||||
* Extract a xar compatible archive
|
|
||||||
*
|
|
||||||
* @param file path to the archive
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param flags flags for the xar. Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
export declare function extractXar(file: string, dest?: string, flags?: string | string[]): Promise<string>;
|
|
||||||
/**
|
/**
|
||||||
* Extract a zip
|
* Extract a zip
|
||||||
*
|
*
|
||||||
@@ -89,7 +77,3 @@ export declare function find(toolName: string, versionSpec: string, arch?: strin
|
|||||||
* @param arch optional arch. defaults to arch of computer
|
* @param arch optional arch. defaults to arch of computer
|
||||||
*/
|
*/
|
||||||
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
||||||
export declare type IToolRelease = mm.IToolRelease;
|
|
||||||
export declare type IToolReleaseFile = mm.IToolReleaseFile;
|
|
||||||
export declare function getManifestFromRepo(owner: string, repo: string, auth?: string, branch?: string): Promise<IToolRelease[]>;
|
|
||||||
export declare function findFromManifest(versionSpec: string, stable: boolean, manifest: IToolRelease[], archFilter?: string): Promise<IToolRelease | undefined>;
|
|
||||||
|
|||||||
+103
-260
@@ -8,31 +8,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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;
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const core = __importStar(require("@actions/core"));
|
const core = require("@actions/core");
|
||||||
const io = __importStar(require("@actions/io"));
|
const io = require("@actions/io");
|
||||||
const fs = __importStar(require("fs"));
|
const fs = require("fs");
|
||||||
const mm = __importStar(require("./manifest"));
|
const os = require("os");
|
||||||
const os = __importStar(require("os"));
|
const path = require("path");
|
||||||
const path = __importStar(require("path"));
|
const httpm = require("typed-rest-client/HttpClient");
|
||||||
const httpm = __importStar(require("@actions/http-client"));
|
const semver = require("semver");
|
||||||
const semver = __importStar(require("semver"));
|
const uuidV4 = require("uuid/v4");
|
||||||
const stream = __importStar(require("stream"));
|
|
||||||
const util = __importStar(require("util"));
|
|
||||||
const v4_1 = __importDefault(require("uuid/v4"));
|
|
||||||
const exec_1 = require("@actions/exec/lib/exec");
|
const exec_1 = require("@actions/exec/lib/exec");
|
||||||
const assert_1 = require("assert");
|
const assert_1 = require("assert");
|
||||||
const retry_helper_1 = require("./retry-helper");
|
|
||||||
class HTTPError extends Error {
|
class HTTPError extends Error {
|
||||||
constructor(httpStatusCode) {
|
constructor(httpStatusCode) {
|
||||||
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
||||||
@@ -42,90 +28,86 @@ class HTTPError extends Error {
|
|||||||
}
|
}
|
||||||
exports.HTTPError = HTTPError;
|
exports.HTTPError = HTTPError;
|
||||||
const IS_WINDOWS = process.platform === 'win32';
|
const IS_WINDOWS = process.platform === 'win32';
|
||||||
const IS_MAC = process.platform === 'darwin';
|
|
||||||
const userAgent = 'actions/tool-cache';
|
const userAgent = 'actions/tool-cache';
|
||||||
|
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
|
||||||
|
let tempDirectory = process.env['RUNNER_TEMP'] || '';
|
||||||
|
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
|
||||||
|
// If directories not found, place them in common temp locations
|
||||||
|
if (!tempDirectory || !cacheRoot) {
|
||||||
|
let baseLocation;
|
||||||
|
if (IS_WINDOWS) {
|
||||||
|
// On windows use the USERPROFILE env variable
|
||||||
|
baseLocation = process.env['USERPROFILE'] || 'C:\\';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
baseLocation = '/Users';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
baseLocation = '/home';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!tempDirectory) {
|
||||||
|
tempDirectory = path.join(baseLocation, 'actions', 'temp');
|
||||||
|
}
|
||||||
|
if (!cacheRoot) {
|
||||||
|
cacheRoot = path.join(baseLocation, 'actions', 'cache');
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Download a tool from an url and stream it into a file
|
* Download a tool from an url and stream it into a file
|
||||||
*
|
*
|
||||||
* @param url url of tool to download
|
* @param url url of tool to download
|
||||||
* @param dest path to download tool
|
|
||||||
* @param auth authorization header
|
|
||||||
* @returns path to downloaded tool
|
* @returns path to downloaded tool
|
||||||
*/
|
*/
|
||||||
function downloadTool(url, dest, auth) {
|
function downloadTool(url) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
dest = dest || path.join(_getTempDirectory(), v4_1.default());
|
// Wrap in a promise so that we can resolve from within stream callbacks
|
||||||
yield io.mkdirP(path.dirname(dest));
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||||||
core.debug(`Downloading ${url}`);
|
try {
|
||||||
core.debug(`Destination ${dest}`);
|
const http = new httpm.HttpClient(userAgent, [], {
|
||||||
const maxAttempts = 3;
|
allowRetries: true,
|
||||||
const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10);
|
maxRetries: 3
|
||||||
const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20);
|
});
|
||||||
const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
|
const destPath = path.join(tempDirectory, uuidV4());
|
||||||
return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () {
|
yield io.mkdirP(tempDirectory);
|
||||||
return yield downloadToolAttempt(url, dest || '', auth);
|
core.debug(`Downloading ${url}`);
|
||||||
}), (err) => {
|
core.debug(`Downloading ${destPath}`);
|
||||||
if (err instanceof HTTPError && err.httpStatusCode) {
|
if (fs.existsSync(destPath)) {
|
||||||
// Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests
|
throw new Error(`Destination file path ${destPath} already exists`);
|
||||||
if (err.httpStatusCode < 500 &&
|
|
||||||
err.httpStatusCode !== 408 &&
|
|
||||||
err.httpStatusCode !== 429) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
const response = yield http.get(url);
|
||||||
|
if (response.message.statusCode !== 200) {
|
||||||
|
const err = new HTTPError(response.message.statusCode);
|
||||||
|
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
const file = fs.createWriteStream(destPath);
|
||||||
|
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
|
||||||
|
try {
|
||||||
|
const stream = response.message.pipe(file);
|
||||||
|
stream.on('close', () => {
|
||||||
|
core.debug('download complete');
|
||||||
|
resolve(destPath);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
file.on('error', err => {
|
||||||
|
file.end();
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// Otherwise retry
|
catch (err) {
|
||||||
return true;
|
reject(err);
|
||||||
});
|
}
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
exports.downloadTool = downloadTool;
|
exports.downloadTool = downloadTool;
|
||||||
function downloadToolAttempt(url, dest, auth) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (fs.existsSync(dest)) {
|
|
||||||
throw new Error(`Destination file path ${dest} already exists`);
|
|
||||||
}
|
|
||||||
// Get the response headers
|
|
||||||
const http = new httpm.HttpClient(userAgent, [], {
|
|
||||||
allowRetries: false
|
|
||||||
});
|
|
||||||
let headers;
|
|
||||||
if (auth) {
|
|
||||||
core.debug('set auth');
|
|
||||||
headers = {
|
|
||||||
authorization: auth
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const response = yield http.get(url, headers);
|
|
||||||
if (response.message.statusCode !== 200) {
|
|
||||||
const err = new HTTPError(response.message.statusCode);
|
|
||||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
// Download the response body
|
|
||||||
const pipeline = util.promisify(stream.pipeline);
|
|
||||||
const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message);
|
|
||||||
const readStream = responseMessageFactory();
|
|
||||||
let succeeded = false;
|
|
||||||
try {
|
|
||||||
yield pipeline(readStream, fs.createWriteStream(dest));
|
|
||||||
core.debug('download complete');
|
|
||||||
succeeded = true;
|
|
||||||
return dest;
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
// Error, delete dest before retry
|
|
||||||
if (!succeeded) {
|
|
||||||
core.debug('download failed');
|
|
||||||
try {
|
|
||||||
yield io.rmRF(dest);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
core.debug(`Failed to delete '${dest}'. ${err.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
/**
|
||||||
* Extract a .7z file
|
* Extract a .7z file
|
||||||
*
|
*
|
||||||
@@ -145,15 +127,14 @@ function extract7z(file, dest, _7zPath) {
|
|||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
||||||
assert_1.ok(file, 'parameter "file" is required');
|
assert_1.ok(file, 'parameter "file" is required');
|
||||||
dest = yield _createExtractFolder(dest);
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
const originalCwd = process.cwd();
|
const originalCwd = process.cwd();
|
||||||
process.chdir(dest);
|
process.chdir(dest);
|
||||||
if (_7zPath) {
|
if (_7zPath) {
|
||||||
try {
|
try {
|
||||||
const logLevel = core.isDebug() ? '-bb1' : '-bb0';
|
|
||||||
const args = [
|
const args = [
|
||||||
'x',
|
'x',
|
||||||
logLevel,
|
'-bb1',
|
||||||
'-bd',
|
'-bd',
|
||||||
'-sccUTF-8',
|
'-sccUTF-8',
|
||||||
file
|
file
|
||||||
@@ -201,11 +182,11 @@ function extract7z(file, dest, _7zPath) {
|
|||||||
}
|
}
|
||||||
exports.extract7z = extract7z;
|
exports.extract7z = extract7z;
|
||||||
/**
|
/**
|
||||||
* Extract a compressed tar archive
|
* Extract a tar
|
||||||
*
|
*
|
||||||
* @param file path to the tar
|
* @param file path to the tar
|
||||||
* @param dest destination directory. Optional.
|
* @param dest destination directory. Optional.
|
||||||
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
|
* @param flags flags for the tar. Optional.
|
||||||
* @returns path to the destination directory
|
* @returns path to the destination directory
|
||||||
*/
|
*/
|
||||||
function extractTar(file, dest, flags = 'xz') {
|
function extractTar(file, dest, flags = 'xz') {
|
||||||
@@ -213,81 +194,13 @@ function extractTar(file, dest, flags = 'xz') {
|
|||||||
if (!file) {
|
if (!file) {
|
||||||
throw new Error("parameter 'file' is required");
|
throw new Error("parameter 'file' is required");
|
||||||
}
|
}
|
||||||
// Create dest
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
dest = yield _createExtractFolder(dest);
|
const tarPath = yield io.which('tar', true);
|
||||||
// Determine whether GNU tar
|
yield exec_1.exec(`"${tarPath}"`, [flags, '-C', dest, '-f', file]);
|
||||||
core.debug('Checking tar --version');
|
|
||||||
let versionOutput = '';
|
|
||||||
yield exec_1.exec('tar --version', [], {
|
|
||||||
ignoreReturnCode: true,
|
|
||||||
silent: true,
|
|
||||||
listeners: {
|
|
||||||
stdout: (data) => (versionOutput += data.toString()),
|
|
||||||
stderr: (data) => (versionOutput += data.toString())
|
|
||||||
}
|
|
||||||
});
|
|
||||||
core.debug(versionOutput.trim());
|
|
||||||
const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR');
|
|
||||||
// Initialize args
|
|
||||||
let args;
|
|
||||||
if (flags instanceof Array) {
|
|
||||||
args = flags;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
args = [flags];
|
|
||||||
}
|
|
||||||
if (core.isDebug() && !flags.includes('v')) {
|
|
||||||
args.push('-v');
|
|
||||||
}
|
|
||||||
let destArg = dest;
|
|
||||||
let fileArg = file;
|
|
||||||
if (IS_WINDOWS && isGnuTar) {
|
|
||||||
args.push('--force-local');
|
|
||||||
destArg = dest.replace(/\\/g, '/');
|
|
||||||
// Technically only the dest needs to have `/` but for aesthetic consistency
|
|
||||||
// convert slashes in the file arg too.
|
|
||||||
fileArg = file.replace(/\\/g, '/');
|
|
||||||
}
|
|
||||||
if (isGnuTar) {
|
|
||||||
// Suppress warnings when using GNU tar to extract archives created by BSD tar
|
|
||||||
args.push('--warning=no-unknown-keyword');
|
|
||||||
}
|
|
||||||
args.push('-C', destArg, '-f', fileArg);
|
|
||||||
yield exec_1.exec(`tar`, args);
|
|
||||||
return dest;
|
return dest;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
exports.extractTar = extractTar;
|
exports.extractTar = extractTar;
|
||||||
/**
|
|
||||||
* Extract a xar compatible archive
|
|
||||||
*
|
|
||||||
* @param file path to the archive
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param flags flags for the xar. Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
function extractXar(file, dest, flags = []) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
assert_1.ok(IS_MAC, 'extractXar() not supported on current OS');
|
|
||||||
assert_1.ok(file, 'parameter "file" is required');
|
|
||||||
dest = yield _createExtractFolder(dest);
|
|
||||||
let args;
|
|
||||||
if (flags instanceof Array) {
|
|
||||||
args = flags;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
args = [flags];
|
|
||||||
}
|
|
||||||
args.push('-x', '-C', dest, '-f', file);
|
|
||||||
if (core.isDebug()) {
|
|
||||||
args.push('-v');
|
|
||||||
}
|
|
||||||
const xarPath = yield io.which('xar', true);
|
|
||||||
yield exec_1.exec(`"${xarPath}"`, _unique(args));
|
|
||||||
return dest;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.extractXar = extractXar;
|
|
||||||
/**
|
/**
|
||||||
* Extract a zip
|
* Extract a zip
|
||||||
*
|
*
|
||||||
@@ -300,12 +213,17 @@ function extractZip(file, dest) {
|
|||||||
if (!file) {
|
if (!file) {
|
||||||
throw new Error("parameter 'file' is required");
|
throw new Error("parameter 'file' is required");
|
||||||
}
|
}
|
||||||
dest = yield _createExtractFolder(dest);
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
if (IS_WINDOWS) {
|
if (IS_WINDOWS) {
|
||||||
yield extractZipWin(file, dest);
|
yield extractZipWin(file, dest);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
yield extractZipNix(file, dest);
|
if (process.platform === 'darwin') {
|
||||||
|
yield extractZipDarwin(file, dest);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
yield extractZipNix(file, dest);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return dest;
|
return dest;
|
||||||
});
|
});
|
||||||
@@ -318,7 +236,7 @@ function extractZipWin(file, dest) {
|
|||||||
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||||
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
||||||
// run powershell
|
// run powershell
|
||||||
const powershellPath = yield io.which('powershell', true);
|
const powershellPath = yield io.which('powershell');
|
||||||
const args = [
|
const args = [
|
||||||
'-NoLogo',
|
'-NoLogo',
|
||||||
'-Sta',
|
'-Sta',
|
||||||
@@ -334,12 +252,14 @@ function extractZipWin(file, dest) {
|
|||||||
}
|
}
|
||||||
function extractZipNix(file, dest) {
|
function extractZipNix(file, dest) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const unzipPath = yield io.which('unzip', true);
|
const unzipPath = path.join(__dirname, '..', 'scripts', 'externals', 'unzip');
|
||||||
const args = [file];
|
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
||||||
if (!core.isDebug()) {
|
});
|
||||||
args.unshift('-q');
|
}
|
||||||
}
|
function extractZipDarwin(file, dest) {
|
||||||
yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest });
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
const unzipPath = path.join(__dirname, '..', 'scripts', 'externals', 'unzip-darwin');
|
||||||
|
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -430,7 +350,7 @@ function find(toolName, versionSpec, arch) {
|
|||||||
let toolPath = '';
|
let toolPath = '';
|
||||||
if (versionSpec) {
|
if (versionSpec) {
|
||||||
versionSpec = semver.clean(versionSpec) || '';
|
versionSpec = semver.clean(versionSpec) || '';
|
||||||
const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch);
|
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch);
|
||||||
core.debug(`checking cache: ${cachePath}`);
|
core.debug(`checking cache: ${cachePath}`);
|
||||||
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
||||||
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
||||||
@@ -452,7 +372,7 @@ exports.find = find;
|
|||||||
function findAllVersions(toolName, arch) {
|
function findAllVersions(toolName, arch) {
|
||||||
const versions = [];
|
const versions = [];
|
||||||
arch = arch || os.arch();
|
arch = arch || os.arch();
|
||||||
const toolPath = path.join(_getCacheDirectory(), toolName);
|
const toolPath = path.join(cacheRoot, toolName);
|
||||||
if (fs.existsSync(toolPath)) {
|
if (fs.existsSync(toolPath)) {
|
||||||
const children = fs.readdirSync(toolPath);
|
const children = fs.readdirSync(toolPath);
|
||||||
for (const child of children) {
|
for (const child of children) {
|
||||||
@@ -467,56 +387,11 @@ function findAllVersions(toolName, arch) {
|
|||||||
return versions;
|
return versions;
|
||||||
}
|
}
|
||||||
exports.findAllVersions = findAllVersions;
|
exports.findAllVersions = findAllVersions;
|
||||||
function getManifestFromRepo(owner, repo, auth, branch = 'master') {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let releases = [];
|
|
||||||
const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
|
|
||||||
const http = new httpm.HttpClient('tool-cache');
|
|
||||||
const headers = {};
|
|
||||||
if (auth) {
|
|
||||||
core.debug('set auth');
|
|
||||||
headers.authorization = auth;
|
|
||||||
}
|
|
||||||
const response = yield http.getJson(treeUrl, headers);
|
|
||||||
if (!response.result) {
|
|
||||||
return releases;
|
|
||||||
}
|
|
||||||
let manifestUrl = '';
|
|
||||||
for (const item of response.result.tree) {
|
|
||||||
if (item.path === 'versions-manifest.json') {
|
|
||||||
manifestUrl = item.url;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
headers['accept'] = 'application/vnd.github.VERSION.raw';
|
|
||||||
let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
|
|
||||||
if (versionsRaw) {
|
|
||||||
// shouldn't be needed but protects against invalid json saved with BOM
|
|
||||||
versionsRaw = versionsRaw.replace(/^\uFEFF/, '');
|
|
||||||
try {
|
|
||||||
releases = JSON.parse(versionsRaw);
|
|
||||||
}
|
|
||||||
catch (_a) {
|
|
||||||
core.debug('Invalid json');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return releases;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.getManifestFromRepo = getManifestFromRepo;
|
|
||||||
function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// wrap the internal impl
|
|
||||||
const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
|
|
||||||
return match;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.findFromManifest = findFromManifest;
|
|
||||||
function _createExtractFolder(dest) {
|
function _createExtractFolder(dest) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
if (!dest) {
|
if (!dest) {
|
||||||
// create a temp dir
|
// create a temp dir
|
||||||
dest = path.join(_getTempDirectory(), v4_1.default());
|
dest = path.join(tempDirectory, uuidV4());
|
||||||
}
|
}
|
||||||
yield io.mkdirP(dest);
|
yield io.mkdirP(dest);
|
||||||
return dest;
|
return dest;
|
||||||
@@ -524,7 +399,7 @@ function _createExtractFolder(dest) {
|
|||||||
}
|
}
|
||||||
function _createToolPath(tool, version, arch) {
|
function _createToolPath(tool, version, arch) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
|
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||||
core.debug(`destination ${folderPath}`);
|
core.debug(`destination ${folderPath}`);
|
||||||
const markerPath = `${folderPath}.complete`;
|
const markerPath = `${folderPath}.complete`;
|
||||||
yield io.rmRF(folderPath);
|
yield io.rmRF(folderPath);
|
||||||
@@ -534,7 +409,7 @@ function _createToolPath(tool, version, arch) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
function _completeToolPath(tool, version, arch) {
|
function _completeToolPath(tool, version, arch) {
|
||||||
const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
|
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||||
const markerPath = `${folderPath}.complete`;
|
const markerPath = `${folderPath}.complete`;
|
||||||
fs.writeFileSync(markerPath, '');
|
fs.writeFileSync(markerPath, '');
|
||||||
core.debug('finished caching tool');
|
core.debug('finished caching tool');
|
||||||
@@ -571,36 +446,4 @@ function _evaluateVersions(versions, versionSpec) {
|
|||||||
}
|
}
|
||||||
return version;
|
return version;
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Gets RUNNER_TOOL_CACHE
|
|
||||||
*/
|
|
||||||
function _getCacheDirectory() {
|
|
||||||
const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || '';
|
|
||||||
assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined');
|
|
||||||
return cacheDirectory;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Gets RUNNER_TEMP
|
|
||||||
*/
|
|
||||||
function _getTempDirectory() {
|
|
||||||
const tempDirectory = process.env['RUNNER_TEMP'] || '';
|
|
||||||
assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined');
|
|
||||||
return tempDirectory;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Gets a global variable
|
|
||||||
*/
|
|
||||||
function _getGlobal(key, defaultValue) {
|
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
||||||
const value = global[key];
|
|
||||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
||||||
return value !== undefined ? value : defaultValue;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Returns an array of unique values.
|
|
||||||
* @param values Values to make unique.
|
|
||||||
*/
|
|
||||||
function _unique(values) {
|
|
||||||
return Array.from(new Set(values));
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=tool-cache.js.map
|
//# sourceMappingURL=tool-cache.js.map
|
||||||
+1
-1
File diff suppressed because one or more lines are too long
+22
-21
@@ -1,41 +1,44 @@
|
|||||||
{
|
{
|
||||||
"_from": "@actions/tool-cache@1.6.0",
|
"_args": [
|
||||||
"_id": "@actions/tool-cache@1.6.0",
|
[
|
||||||
|
"@actions/tool-cache@1.1.1",
|
||||||
|
"E:\\k8s-actions\\deploy\\k8s-deploy"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"_from": "@actions/tool-cache@1.1.1",
|
||||||
|
"_id": "@actions/tool-cache@1.1.1",
|
||||||
"_inBundle": false,
|
"_inBundle": false,
|
||||||
"_integrity": "sha512-+fyEBImPD3m5I0o6DflCO0NHY180LPoX8Lo6y4Iez+V17kO8kfkH0VHxb8mUdmD6hn9dWA9Ch1JA20fXoIYUeQ==",
|
"_integrity": "sha512-AILekrrj/L4N/5z5TGtUKVie4nKjxDioCgOEymyYxzPhGfjIxfE71tN2VTTpiICEWJ883rPRj2+WinTr1b6yVA==",
|
||||||
"_location": "/@actions/tool-cache",
|
"_location": "/@actions/tool-cache",
|
||||||
"_phantomChildren": {},
|
"_phantomChildren": {},
|
||||||
"_requested": {
|
"_requested": {
|
||||||
"type": "version",
|
"type": "version",
|
||||||
"registry": true,
|
"registry": true,
|
||||||
"raw": "@actions/tool-cache@1.6.0",
|
"raw": "@actions/tool-cache@1.1.1",
|
||||||
"name": "@actions/tool-cache",
|
"name": "@actions/tool-cache",
|
||||||
"escapedName": "@actions%2ftool-cache",
|
"escapedName": "@actions%2ftool-cache",
|
||||||
"scope": "@actions",
|
"scope": "@actions",
|
||||||
"rawSpec": "1.6.0",
|
"rawSpec": "1.1.1",
|
||||||
"saveSpec": null,
|
"saveSpec": null,
|
||||||
"fetchSpec": "1.6.0"
|
"fetchSpec": "1.1.1"
|
||||||
},
|
},
|
||||||
"_requiredBy": [
|
"_requiredBy": [
|
||||||
"/"
|
"/"
|
||||||
],
|
],
|
||||||
"_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.6.0.tgz",
|
"_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.1.1.tgz",
|
||||||
"_shasum": "5b425db2d642df65dd0d6bcec0d84dcdbca3f80d",
|
"_spec": "1.1.1",
|
||||||
"_spec": "@actions/tool-cache@1.6.0",
|
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy",
|
||||||
"_where": "/Users/aj/repos/k8s-deploy",
|
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
"url": "https://github.com/actions/toolkit/issues"
|
||||||
},
|
},
|
||||||
"bundleDependencies": false,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.2.3",
|
"@actions/core": "^1.1.0",
|
||||||
"@actions/exec": "^1.0.0",
|
"@actions/exec": "^1.0.1",
|
||||||
"@actions/http-client": "^1.0.8",
|
|
||||||
"@actions/io": "^1.0.1",
|
"@actions/io": "^1.0.1",
|
||||||
"semver": "^6.1.0",
|
"semver": "^6.1.0",
|
||||||
|
"typed-rest-client": "^1.4.0",
|
||||||
"uuid": "^3.3.2"
|
"uuid": "^3.3.2"
|
||||||
},
|
},
|
||||||
"deprecated": false,
|
|
||||||
"description": "Actions tool-cache lib",
|
"description": "Actions tool-cache lib",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/nock": "^10.0.3",
|
"@types/nock": "^10.0.3",
|
||||||
@@ -51,7 +54,8 @@
|
|||||||
"lib",
|
"lib",
|
||||||
"scripts"
|
"scripts"
|
||||||
],
|
],
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/tool-cache",
|
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52",
|
||||||
|
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"github",
|
"github",
|
||||||
"actions",
|
"actions",
|
||||||
@@ -65,14 +69,11 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
"url": "git+https://github.com/actions/toolkit.git"
|
||||||
"directory": "packages/tool-cache"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||||
"tsc": "tsc"
|
"tsc": "tsc"
|
||||||
},
|
},
|
||||||
"types": "lib/tool-cache.d.ts",
|
"version": "1.1.1"
|
||||||
"version": "1.6.0"
|
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) Microsoft Corporation. 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
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
# Installation
|
||||||
|
> `npm install --save @types/node`
|
||||||
|
|
||||||
|
# Summary
|
||||||
|
This package contains type definitions for Node.js (http://nodejs.org/).
|
||||||
|
|
||||||
|
# Details
|
||||||
|
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node
|
||||||
|
|
||||||
|
Additional Details
|
||||||
|
* Last updated: Tue, 03 Sep 2019 18:47:08 GMT
|
||||||
|
* Dependencies: none
|
||||||
|
* Global values: Buffer, NodeJS, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, queueMicrotask, require, setImmediate, setInterval, setTimeout
|
||||||
|
|
||||||
|
# Credits
|
||||||
|
These definitions were written by Microsoft TypeScript <https://github.com/Microsoft>, DefinitelyTyped <https://github.com/DefinitelyTyped>, Alberto Schiabel <https://github.com/jkomyno>, Alexander T. <https://github.com/a-tarasyuk>, Alvis HT Tang <https://github.com/alvis>, Andrew Makarov <https://github.com/r3nya>, Benjamin Toueg <https://github.com/btoueg>, Bruno Scheufler <https://github.com/brunoscheufler>, Chigozirim C. <https://github.com/smac89>, Christian Vaagland Tellnes <https://github.com/tellnes>, David Junger <https://github.com/touffy>, Deividas Bakanas <https://github.com/DeividasBakanas>, Eugene Y. Q. Shen <https://github.com/eyqs>, Flarna <https://github.com/Flarna>, Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>, Hoàng Văn Khải <https://github.com/KSXGitHub>, Huw <https://github.com/hoo29>, Kelvin Jin <https://github.com/kjin>, Klaus Meinhardt <https://github.com/ajafff>, Lishude <https://github.com/islishude>, Mariusz Wiktorczyk <https://github.com/mwiktorczyk>, Matthieu Sieben <https://github.com/matthieusieben>, Mohsen Azimi <https://github.com/mohsen1>, Nicolas Even <https://github.com/n-e>, Nicolas Voigt <https://github.com/octo-sniffle>, Parambir Singh <https://github.com/parambirs>, Sebastian Silbermann <https://github.com/eps1lon>, Simon Schick <https://github.com/SimonSchick>, Thomas den Hollander <https://github.com/ThomasdenH>, Wilco Bakker <https://github.com/WilcoBakker>, wwwy3y3 <https://github.com/wwwy3y3>, Zane Hannan AU <https://github.com/ZaneHannanAU>, Samuel Ainsworth <https://github.com/samuela>, Kyle Uehlein <https://github.com/kuehlein>, Jordi Oliveras Rovira <https://github.com/j-oliveras>, Thanik Bhongbhibhat <https://github.com/bhongy>, and Marcin Kopacz <https://github.com/chyzwar>.
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
declare module "assert" {
|
||||||
|
function internal(value: any, message?: string | Error): void;
|
||||||
|
namespace internal {
|
||||||
|
class AssertionError implements Error {
|
||||||
|
name: string;
|
||||||
|
message: string;
|
||||||
|
actual: any;
|
||||||
|
expected: any;
|
||||||
|
operator: string;
|
||||||
|
generatedMessage: boolean;
|
||||||
|
code: 'ERR_ASSERTION';
|
||||||
|
|
||||||
|
constructor(options?: {
|
||||||
|
message?: string; actual?: any; expected?: any;
|
||||||
|
operator?: string; stackStartFn?: Function
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(message?: string | Error): never;
|
||||||
|
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
|
||||||
|
function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never;
|
||||||
|
function ok(value: any, message?: string | Error): void;
|
||||||
|
/** @deprecated since v9.9.0 - use strictEqual() instead. */
|
||||||
|
function equal(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
/** @deprecated since v9.9.0 - use notStrictEqual() instead. */
|
||||||
|
function notEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
/** @deprecated since v9.9.0 - use deepStrictEqual() instead. */
|
||||||
|
function deepEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
/** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */
|
||||||
|
function notDeepEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
function strictEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
function notStrictEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
function deepStrictEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void;
|
||||||
|
|
||||||
|
function throws(block: () => any, message?: string | Error): void;
|
||||||
|
function throws(block: () => any, error: RegExp | Function | Object | Error, message?: string | Error): void;
|
||||||
|
function doesNotThrow(block: () => any, message?: string | Error): void;
|
||||||
|
function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void;
|
||||||
|
|
||||||
|
function ifError(value: any): void;
|
||||||
|
|
||||||
|
function rejects(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
|
||||||
|
function rejects(block: (() => Promise<any>) | Promise<any>, error: RegExp | Function | Object | Error, message?: string | Error): Promise<void>;
|
||||||
|
function doesNotReject(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
|
||||||
|
function doesNotReject(block: (() => Promise<any>) | Promise<any>, error: RegExp | Function, message?: string | Error): Promise<void>;
|
||||||
|
|
||||||
|
const strict: typeof internal;
|
||||||
|
}
|
||||||
|
|
||||||
|
export = internal;
|
||||||
|
}
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
/**
|
||||||
|
* Async Hooks module: https://nodejs.org/api/async_hooks.html
|
||||||
|
*/
|
||||||
|
declare module "async_hooks" {
|
||||||
|
/**
|
||||||
|
* Returns the asyncId of the current execution context.
|
||||||
|
*/
|
||||||
|
function executionAsyncId(): number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the ID of the resource responsible for calling the callback that is currently being executed.
|
||||||
|
*/
|
||||||
|
function triggerAsyncId(): number;
|
||||||
|
|
||||||
|
interface HookCallbacks {
|
||||||
|
/**
|
||||||
|
* Called when a class is constructed that has the possibility to emit an asynchronous event.
|
||||||
|
* @param asyncId a unique ID for the async resource
|
||||||
|
* @param type the type of the async resource
|
||||||
|
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
|
||||||
|
* @param resource reference to the resource representing the async operation, needs to be released during destroy
|
||||||
|
*/
|
||||||
|
init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
|
||||||
|
* The before callback is called just before said callback is executed.
|
||||||
|
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
|
||||||
|
*/
|
||||||
|
before?(asyncId: number): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called immediately after the callback specified in before is completed.
|
||||||
|
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
|
||||||
|
*/
|
||||||
|
after?(asyncId: number): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when a promise has resolve() called. This may not be in the same execution id
|
||||||
|
* as the promise itself.
|
||||||
|
* @param asyncId the unique id for the promise that was resolve()d.
|
||||||
|
*/
|
||||||
|
promiseResolve?(asyncId: number): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called after the resource corresponding to asyncId is destroyed
|
||||||
|
* @param asyncId a unique ID for the async resource
|
||||||
|
*/
|
||||||
|
destroy?(asyncId: number): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AsyncHook {
|
||||||
|
/**
|
||||||
|
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
|
||||||
|
*/
|
||||||
|
enable(): this;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
|
||||||
|
*/
|
||||||
|
disable(): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers functions to be called for different lifetime events of each async operation.
|
||||||
|
* @param options the callbacks to register
|
||||||
|
* @return an AsyncHooks instance used for disabling and enabling hooks
|
||||||
|
*/
|
||||||
|
function createHook(options: HookCallbacks): AsyncHook;
|
||||||
|
|
||||||
|
interface AsyncResourceOptions {
|
||||||
|
/**
|
||||||
|
* The ID of the execution context that created this async event.
|
||||||
|
* Default: `executionAsyncId()`
|
||||||
|
*/
|
||||||
|
triggerAsyncId?: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disables automatic `emitDestroy` when the object is garbage collected.
|
||||||
|
* This usually does not need to be set (even if `emitDestroy` is called
|
||||||
|
* manually), unless the resource's `asyncId` is retrieved and the
|
||||||
|
* sensitive API's `emitDestroy` is called with it.
|
||||||
|
* Default: `false`
|
||||||
|
*/
|
||||||
|
requireManualDestroy?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The class AsyncResource was designed to be extended by the embedder's async resources.
|
||||||
|
* Using this users can easily trigger the lifetime events of their own resources.
|
||||||
|
*/
|
||||||
|
class AsyncResource {
|
||||||
|
/**
|
||||||
|
* AsyncResource() is meant to be extended. Instantiating a
|
||||||
|
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||||
|
* async_hook.executionAsyncId() is used.
|
||||||
|
* @param type The type of async event.
|
||||||
|
* @param triggerAsyncId The ID of the execution context that created
|
||||||
|
* this async event (default: `executionAsyncId()`), or an
|
||||||
|
* AsyncResourceOptions object (since 9.3)
|
||||||
|
*/
|
||||||
|
constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call the provided function with the provided arguments in the
|
||||||
|
* execution context of the async resource. This will establish the
|
||||||
|
* context, trigger the AsyncHooks before callbacks, call the function,
|
||||||
|
* trigger the AsyncHooks after callbacks, and then restore the original
|
||||||
|
* execution context.
|
||||||
|
* @param fn The function to call in the execution context of this
|
||||||
|
* async resource.
|
||||||
|
* @param thisArg The receiver to be used for the function call.
|
||||||
|
* @param args Optional arguments to pass to the function.
|
||||||
|
*/
|
||||||
|
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call AsyncHooks destroy callbacks.
|
||||||
|
*/
|
||||||
|
emitDestroy(): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return the unique ID assigned to this AsyncResource instance.
|
||||||
|
*/
|
||||||
|
asyncId(): number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return the trigger ID for this AsyncResource instance.
|
||||||
|
*/
|
||||||
|
triggerAsyncId(): number;
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
// base definnitions for all NodeJS modules that are not specific to any version of TypeScript
|
||||||
|
/// <reference path="globals.d.ts" />
|
||||||
|
/// <reference path="assert.d.ts" />
|
||||||
|
/// <reference path="async_hooks.d.ts" />
|
||||||
|
/// <reference path="buffer.d.ts" />
|
||||||
|
/// <reference path="child_process.d.ts" />
|
||||||
|
/// <reference path="cluster.d.ts" />
|
||||||
|
/// <reference path="console.d.ts" />
|
||||||
|
/// <reference path="constants.d.ts" />
|
||||||
|
/// <reference path="crypto.d.ts" />
|
||||||
|
/// <reference path="dgram.d.ts" />
|
||||||
|
/// <reference path="dns.d.ts" />
|
||||||
|
/// <reference path="domain.d.ts" />
|
||||||
|
/// <reference path="events.d.ts" />
|
||||||
|
/// <reference path="fs.d.ts" />
|
||||||
|
/// <reference path="http.d.ts" />
|
||||||
|
/// <reference path="http2.d.ts" />
|
||||||
|
/// <reference path="https.d.ts" />
|
||||||
|
/// <reference path="inspector.d.ts" />
|
||||||
|
/// <reference path="module.d.ts" />
|
||||||
|
/// <reference path="net.d.ts" />
|
||||||
|
/// <reference path="os.d.ts" />
|
||||||
|
/// <reference path="path.d.ts" />
|
||||||
|
/// <reference path="perf_hooks.d.ts" />
|
||||||
|
/// <reference path="process.d.ts" />
|
||||||
|
/// <reference path="punycode.d.ts" />
|
||||||
|
/// <reference path="querystring.d.ts" />
|
||||||
|
/// <reference path="readline.d.ts" />
|
||||||
|
/// <reference path="repl.d.ts" />
|
||||||
|
/// <reference path="stream.d.ts" />
|
||||||
|
/// <reference path="string_decoder.d.ts" />
|
||||||
|
/// <reference path="timers.d.ts" />
|
||||||
|
/// <reference path="tls.d.ts" />
|
||||||
|
/// <reference path="trace_events.d.ts" />
|
||||||
|
/// <reference path="tty.d.ts" />
|
||||||
|
/// <reference path="url.d.ts" />
|
||||||
|
/// <reference path="util.d.ts" />
|
||||||
|
/// <reference path="v8.d.ts" />
|
||||||
|
/// <reference path="vm.d.ts" />
|
||||||
|
/// <reference path="worker_threads.d.ts" />
|
||||||
|
/// <reference path="zlib.d.ts" />
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
declare module "buffer" {
|
||||||
|
export const INSPECT_MAX_BYTES: number;
|
||||||
|
export const kMaxLength: number;
|
||||||
|
export const kStringMaxLength: number;
|
||||||
|
export const constants: {
|
||||||
|
MAX_LENGTH: number;
|
||||||
|
MAX_STRING_LENGTH: number;
|
||||||
|
};
|
||||||
|
const BuffType: typeof Buffer;
|
||||||
|
|
||||||
|
export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary";
|
||||||
|
|
||||||
|
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
|
||||||
|
|
||||||
|
export const SlowBuffer: {
|
||||||
|
/** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */
|
||||||
|
new(size: number): Buffer;
|
||||||
|
prototype: Buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BuffType as Buffer };
|
||||||
|
}
|
||||||
+478
@@ -0,0 +1,478 @@
|
|||||||
|
declare module "child_process" {
|
||||||
|
import * as events from "events";
|
||||||
|
import * as net from "net";
|
||||||
|
import { Writable, Readable, Stream, Pipe } from "stream";
|
||||||
|
|
||||||
|
interface ChildProcess extends events.EventEmitter {
|
||||||
|
stdin: Writable | null;
|
||||||
|
stdout: Readable | null;
|
||||||
|
stderr: Readable | null;
|
||||||
|
readonly channel?: Pipe | null;
|
||||||
|
readonly stdio: [
|
||||||
|
Writable | null, // stdin
|
||||||
|
Readable | null, // stdout
|
||||||
|
Readable | null, // stderr
|
||||||
|
Readable | Writable | null | undefined, // extra
|
||||||
|
Readable | Writable | null | undefined // extra
|
||||||
|
];
|
||||||
|
readonly killed: boolean;
|
||||||
|
readonly pid: number;
|
||||||
|
readonly connected: boolean;
|
||||||
|
kill(signal?: string): void;
|
||||||
|
send(message: any, callback?: (error: Error | null) => void): boolean;
|
||||||
|
send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error | null) => void): boolean;
|
||||||
|
send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error | null) => void): boolean;
|
||||||
|
disconnect(): void;
|
||||||
|
unref(): void;
|
||||||
|
ref(): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* events.EventEmitter
|
||||||
|
* 1. close
|
||||||
|
* 2. disconnect
|
||||||
|
* 3. error
|
||||||
|
* 4. exit
|
||||||
|
* 5. message
|
||||||
|
*/
|
||||||
|
|
||||||
|
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
addListener(event: "close", listener: (code: number, signal: string) => void): this;
|
||||||
|
addListener(event: "disconnect", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
|
||||||
|
addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this;
|
||||||
|
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
emit(event: "close", code: number, signal: string): boolean;
|
||||||
|
emit(event: "disconnect"): boolean;
|
||||||
|
emit(event: "error", err: Error): boolean;
|
||||||
|
emit(event: "exit", code: number | null, signal: string | null): boolean;
|
||||||
|
emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean;
|
||||||
|
|
||||||
|
on(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
on(event: "close", listener: (code: number, signal: string) => void): this;
|
||||||
|
on(event: "disconnect", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (err: Error) => void): this;
|
||||||
|
on(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
|
||||||
|
on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this;
|
||||||
|
|
||||||
|
once(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
once(event: "close", listener: (code: number, signal: string) => void): this;
|
||||||
|
once(event: "disconnect", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (err: Error) => void): this;
|
||||||
|
once(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
|
||||||
|
once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependListener(event: "close", listener: (code: number, signal: string) => void): this;
|
||||||
|
prependListener(event: "disconnect", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
|
||||||
|
prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this;
|
||||||
|
prependOnceListener(event: "disconnect", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
|
||||||
|
prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// return this object when stdio option is undefined or not specified
|
||||||
|
interface ChildProcessWithoutNullStreams extends ChildProcess {
|
||||||
|
stdin: Writable;
|
||||||
|
stdout: Readable;
|
||||||
|
stderr: Readable;
|
||||||
|
readonly stdio: [
|
||||||
|
Writable, // stdin
|
||||||
|
Readable, // stdout
|
||||||
|
Readable, // stderr
|
||||||
|
Readable | Writable | null | undefined, // extra, no modification
|
||||||
|
Readable | Writable | null | undefined // extra, no modification
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// return this object when stdio option is a tuple of 3
|
||||||
|
interface ChildProcessByStdio<
|
||||||
|
I extends null | Writable,
|
||||||
|
O extends null | Readable,
|
||||||
|
E extends null | Readable,
|
||||||
|
> extends ChildProcess {
|
||||||
|
stdin: I;
|
||||||
|
stdout: O;
|
||||||
|
stderr: E;
|
||||||
|
readonly stdio: [
|
||||||
|
I,
|
||||||
|
O,
|
||||||
|
E,
|
||||||
|
Readable | Writable | null | undefined, // extra, no modification
|
||||||
|
Readable | Writable | null | undefined // extra, no modification
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MessageOptions {
|
||||||
|
keepOpen?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>;
|
||||||
|
|
||||||
|
interface ProcessEnvOptions {
|
||||||
|
uid?: number;
|
||||||
|
gid?: number;
|
||||||
|
cwd?: string;
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CommonOptions extends ProcessEnvOptions {
|
||||||
|
/**
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
windowsHide?: boolean;
|
||||||
|
/**
|
||||||
|
* @default 0
|
||||||
|
*/
|
||||||
|
timeout?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpawnOptions extends CommonOptions {
|
||||||
|
argv0?: string;
|
||||||
|
stdio?: StdioOptions;
|
||||||
|
detached?: boolean;
|
||||||
|
shell?: boolean | string;
|
||||||
|
windowsVerbatimArguments?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpawnOptionsWithoutStdio extends SpawnOptions {
|
||||||
|
stdio?: 'pipe' | Array<null | undefined | 'pipe'>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type StdioNull = 'inherit' | 'ignore' | Stream;
|
||||||
|
type StdioPipe = undefined | null | 'pipe';
|
||||||
|
|
||||||
|
interface SpawnOptionsWithStdioTuple<
|
||||||
|
Stdin extends StdioNull | StdioPipe,
|
||||||
|
Stdout extends StdioNull | StdioPipe,
|
||||||
|
Stderr extends StdioNull | StdioPipe,
|
||||||
|
> extends SpawnOptions {
|
||||||
|
stdio: [Stdin, Stdout, Stderr];
|
||||||
|
}
|
||||||
|
|
||||||
|
// overloads of spawn without 'args'
|
||||||
|
function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
|
||||||
|
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<Writable, Readable, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
|
||||||
|
): ChildProcessByStdio<Writable, Readable, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<Writable, null, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<null, Readable, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
|
||||||
|
): ChildProcessByStdio<Writable, null, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
|
||||||
|
): ChildProcessByStdio<null, Readable, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<null, null, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
|
||||||
|
): ChildProcessByStdio<null, null, null>;
|
||||||
|
|
||||||
|
function spawn(command: string, options: SpawnOptions): ChildProcess;
|
||||||
|
|
||||||
|
// overloads of spawn with 'args'
|
||||||
|
function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
|
||||||
|
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<Writable, Readable, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
|
||||||
|
): ChildProcessByStdio<Writable, Readable, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<Writable, null, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<null, Readable, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
|
||||||
|
): ChildProcessByStdio<Writable, null, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
|
||||||
|
): ChildProcessByStdio<null, Readable, null>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
|
||||||
|
): ChildProcessByStdio<null, null, Readable>;
|
||||||
|
function spawn(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
|
||||||
|
): ChildProcessByStdio<null, null, null>;
|
||||||
|
|
||||||
|
function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptions): ChildProcess;
|
||||||
|
|
||||||
|
interface ExecOptions extends CommonOptions {
|
||||||
|
shell?: string;
|
||||||
|
maxBuffer?: number;
|
||||||
|
killSignal?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExecOptionsWithStringEncoding extends ExecOptions {
|
||||||
|
encoding: BufferEncoding;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExecOptionsWithBufferEncoding extends ExecOptions {
|
||||||
|
encoding: string | null; // specify `null`.
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExecException extends Error {
|
||||||
|
cmd?: string;
|
||||||
|
killed?: boolean;
|
||||||
|
code?: number;
|
||||||
|
signal?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no `options` definitely means stdout/stderr are `string`.
|
||||||
|
function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
|
||||||
|
function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with well known `encoding` means stdout/stderr are definitely `string`.
|
||||||
|
function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
|
||||||
|
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
|
||||||
|
function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess;
|
||||||
|
|
||||||
|
// `options` without an `encoding` means stdout/stderr are definitely `string`.
|
||||||
|
function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
|
||||||
|
// fallback if nothing else matches. Worst case is always `string | Buffer`.
|
||||||
|
function exec(
|
||||||
|
command: string,
|
||||||
|
options: ({ encoding?: string | null } & ExecOptions) | undefined | null,
|
||||||
|
callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
|
||||||
|
): ChildProcess;
|
||||||
|
|
||||||
|
interface PromiseWithChild<T> extends Promise<T> {
|
||||||
|
child: ChildProcess;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace exec {
|
||||||
|
function __promisify__(command: string): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
|
||||||
|
function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExecFileOptions extends CommonOptions {
|
||||||
|
maxBuffer?: number;
|
||||||
|
killSignal?: string;
|
||||||
|
windowsVerbatimArguments?: boolean;
|
||||||
|
shell?: boolean | string;
|
||||||
|
}
|
||||||
|
interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
|
||||||
|
encoding: BufferEncoding;
|
||||||
|
}
|
||||||
|
interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
|
||||||
|
encoding: 'buffer' | null;
|
||||||
|
}
|
||||||
|
interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {
|
||||||
|
encoding: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function execFile(file: string): ChildProcess;
|
||||||
|
function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess;
|
||||||
|
function execFile(file: string, args?: ReadonlyArray<string> | null): ChildProcess;
|
||||||
|
function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess;
|
||||||
|
|
||||||
|
// no `options` definitely means stdout/stderr are `string`.
|
||||||
|
function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
function execFile(file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
|
||||||
|
function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
args: ReadonlyArray<string> | undefined | null,
|
||||||
|
options: ExecFileOptionsWithBufferEncoding,
|
||||||
|
callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
|
||||||
|
): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with well known `encoding` means stdout/stderr are definitely `string`.
|
||||||
|
function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
args: ReadonlyArray<string> | undefined | null,
|
||||||
|
options: ExecFileOptionsWithStringEncoding,
|
||||||
|
callback: (error: Error | null, stdout: string, stderr: string) => void,
|
||||||
|
): ChildProcess;
|
||||||
|
|
||||||
|
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
|
||||||
|
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
options: ExecFileOptionsWithOtherEncoding,
|
||||||
|
callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void,
|
||||||
|
): ChildProcess;
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
args: ReadonlyArray<string> | undefined | null,
|
||||||
|
options: ExecFileOptionsWithOtherEncoding,
|
||||||
|
callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void,
|
||||||
|
): ChildProcess;
|
||||||
|
|
||||||
|
// `options` without an `encoding` means stdout/stderr are definitely `string`.
|
||||||
|
function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess;
|
||||||
|
|
||||||
|
// fallback if nothing else matches. Worst case is always `string | Buffer`.
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null,
|
||||||
|
callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null,
|
||||||
|
): ChildProcess;
|
||||||
|
function execFile(
|
||||||
|
file: string,
|
||||||
|
args: ReadonlyArray<string> | undefined | null,
|
||||||
|
options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null,
|
||||||
|
callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null,
|
||||||
|
): ChildProcess;
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace execFile {
|
||||||
|
function __promisify__(file: string): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, args: string[] | undefined | null): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
|
||||||
|
function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
|
||||||
|
function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
|
||||||
|
function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
|
||||||
|
function __promisify__(file: string, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
|
||||||
|
function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
|
||||||
|
function __promisify__(
|
||||||
|
file: string,
|
||||||
|
args: string[] | undefined | null,
|
||||||
|
options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null,
|
||||||
|
): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ForkOptions extends ProcessEnvOptions {
|
||||||
|
execPath?: string;
|
||||||
|
execArgv?: string[];
|
||||||
|
silent?: boolean;
|
||||||
|
stdio?: StdioOptions;
|
||||||
|
detached?: boolean;
|
||||||
|
windowsVerbatimArguments?: boolean;
|
||||||
|
}
|
||||||
|
function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess;
|
||||||
|
|
||||||
|
interface SpawnSyncOptions extends CommonOptions {
|
||||||
|
argv0?: string; // Not specified in the docs
|
||||||
|
input?: string | NodeJS.TypedArray | DataView;
|
||||||
|
stdio?: StdioOptions;
|
||||||
|
killSignal?: string | number;
|
||||||
|
maxBuffer?: number;
|
||||||
|
encoding?: string;
|
||||||
|
shell?: boolean | string;
|
||||||
|
windowsVerbatimArguments?: boolean;
|
||||||
|
}
|
||||||
|
interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {
|
||||||
|
encoding: BufferEncoding;
|
||||||
|
}
|
||||||
|
interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {
|
||||||
|
encoding: string; // specify `null`.
|
||||||
|
}
|
||||||
|
interface SpawnSyncReturns<T> {
|
||||||
|
pid: number;
|
||||||
|
output: string[];
|
||||||
|
stdout: T;
|
||||||
|
stderr: T;
|
||||||
|
status: number | null;
|
||||||
|
signal: string | null;
|
||||||
|
error?: Error;
|
||||||
|
}
|
||||||
|
function spawnSync(command: string): SpawnSyncReturns<Buffer>;
|
||||||
|
function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
|
||||||
|
function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
|
||||||
|
function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;
|
||||||
|
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
|
||||||
|
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
|
||||||
|
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;
|
||||||
|
|
||||||
|
interface ExecSyncOptions extends CommonOptions {
|
||||||
|
input?: string | Uint8Array;
|
||||||
|
stdio?: StdioOptions;
|
||||||
|
shell?: string;
|
||||||
|
killSignal?: string | number;
|
||||||
|
maxBuffer?: number;
|
||||||
|
encoding?: string;
|
||||||
|
}
|
||||||
|
interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions {
|
||||||
|
encoding: BufferEncoding;
|
||||||
|
}
|
||||||
|
interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions {
|
||||||
|
encoding: string; // specify `null`.
|
||||||
|
}
|
||||||
|
function execSync(command: string): Buffer;
|
||||||
|
function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string;
|
||||||
|
function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer;
|
||||||
|
function execSync(command: string, options?: ExecSyncOptions): Buffer;
|
||||||
|
|
||||||
|
interface ExecFileSyncOptions extends CommonOptions {
|
||||||
|
input?: string | NodeJS.TypedArray | DataView;
|
||||||
|
stdio?: StdioOptions;
|
||||||
|
killSignal?: string | number;
|
||||||
|
maxBuffer?: number;
|
||||||
|
encoding?: string;
|
||||||
|
shell?: boolean | string;
|
||||||
|
}
|
||||||
|
interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions {
|
||||||
|
encoding: BufferEncoding;
|
||||||
|
}
|
||||||
|
interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {
|
||||||
|
encoding: string; // specify `null`.
|
||||||
|
}
|
||||||
|
function execFileSync(command: string): Buffer;
|
||||||
|
function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string;
|
||||||
|
function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
|
||||||
|
function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer;
|
||||||
|
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithStringEncoding): string;
|
||||||
|
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
|
||||||
|
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptions): Buffer;
|
||||||
|
}
|
||||||
+260
@@ -0,0 +1,260 @@
|
|||||||
|
declare module "cluster" {
|
||||||
|
import * as child from "child_process";
|
||||||
|
import * as events from "events";
|
||||||
|
import * as net from "net";
|
||||||
|
|
||||||
|
// interfaces
|
||||||
|
interface ClusterSettings {
|
||||||
|
execArgv?: string[]; // default: process.execArgv
|
||||||
|
exec?: string;
|
||||||
|
args?: string[];
|
||||||
|
silent?: boolean;
|
||||||
|
stdio?: any[];
|
||||||
|
uid?: number;
|
||||||
|
gid?: number;
|
||||||
|
inspectPort?: number | (() => number);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Address {
|
||||||
|
address: string;
|
||||||
|
port: number;
|
||||||
|
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6"
|
||||||
|
}
|
||||||
|
|
||||||
|
class Worker extends events.EventEmitter {
|
||||||
|
id: number;
|
||||||
|
process: child.ChildProcess;
|
||||||
|
send(message: any, sendHandle?: any, callback?: (error: Error | null) => void): boolean;
|
||||||
|
kill(signal?: string): void;
|
||||||
|
destroy(signal?: string): void;
|
||||||
|
disconnect(): void;
|
||||||
|
isConnected(): boolean;
|
||||||
|
isDead(): boolean;
|
||||||
|
exitedAfterDisconnect: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* events.EventEmitter
|
||||||
|
* 1. disconnect
|
||||||
|
* 2. error
|
||||||
|
* 3. exit
|
||||||
|
* 4. listening
|
||||||
|
* 5. message
|
||||||
|
* 6. online
|
||||||
|
*/
|
||||||
|
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
addListener(event: "disconnect", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||||
|
addListener(event: "listening", listener: (address: Address) => void): this;
|
||||||
|
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
addListener(event: "online", listener: () => void): this;
|
||||||
|
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
emit(event: "disconnect"): boolean;
|
||||||
|
emit(event: "error", error: Error): boolean;
|
||||||
|
emit(event: "exit", code: number, signal: string): boolean;
|
||||||
|
emit(event: "listening", address: Address): boolean;
|
||||||
|
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
|
||||||
|
emit(event: "online"): boolean;
|
||||||
|
|
||||||
|
on(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
on(event: "disconnect", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (error: Error) => void): this;
|
||||||
|
on(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||||
|
on(event: "listening", listener: (address: Address) => void): this;
|
||||||
|
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
on(event: "online", listener: () => void): this;
|
||||||
|
|
||||||
|
once(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
once(event: "disconnect", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (error: Error) => void): this;
|
||||||
|
once(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||||
|
once(event: "listening", listener: (address: Address) => void): this;
|
||||||
|
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
once(event: "online", listener: () => void): this;
|
||||||
|
|
||||||
|
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependListener(event: "disconnect", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||||
|
prependListener(event: "listening", listener: (address: Address) => void): this;
|
||||||
|
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
prependListener(event: "online", listener: () => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependOnceListener(event: "disconnect", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||||
|
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
|
||||||
|
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
prependOnceListener(event: "online", listener: () => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Cluster extends events.EventEmitter {
|
||||||
|
Worker: Worker;
|
||||||
|
disconnect(callback?: () => void): void;
|
||||||
|
fork(env?: any): Worker;
|
||||||
|
isMaster: boolean;
|
||||||
|
isWorker: boolean;
|
||||||
|
// TODO: cluster.schedulingPolicy
|
||||||
|
settings: ClusterSettings;
|
||||||
|
setupMaster(settings?: ClusterSettings): void;
|
||||||
|
worker?: Worker;
|
||||||
|
workers?: {
|
||||||
|
[index: string]: Worker | undefined
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* events.EventEmitter
|
||||||
|
* 1. disconnect
|
||||||
|
* 2. exit
|
||||||
|
* 3. fork
|
||||||
|
* 4. listening
|
||||||
|
* 5. message
|
||||||
|
* 6. online
|
||||||
|
* 7. setup
|
||||||
|
*/
|
||||||
|
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||||
|
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||||
|
addListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||||
|
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||||
|
addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
addListener(event: "online", listener: (worker: Worker) => void): this;
|
||||||
|
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||||
|
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
emit(event: "disconnect", worker: Worker): boolean;
|
||||||
|
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
|
||||||
|
emit(event: "fork", worker: Worker): boolean;
|
||||||
|
emit(event: "listening", worker: Worker, address: Address): boolean;
|
||||||
|
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
|
||||||
|
emit(event: "online", worker: Worker): boolean;
|
||||||
|
emit(event: "setup", settings: ClusterSettings): boolean;
|
||||||
|
|
||||||
|
on(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
on(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||||
|
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||||
|
on(event: "fork", listener: (worker: Worker) => void): this;
|
||||||
|
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||||
|
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
on(event: "online", listener: (worker: Worker) => void): this;
|
||||||
|
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||||
|
|
||||||
|
once(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
once(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||||
|
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||||
|
once(event: "fork", listener: (worker: Worker) => void): this;
|
||||||
|
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||||
|
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
once(event: "online", listener: (worker: Worker) => void): this;
|
||||||
|
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||||
|
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||||
|
prependListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||||
|
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||||
|
prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
prependListener(event: "online", listener: (worker: Worker) => void): this;
|
||||||
|
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||||
|
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||||
|
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||||
|
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||||
|
// the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
|
||||||
|
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
|
||||||
|
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
function disconnect(callback?: () => void): void;
|
||||||
|
function fork(env?: any): Worker;
|
||||||
|
const isMaster: boolean;
|
||||||
|
const isWorker: boolean;
|
||||||
|
// TODO: cluster.schedulingPolicy
|
||||||
|
const settings: ClusterSettings;
|
||||||
|
function setupMaster(settings?: ClusterSettings): void;
|
||||||
|
const worker: Worker;
|
||||||
|
const workers: {
|
||||||
|
[index: string]: Worker | undefined
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* events.EventEmitter
|
||||||
|
* 1. disconnect
|
||||||
|
* 2. exit
|
||||||
|
* 3. fork
|
||||||
|
* 4. listening
|
||||||
|
* 5. message
|
||||||
|
* 6. online
|
||||||
|
* 7. setup
|
||||||
|
*/
|
||||||
|
function addListener(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
|
||||||
|
function addListener(event: "fork", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
|
||||||
|
// the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
|
||||||
|
function addListener(event: "online", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
|
||||||
|
|
||||||
|
function emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
function emit(event: "disconnect", worker: Worker): boolean;
|
||||||
|
function emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
|
||||||
|
function emit(event: "fork", worker: Worker): boolean;
|
||||||
|
function emit(event: "listening", worker: Worker, address: Address): boolean;
|
||||||
|
function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
|
||||||
|
function emit(event: "online", worker: Worker): boolean;
|
||||||
|
function emit(event: "setup", settings: ClusterSettings): boolean;
|
||||||
|
|
||||||
|
function on(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function on(event: "disconnect", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
|
||||||
|
function on(event: "fork", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
|
||||||
|
function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
function on(event: "online", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
|
||||||
|
|
||||||
|
function once(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function once(event: "disconnect", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
|
||||||
|
function once(event: "fork", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
|
||||||
|
function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
function once(event: "online", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
|
||||||
|
|
||||||
|
function removeListener(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function removeAllListeners(event?: string): Cluster;
|
||||||
|
function setMaxListeners(n: number): Cluster;
|
||||||
|
function getMaxListeners(): number;
|
||||||
|
function listeners(event: string): Function[];
|
||||||
|
function listenerCount(type: string): number;
|
||||||
|
|
||||||
|
function prependListener(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
|
||||||
|
function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
|
||||||
|
// the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
|
||||||
|
function prependListener(event: "online", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
|
||||||
|
|
||||||
|
function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
|
||||||
|
// the handle is a net.Socket or net.Server object, or undefined.
|
||||||
|
function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster;
|
||||||
|
function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
|
||||||
|
|
||||||
|
function eventNames(): string[];
|
||||||
|
}
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
declare module "console" {
|
||||||
|
export = console;
|
||||||
|
}
|
||||||
+278
@@ -0,0 +1,278 @@
|
|||||||
|
declare module "constants" {
|
||||||
|
const E2BIG: number;
|
||||||
|
const EACCES: number;
|
||||||
|
const EADDRINUSE: number;
|
||||||
|
const EADDRNOTAVAIL: number;
|
||||||
|
const EAFNOSUPPORT: number;
|
||||||
|
const EAGAIN: number;
|
||||||
|
const EALREADY: number;
|
||||||
|
const EBADF: number;
|
||||||
|
const EBADMSG: number;
|
||||||
|
const EBUSY: number;
|
||||||
|
const ECANCELED: number;
|
||||||
|
const ECHILD: number;
|
||||||
|
const ECONNABORTED: number;
|
||||||
|
const ECONNREFUSED: number;
|
||||||
|
const ECONNRESET: number;
|
||||||
|
const EDEADLK: number;
|
||||||
|
const EDESTADDRREQ: number;
|
||||||
|
const EDOM: number;
|
||||||
|
const EEXIST: number;
|
||||||
|
const EFAULT: number;
|
||||||
|
const EFBIG: number;
|
||||||
|
const EHOSTUNREACH: number;
|
||||||
|
const EIDRM: number;
|
||||||
|
const EILSEQ: number;
|
||||||
|
const EINPROGRESS: number;
|
||||||
|
const EINTR: number;
|
||||||
|
const EINVAL: number;
|
||||||
|
const EIO: number;
|
||||||
|
const EISCONN: number;
|
||||||
|
const EISDIR: number;
|
||||||
|
const ELOOP: number;
|
||||||
|
const EMFILE: number;
|
||||||
|
const EMLINK: number;
|
||||||
|
const EMSGSIZE: number;
|
||||||
|
const ENAMETOOLONG: number;
|
||||||
|
const ENETDOWN: number;
|
||||||
|
const ENETRESET: number;
|
||||||
|
const ENETUNREACH: number;
|
||||||
|
const ENFILE: number;
|
||||||
|
const ENOBUFS: number;
|
||||||
|
const ENODATA: number;
|
||||||
|
const ENODEV: number;
|
||||||
|
const ENOENT: number;
|
||||||
|
const ENOEXEC: number;
|
||||||
|
const ENOLCK: number;
|
||||||
|
const ENOLINK: number;
|
||||||
|
const ENOMEM: number;
|
||||||
|
const ENOMSG: number;
|
||||||
|
const ENOPROTOOPT: number;
|
||||||
|
const ENOSPC: number;
|
||||||
|
const ENOSR: number;
|
||||||
|
const ENOSTR: number;
|
||||||
|
const ENOSYS: number;
|
||||||
|
const ENOTCONN: number;
|
||||||
|
const ENOTDIR: number;
|
||||||
|
const ENOTEMPTY: number;
|
||||||
|
const ENOTSOCK: number;
|
||||||
|
const ENOTSUP: number;
|
||||||
|
const ENOTTY: number;
|
||||||
|
const ENXIO: number;
|
||||||
|
const EOPNOTSUPP: number;
|
||||||
|
const EOVERFLOW: number;
|
||||||
|
const EPERM: number;
|
||||||
|
const EPIPE: number;
|
||||||
|
const EPROTO: number;
|
||||||
|
const EPROTONOSUPPORT: number;
|
||||||
|
const EPROTOTYPE: number;
|
||||||
|
const ERANGE: number;
|
||||||
|
const EROFS: number;
|
||||||
|
const ESPIPE: number;
|
||||||
|
const ESRCH: number;
|
||||||
|
const ETIME: number;
|
||||||
|
const ETIMEDOUT: number;
|
||||||
|
const ETXTBSY: number;
|
||||||
|
const EWOULDBLOCK: number;
|
||||||
|
const EXDEV: number;
|
||||||
|
const WSAEINTR: number;
|
||||||
|
const WSAEBADF: number;
|
||||||
|
const WSAEACCES: number;
|
||||||
|
const WSAEFAULT: number;
|
||||||
|
const WSAEINVAL: number;
|
||||||
|
const WSAEMFILE: number;
|
||||||
|
const WSAEWOULDBLOCK: number;
|
||||||
|
const WSAEINPROGRESS: number;
|
||||||
|
const WSAEALREADY: number;
|
||||||
|
const WSAENOTSOCK: number;
|
||||||
|
const WSAEDESTADDRREQ: number;
|
||||||
|
const WSAEMSGSIZE: number;
|
||||||
|
const WSAEPROTOTYPE: number;
|
||||||
|
const WSAENOPROTOOPT: number;
|
||||||
|
const WSAEPROTONOSUPPORT: number;
|
||||||
|
const WSAESOCKTNOSUPPORT: number;
|
||||||
|
const WSAEOPNOTSUPP: number;
|
||||||
|
const WSAEPFNOSUPPORT: number;
|
||||||
|
const WSAEAFNOSUPPORT: number;
|
||||||
|
const WSAEADDRINUSE: number;
|
||||||
|
const WSAEADDRNOTAVAIL: number;
|
||||||
|
const WSAENETDOWN: number;
|
||||||
|
const WSAENETUNREACH: number;
|
||||||
|
const WSAENETRESET: number;
|
||||||
|
const WSAECONNABORTED: number;
|
||||||
|
const WSAECONNRESET: number;
|
||||||
|
const WSAENOBUFS: number;
|
||||||
|
const WSAEISCONN: number;
|
||||||
|
const WSAENOTCONN: number;
|
||||||
|
const WSAESHUTDOWN: number;
|
||||||
|
const WSAETOOMANYREFS: number;
|
||||||
|
const WSAETIMEDOUT: number;
|
||||||
|
const WSAECONNREFUSED: number;
|
||||||
|
const WSAELOOP: number;
|
||||||
|
const WSAENAMETOOLONG: number;
|
||||||
|
const WSAEHOSTDOWN: number;
|
||||||
|
const WSAEHOSTUNREACH: number;
|
||||||
|
const WSAENOTEMPTY: number;
|
||||||
|
const WSAEPROCLIM: number;
|
||||||
|
const WSAEUSERS: number;
|
||||||
|
const WSAEDQUOT: number;
|
||||||
|
const WSAESTALE: number;
|
||||||
|
const WSAEREMOTE: number;
|
||||||
|
const WSASYSNOTREADY: number;
|
||||||
|
const WSAVERNOTSUPPORTED: number;
|
||||||
|
const WSANOTINITIALISED: number;
|
||||||
|
const WSAEDISCON: number;
|
||||||
|
const WSAENOMORE: number;
|
||||||
|
const WSAECANCELLED: number;
|
||||||
|
const WSAEINVALIDPROCTABLE: number;
|
||||||
|
const WSAEINVALIDPROVIDER: number;
|
||||||
|
const WSAEPROVIDERFAILEDINIT: number;
|
||||||
|
const WSASYSCALLFAILURE: number;
|
||||||
|
const WSASERVICE_NOT_FOUND: number;
|
||||||
|
const WSATYPE_NOT_FOUND: number;
|
||||||
|
const WSA_E_NO_MORE: number;
|
||||||
|
const WSA_E_CANCELLED: number;
|
||||||
|
const WSAEREFUSED: number;
|
||||||
|
const SIGHUP: number;
|
||||||
|
const SIGINT: number;
|
||||||
|
const SIGILL: number;
|
||||||
|
const SIGABRT: number;
|
||||||
|
const SIGFPE: number;
|
||||||
|
const SIGKILL: number;
|
||||||
|
const SIGSEGV: number;
|
||||||
|
const SIGTERM: number;
|
||||||
|
const SIGBREAK: number;
|
||||||
|
const SIGWINCH: number;
|
||||||
|
const SSL_OP_ALL: number;
|
||||||
|
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
|
||||||
|
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
|
||||||
|
const SSL_OP_CISCO_ANYCONNECT: number;
|
||||||
|
const SSL_OP_COOKIE_EXCHANGE: number;
|
||||||
|
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
|
||||||
|
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
|
||||||
|
const SSL_OP_EPHEMERAL_RSA: number;
|
||||||
|
const SSL_OP_LEGACY_SERVER_CONNECT: number;
|
||||||
|
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
|
||||||
|
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
|
||||||
|
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
|
||||||
|
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
|
||||||
|
const SSL_OP_NO_COMPRESSION: number;
|
||||||
|
const SSL_OP_NO_QUERY_MTU: number;
|
||||||
|
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
|
||||||
|
const SSL_OP_NO_SSLv2: number;
|
||||||
|
const SSL_OP_NO_SSLv3: number;
|
||||||
|
const SSL_OP_NO_TICKET: number;
|
||||||
|
const SSL_OP_NO_TLSv1: number;
|
||||||
|
const SSL_OP_NO_TLSv1_1: number;
|
||||||
|
const SSL_OP_NO_TLSv1_2: number;
|
||||||
|
const SSL_OP_PKCS1_CHECK_1: number;
|
||||||
|
const SSL_OP_PKCS1_CHECK_2: number;
|
||||||
|
const SSL_OP_SINGLE_DH_USE: number;
|
||||||
|
const SSL_OP_SINGLE_ECDH_USE: number;
|
||||||
|
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
|
||||||
|
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
|
||||||
|
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
|
||||||
|
const SSL_OP_TLS_D5_BUG: number;
|
||||||
|
const SSL_OP_TLS_ROLLBACK_BUG: number;
|
||||||
|
const ENGINE_METHOD_DSA: number;
|
||||||
|
const ENGINE_METHOD_DH: number;
|
||||||
|
const ENGINE_METHOD_RAND: number;
|
||||||
|
const ENGINE_METHOD_ECDH: number;
|
||||||
|
const ENGINE_METHOD_ECDSA: number;
|
||||||
|
const ENGINE_METHOD_CIPHERS: number;
|
||||||
|
const ENGINE_METHOD_DIGESTS: number;
|
||||||
|
const ENGINE_METHOD_STORE: number;
|
||||||
|
const ENGINE_METHOD_PKEY_METHS: number;
|
||||||
|
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
|
||||||
|
const ENGINE_METHOD_ALL: number;
|
||||||
|
const ENGINE_METHOD_NONE: number;
|
||||||
|
const DH_CHECK_P_NOT_SAFE_PRIME: number;
|
||||||
|
const DH_CHECK_P_NOT_PRIME: number;
|
||||||
|
const DH_UNABLE_TO_CHECK_GENERATOR: number;
|
||||||
|
const DH_NOT_SUITABLE_GENERATOR: number;
|
||||||
|
const RSA_PKCS1_PADDING: number;
|
||||||
|
const RSA_SSLV23_PADDING: number;
|
||||||
|
const RSA_NO_PADDING: number;
|
||||||
|
const RSA_PKCS1_OAEP_PADDING: number;
|
||||||
|
const RSA_X931_PADDING: number;
|
||||||
|
const RSA_PKCS1_PSS_PADDING: number;
|
||||||
|
const POINT_CONVERSION_COMPRESSED: number;
|
||||||
|
const POINT_CONVERSION_UNCOMPRESSED: number;
|
||||||
|
const POINT_CONVERSION_HYBRID: number;
|
||||||
|
const O_RDONLY: number;
|
||||||
|
const O_WRONLY: number;
|
||||||
|
const O_RDWR: number;
|
||||||
|
const S_IFMT: number;
|
||||||
|
const S_IFREG: number;
|
||||||
|
const S_IFDIR: number;
|
||||||
|
const S_IFCHR: number;
|
||||||
|
const S_IFBLK: number;
|
||||||
|
const S_IFIFO: number;
|
||||||
|
const S_IFSOCK: number;
|
||||||
|
const S_IRWXU: number;
|
||||||
|
const S_IRUSR: number;
|
||||||
|
const S_IWUSR: number;
|
||||||
|
const S_IXUSR: number;
|
||||||
|
const S_IRWXG: number;
|
||||||
|
const S_IRGRP: number;
|
||||||
|
const S_IWGRP: number;
|
||||||
|
const S_IXGRP: number;
|
||||||
|
const S_IRWXO: number;
|
||||||
|
const S_IROTH: number;
|
||||||
|
const S_IWOTH: number;
|
||||||
|
const S_IXOTH: number;
|
||||||
|
const S_IFLNK: number;
|
||||||
|
const O_CREAT: number;
|
||||||
|
const O_EXCL: number;
|
||||||
|
const O_NOCTTY: number;
|
||||||
|
const O_DIRECTORY: number;
|
||||||
|
const O_NOATIME: number;
|
||||||
|
const O_NOFOLLOW: number;
|
||||||
|
const O_SYNC: number;
|
||||||
|
const O_DSYNC: number;
|
||||||
|
const O_SYMLINK: number;
|
||||||
|
const O_DIRECT: number;
|
||||||
|
const O_NONBLOCK: number;
|
||||||
|
const O_TRUNC: number;
|
||||||
|
const O_APPEND: number;
|
||||||
|
const F_OK: number;
|
||||||
|
const R_OK: number;
|
||||||
|
const W_OK: number;
|
||||||
|
const X_OK: number;
|
||||||
|
const COPYFILE_EXCL: number;
|
||||||
|
const COPYFILE_FICLONE: number;
|
||||||
|
const COPYFILE_FICLONE_FORCE: number;
|
||||||
|
const UV_UDP_REUSEADDR: number;
|
||||||
|
const SIGQUIT: number;
|
||||||
|
const SIGTRAP: number;
|
||||||
|
const SIGIOT: number;
|
||||||
|
const SIGBUS: number;
|
||||||
|
const SIGUSR1: number;
|
||||||
|
const SIGUSR2: number;
|
||||||
|
const SIGPIPE: number;
|
||||||
|
const SIGALRM: number;
|
||||||
|
const SIGCHLD: number;
|
||||||
|
const SIGSTKFLT: number;
|
||||||
|
const SIGCONT: number;
|
||||||
|
const SIGSTOP: number;
|
||||||
|
const SIGTSTP: number;
|
||||||
|
const SIGTTIN: number;
|
||||||
|
const SIGTTOU: number;
|
||||||
|
const SIGURG: number;
|
||||||
|
const SIGXCPU: number;
|
||||||
|
const SIGXFSZ: number;
|
||||||
|
const SIGVTALRM: number;
|
||||||
|
const SIGPROF: number;
|
||||||
|
const SIGIO: number;
|
||||||
|
const SIGPOLL: number;
|
||||||
|
const SIGPWR: number;
|
||||||
|
const SIGSYS: number;
|
||||||
|
const SIGUNUSED: number;
|
||||||
|
const defaultCoreCipherList: string;
|
||||||
|
const defaultCipherList: string;
|
||||||
|
const ENGINE_METHOD_RSA: number;
|
||||||
|
const ALPN_ENABLED: number;
|
||||||
|
}
|
||||||
+602
@@ -0,0 +1,602 @@
|
|||||||
|
declare module "crypto" {
|
||||||
|
import * as stream from "stream";
|
||||||
|
|
||||||
|
interface Certificate {
|
||||||
|
exportChallenge(spkac: BinaryLike): Buffer;
|
||||||
|
exportPublicKey(spkac: BinaryLike): Buffer;
|
||||||
|
verifySpkac(spkac: Binary): boolean;
|
||||||
|
}
|
||||||
|
const Certificate: {
|
||||||
|
new(): Certificate;
|
||||||
|
(): Certificate;
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
|
||||||
|
const OPENSSL_VERSION_NUMBER: number;
|
||||||
|
|
||||||
|
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
|
||||||
|
const SSL_OP_ALL: number;
|
||||||
|
/** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
|
||||||
|
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
|
||||||
|
/** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
|
||||||
|
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
|
||||||
|
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
|
||||||
|
const SSL_OP_CISCO_ANYCONNECT: number;
|
||||||
|
/** Instructs OpenSSL to turn on cookie exchange. */
|
||||||
|
const SSL_OP_COOKIE_EXCHANGE: number;
|
||||||
|
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
|
||||||
|
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
|
||||||
|
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
|
||||||
|
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
|
||||||
|
/** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */
|
||||||
|
const SSL_OP_EPHEMERAL_RSA: number;
|
||||||
|
/** Allows initial connection to servers that do not support RI. */
|
||||||
|
const SSL_OP_LEGACY_SERVER_CONNECT: number;
|
||||||
|
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
|
||||||
|
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
|
||||||
|
/** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */
|
||||||
|
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
|
||||||
|
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
|
||||||
|
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
|
||||||
|
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
|
||||||
|
const SSL_OP_NO_COMPRESSION: number;
|
||||||
|
const SSL_OP_NO_QUERY_MTU: number;
|
||||||
|
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
|
||||||
|
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
|
||||||
|
const SSL_OP_NO_SSLv2: number;
|
||||||
|
const SSL_OP_NO_SSLv3: number;
|
||||||
|
const SSL_OP_NO_TICKET: number;
|
||||||
|
const SSL_OP_NO_TLSv1: number;
|
||||||
|
const SSL_OP_NO_TLSv1_1: number;
|
||||||
|
const SSL_OP_NO_TLSv1_2: number;
|
||||||
|
const SSL_OP_PKCS1_CHECK_1: number;
|
||||||
|
const SSL_OP_PKCS1_CHECK_2: number;
|
||||||
|
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */
|
||||||
|
const SSL_OP_SINGLE_DH_USE: number;
|
||||||
|
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */
|
||||||
|
const SSL_OP_SINGLE_ECDH_USE: number;
|
||||||
|
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
|
||||||
|
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
|
||||||
|
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
|
||||||
|
const SSL_OP_TLS_D5_BUG: number;
|
||||||
|
/** Instructs OpenSSL to disable version rollback attack detection. */
|
||||||
|
const SSL_OP_TLS_ROLLBACK_BUG: number;
|
||||||
|
|
||||||
|
const ENGINE_METHOD_RSA: number;
|
||||||
|
const ENGINE_METHOD_DSA: number;
|
||||||
|
const ENGINE_METHOD_DH: number;
|
||||||
|
const ENGINE_METHOD_RAND: number;
|
||||||
|
const ENGINE_METHOD_EC: number;
|
||||||
|
const ENGINE_METHOD_CIPHERS: number;
|
||||||
|
const ENGINE_METHOD_DIGESTS: number;
|
||||||
|
const ENGINE_METHOD_PKEY_METHS: number;
|
||||||
|
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
|
||||||
|
const ENGINE_METHOD_ALL: number;
|
||||||
|
const ENGINE_METHOD_NONE: number;
|
||||||
|
|
||||||
|
const DH_CHECK_P_NOT_SAFE_PRIME: number;
|
||||||
|
const DH_CHECK_P_NOT_PRIME: number;
|
||||||
|
const DH_UNABLE_TO_CHECK_GENERATOR: number;
|
||||||
|
const DH_NOT_SUITABLE_GENERATOR: number;
|
||||||
|
|
||||||
|
const ALPN_ENABLED: number;
|
||||||
|
|
||||||
|
const RSA_PKCS1_PADDING: number;
|
||||||
|
const RSA_SSLV23_PADDING: number;
|
||||||
|
const RSA_NO_PADDING: number;
|
||||||
|
const RSA_PKCS1_OAEP_PADDING: number;
|
||||||
|
const RSA_X931_PADDING: number;
|
||||||
|
const RSA_PKCS1_PSS_PADDING: number;
|
||||||
|
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
|
||||||
|
const RSA_PSS_SALTLEN_DIGEST: number;
|
||||||
|
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
|
||||||
|
const RSA_PSS_SALTLEN_MAX_SIGN: number;
|
||||||
|
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
|
||||||
|
const RSA_PSS_SALTLEN_AUTO: number;
|
||||||
|
|
||||||
|
const POINT_CONVERSION_COMPRESSED: number;
|
||||||
|
const POINT_CONVERSION_UNCOMPRESSED: number;
|
||||||
|
const POINT_CONVERSION_HYBRID: number;
|
||||||
|
|
||||||
|
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
|
||||||
|
const defaultCoreCipherList: string;
|
||||||
|
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
|
||||||
|
const defaultCipherList: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated since v10.0.0 */
|
||||||
|
const fips: boolean;
|
||||||
|
|
||||||
|
function createHash(algorithm: string, options?: stream.TransformOptions): Hash;
|
||||||
|
function createHmac(algorithm: string, key: BinaryLike, options?: stream.TransformOptions): Hmac;
|
||||||
|
|
||||||
|
type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1";
|
||||||
|
type HexBase64Latin1Encoding = "latin1" | "hex" | "base64";
|
||||||
|
type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary";
|
||||||
|
type HexBase64BinaryEncoding = "binary" | "base64" | "hex";
|
||||||
|
type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid";
|
||||||
|
|
||||||
|
class Hash extends stream.Transform {
|
||||||
|
private constructor();
|
||||||
|
update(data: BinaryLike): Hash;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash;
|
||||||
|
digest(): Buffer;
|
||||||
|
digest(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
}
|
||||||
|
class Hmac extends stream.Transform {
|
||||||
|
private constructor();
|
||||||
|
update(data: BinaryLike): Hmac;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac;
|
||||||
|
digest(): Buffer;
|
||||||
|
digest(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type KeyObjectType = 'secret' | 'public' | 'private';
|
||||||
|
|
||||||
|
interface KeyExportOptions<T extends KeyFormat> {
|
||||||
|
type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1';
|
||||||
|
format: T;
|
||||||
|
cipher?: string;
|
||||||
|
passphrase?: string | Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeyObject {
|
||||||
|
private constructor();
|
||||||
|
asymmetricKeyType?: KeyType;
|
||||||
|
/**
|
||||||
|
* For asymmetric keys, this property represents the size of the embedded key in
|
||||||
|
* bytes. This property is `undefined` for symmetric keys.
|
||||||
|
*/
|
||||||
|
asymmetricKeySize?: number;
|
||||||
|
export(options: KeyExportOptions<'pem'>): string | Buffer;
|
||||||
|
export(options?: KeyExportOptions<'der'>): Buffer;
|
||||||
|
symmetricSize?: number;
|
||||||
|
type: KeyObjectType;
|
||||||
|
}
|
||||||
|
|
||||||
|
type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm';
|
||||||
|
type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
|
||||||
|
|
||||||
|
type Binary = NodeJS.TypedArray | DataView;
|
||||||
|
type BinaryLike = string | Binary;
|
||||||
|
|
||||||
|
type CipherKey = BinaryLike | KeyObject;
|
||||||
|
|
||||||
|
interface CipherCCMOptions extends stream.TransformOptions {
|
||||||
|
authTagLength: number;
|
||||||
|
}
|
||||||
|
interface CipherGCMOptions extends stream.TransformOptions {
|
||||||
|
authTagLength?: number;
|
||||||
|
}
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
|
||||||
|
|
||||||
|
function createCipheriv(
|
||||||
|
algorithm: CipherCCMTypes,
|
||||||
|
key: CipherKey,
|
||||||
|
iv: BinaryLike | null,
|
||||||
|
options: CipherCCMOptions
|
||||||
|
): CipherCCM;
|
||||||
|
function createCipheriv(
|
||||||
|
algorithm: CipherGCMTypes,
|
||||||
|
key: CipherKey,
|
||||||
|
iv: BinaryLike | null,
|
||||||
|
options?: CipherGCMOptions
|
||||||
|
): CipherGCM;
|
||||||
|
function createCipheriv(
|
||||||
|
algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions
|
||||||
|
): Cipher;
|
||||||
|
|
||||||
|
class Cipher extends stream.Transform {
|
||||||
|
private constructor();
|
||||||
|
update(data: BinaryLike): Buffer;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer;
|
||||||
|
update(data: Binary, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiBinaryEncoding | undefined, output_encoding: HexBase64BinaryEncoding): string;
|
||||||
|
final(): Buffer;
|
||||||
|
final(output_encoding: string): string;
|
||||||
|
setAutoPadding(auto_padding?: boolean): this;
|
||||||
|
// getAuthTag(): Buffer;
|
||||||
|
// setAAD(buffer: Buffer): this; // docs only say buffer
|
||||||
|
}
|
||||||
|
interface CipherCCM extends Cipher {
|
||||||
|
setAAD(buffer: Buffer, options: { plaintextLength: number }): this;
|
||||||
|
getAuthTag(): Buffer;
|
||||||
|
}
|
||||||
|
interface CipherGCM extends Cipher {
|
||||||
|
setAAD(buffer: Buffer, options?: { plaintextLength: number }): this;
|
||||||
|
getAuthTag(): Buffer;
|
||||||
|
}
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
|
||||||
|
/** @deprecated since v10.0.0 use createCipheriv() */
|
||||||
|
function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
|
||||||
|
|
||||||
|
function createDecipheriv(
|
||||||
|
algorithm: CipherCCMTypes,
|
||||||
|
key: BinaryLike,
|
||||||
|
iv: BinaryLike | null,
|
||||||
|
options: CipherCCMOptions,
|
||||||
|
): DecipherCCM;
|
||||||
|
function createDecipheriv(
|
||||||
|
algorithm: CipherGCMTypes,
|
||||||
|
key: BinaryLike,
|
||||||
|
iv: BinaryLike | null,
|
||||||
|
options?: CipherGCMOptions,
|
||||||
|
): DecipherGCM;
|
||||||
|
function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher;
|
||||||
|
|
||||||
|
class Decipher extends stream.Transform {
|
||||||
|
private constructor();
|
||||||
|
update(data: Binary): Buffer;
|
||||||
|
update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer;
|
||||||
|
update(data: Binary, input_encoding: undefined, output_encoding: Utf8AsciiBinaryEncoding): string;
|
||||||
|
update(data: string, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string;
|
||||||
|
final(): Buffer;
|
||||||
|
final(output_encoding: string): string;
|
||||||
|
setAutoPadding(auto_padding?: boolean): this;
|
||||||
|
// setAuthTag(tag: Binary): this;
|
||||||
|
// setAAD(buffer: Binary): this;
|
||||||
|
}
|
||||||
|
interface DecipherCCM extends Decipher {
|
||||||
|
setAuthTag(buffer: Binary): this;
|
||||||
|
setAAD(buffer: Binary, options: { plaintextLength: number }): this;
|
||||||
|
}
|
||||||
|
interface DecipherGCM extends Decipher {
|
||||||
|
setAuthTag(buffer: Binary): this;
|
||||||
|
setAAD(buffer: Binary, options?: { plaintextLength: number }): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PrivateKeyInput {
|
||||||
|
key: string | Buffer;
|
||||||
|
format?: KeyFormat;
|
||||||
|
type?: 'pkcs1' | 'pkcs8' | 'sec1';
|
||||||
|
passphrase?: string | Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PublicKeyInput {
|
||||||
|
key: string | Buffer;
|
||||||
|
format?: KeyFormat;
|
||||||
|
type?: 'pkcs1' | 'spki';
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject;
|
||||||
|
function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject;
|
||||||
|
function createSecretKey(key: Buffer): KeyObject;
|
||||||
|
|
||||||
|
function createSign(algorithm: string, options?: stream.WritableOptions): Signer;
|
||||||
|
|
||||||
|
interface SigningOptions {
|
||||||
|
/**
|
||||||
|
* @See crypto.constants.RSA_PKCS1_PADDING
|
||||||
|
*/
|
||||||
|
padding?: number;
|
||||||
|
saltLength?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {
|
||||||
|
}
|
||||||
|
|
||||||
|
type KeyLike = string | Buffer | KeyObject;
|
||||||
|
|
||||||
|
class Signer extends stream.Writable {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
update(data: BinaryLike): Signer;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer;
|
||||||
|
sign(private_key: SignPrivateKeyInput | KeyLike): Buffer;
|
||||||
|
sign(private_key: SignPrivateKeyInput | KeyLike, output_format: HexBase64Latin1Encoding): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
|
||||||
|
class Verify extends stream.Writable {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
update(data: BinaryLike): Verify;
|
||||||
|
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify;
|
||||||
|
verify(object: Object | KeyLike, signature: Binary): boolean;
|
||||||
|
verify(object: Object | KeyLike, signature: string, signature_format?: HexBase64Latin1Encoding): boolean;
|
||||||
|
// https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format
|
||||||
|
// The signature field accepts a TypedArray type, but it is only available starting ES2017
|
||||||
|
}
|
||||||
|
function createDiffieHellman(prime_length: number, generator?: number | Binary): DiffieHellman;
|
||||||
|
function createDiffieHellman(prime: Binary): DiffieHellman;
|
||||||
|
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman;
|
||||||
|
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Binary): DiffieHellman;
|
||||||
|
function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman;
|
||||||
|
class DiffieHellman {
|
||||||
|
private constructor();
|
||||||
|
generateKeys(): Buffer;
|
||||||
|
generateKeys(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
computeSecret(other_public_key: Binary): Buffer;
|
||||||
|
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer;
|
||||||
|
computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string;
|
||||||
|
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getPrime(): Buffer;
|
||||||
|
getPrime(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getGenerator(): Buffer;
|
||||||
|
getGenerator(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getPublicKey(): Buffer;
|
||||||
|
getPublicKey(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getPrivateKey(): Buffer;
|
||||||
|
getPrivateKey(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
setPublicKey(public_key: Binary): void;
|
||||||
|
setPublicKey(public_key: string, encoding: string): void;
|
||||||
|
setPrivateKey(private_key: Binary): void;
|
||||||
|
setPrivateKey(private_key: string, encoding: string): void;
|
||||||
|
verifyError: number;
|
||||||
|
}
|
||||||
|
function getDiffieHellman(group_name: string): DiffieHellman;
|
||||||
|
function pbkdf2(
|
||||||
|
password: BinaryLike,
|
||||||
|
salt: BinaryLike,
|
||||||
|
iterations: number,
|
||||||
|
keylen: number,
|
||||||
|
digest: string,
|
||||||
|
callback: (err: Error | null, derivedKey: Buffer) => any,
|
||||||
|
): void;
|
||||||
|
function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer;
|
||||||
|
|
||||||
|
function randomBytes(size: number): Buffer;
|
||||||
|
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
|
||||||
|
function pseudoRandomBytes(size: number): Buffer;
|
||||||
|
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
|
||||||
|
|
||||||
|
function randomFillSync<T extends Binary>(buffer: T, offset?: number, size?: number): T;
|
||||||
|
function randomFill<T extends Binary>(buffer: T, callback: (err: Error | null, buf: T) => void): void;
|
||||||
|
function randomFill<T extends Binary>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void;
|
||||||
|
function randomFill<T extends Binary>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void;
|
||||||
|
|
||||||
|
interface ScryptOptions {
|
||||||
|
N?: number;
|
||||||
|
r?: number;
|
||||||
|
p?: number;
|
||||||
|
maxmem?: number;
|
||||||
|
}
|
||||||
|
function scrypt(
|
||||||
|
password: BinaryLike,
|
||||||
|
salt: BinaryLike,
|
||||||
|
keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void,
|
||||||
|
): void;
|
||||||
|
function scrypt(
|
||||||
|
password: BinaryLike,
|
||||||
|
salt: BinaryLike,
|
||||||
|
keylen: number,
|
||||||
|
options: ScryptOptions,
|
||||||
|
callback: (err: Error | null, derivedKey: Buffer) => void,
|
||||||
|
): void;
|
||||||
|
function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
|
||||||
|
|
||||||
|
interface RsaPublicKey {
|
||||||
|
key: KeyLike;
|
||||||
|
padding?: number;
|
||||||
|
}
|
||||||
|
interface RsaPrivateKey {
|
||||||
|
key: KeyLike;
|
||||||
|
passphrase?: string;
|
||||||
|
padding?: number;
|
||||||
|
}
|
||||||
|
function publicEncrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer;
|
||||||
|
function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer;
|
||||||
|
function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer;
|
||||||
|
function publicDecrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer;
|
||||||
|
function getCiphers(): string[];
|
||||||
|
function getCurves(): string[];
|
||||||
|
function getHashes(): string[];
|
||||||
|
class ECDH {
|
||||||
|
private constructor();
|
||||||
|
static convertKey(
|
||||||
|
key: BinaryLike,
|
||||||
|
curve: string,
|
||||||
|
inputEncoding?: HexBase64Latin1Encoding,
|
||||||
|
outputEncoding?: "latin1" | "hex" | "base64",
|
||||||
|
format?: "uncompressed" | "compressed" | "hybrid",
|
||||||
|
): Buffer | string;
|
||||||
|
generateKeys(): Buffer;
|
||||||
|
generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string;
|
||||||
|
computeSecret(other_public_key: Binary): Buffer;
|
||||||
|
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer;
|
||||||
|
computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string;
|
||||||
|
computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getPrivateKey(): Buffer;
|
||||||
|
getPrivateKey(encoding: HexBase64Latin1Encoding): string;
|
||||||
|
getPublicKey(): Buffer;
|
||||||
|
getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string;
|
||||||
|
setPrivateKey(private_key: Binary): void;
|
||||||
|
setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void;
|
||||||
|
}
|
||||||
|
function createECDH(curve_name: string): ECDH;
|
||||||
|
function timingSafeEqual(a: Binary, b: Binary): boolean;
|
||||||
|
/** @deprecated since v10.0.0 */
|
||||||
|
const DEFAULT_ENCODING: string;
|
||||||
|
|
||||||
|
export type KeyType = 'rsa' | 'dsa' | 'ec';
|
||||||
|
export type KeyFormat = 'pem' | 'der';
|
||||||
|
|
||||||
|
interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
|
||||||
|
format: T;
|
||||||
|
cipher?: string;
|
||||||
|
passphrase?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyPairKeyObjectResult {
|
||||||
|
publicKey: KeyObject;
|
||||||
|
privateKey: KeyObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ECKeyPairKeyObjectOptions {
|
||||||
|
/**
|
||||||
|
* Name of the curve to use.
|
||||||
|
*/
|
||||||
|
namedCurve: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RSAKeyPairKeyObjectOptions {
|
||||||
|
/**
|
||||||
|
* Key size in bits
|
||||||
|
*/
|
||||||
|
modulusLength: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @default 0x10001
|
||||||
|
*/
|
||||||
|
publicExponent?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DSAKeyPairKeyObjectOptions {
|
||||||
|
/**
|
||||||
|
* Key size in bits
|
||||||
|
*/
|
||||||
|
modulusLength: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Size of q in bits
|
||||||
|
*/
|
||||||
|
divisorLength: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
|
||||||
|
/**
|
||||||
|
* Key size in bits
|
||||||
|
*/
|
||||||
|
modulusLength: number;
|
||||||
|
/**
|
||||||
|
* @default 0x10001
|
||||||
|
*/
|
||||||
|
publicExponent?: number;
|
||||||
|
|
||||||
|
publicKeyEncoding: {
|
||||||
|
type: 'pkcs1' | 'spki';
|
||||||
|
format: PubF;
|
||||||
|
};
|
||||||
|
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
|
||||||
|
type: 'pkcs1' | 'pkcs8';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
|
||||||
|
/**
|
||||||
|
* Key size in bits
|
||||||
|
*/
|
||||||
|
modulusLength: number;
|
||||||
|
/**
|
||||||
|
* Size of q in bits
|
||||||
|
*/
|
||||||
|
divisorLength: number;
|
||||||
|
|
||||||
|
publicKeyEncoding: {
|
||||||
|
type: 'spki';
|
||||||
|
format: PubF;
|
||||||
|
};
|
||||||
|
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
|
||||||
|
type: 'pkcs8';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
|
||||||
|
/**
|
||||||
|
* Name of the curve to use.
|
||||||
|
*/
|
||||||
|
namedCurve: string;
|
||||||
|
|
||||||
|
publicKeyEncoding: {
|
||||||
|
type: 'pkcs1' | 'spki';
|
||||||
|
format: PubF;
|
||||||
|
};
|
||||||
|
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
|
||||||
|
type: 'sec1' | 'pkcs8';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
|
||||||
|
publicKey: T1;
|
||||||
|
privateKey: T2;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
|
||||||
|
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
|
||||||
|
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
|
||||||
|
|
||||||
|
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
|
||||||
|
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
|
||||||
|
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
|
||||||
|
|
||||||
|
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
|
||||||
|
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
|
||||||
|
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
|
||||||
|
function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
|
||||||
|
|
||||||
|
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
|
||||||
|
|
||||||
|
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
|
||||||
|
|
||||||
|
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
|
||||||
|
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
|
||||||
|
function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
|
||||||
|
|
||||||
|
namespace generateKeyPair {
|
||||||
|
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
|
||||||
|
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
|
||||||
|
function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
|
||||||
|
|
||||||
|
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
|
||||||
|
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
|
||||||
|
function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
|
||||||
|
|
||||||
|
function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>;
|
||||||
|
function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>;
|
||||||
|
function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>;
|
||||||
|
function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates and returns the signature for `data` using the given private key and
|
||||||
|
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
|
||||||
|
* dependent upon the key type (especially Ed25519 and Ed448).
|
||||||
|
*
|
||||||
|
* If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
|
||||||
|
* passed to [`crypto.createPrivateKey()`][].
|
||||||
|
*/
|
||||||
|
function sign(algorithm: string | null | undefined, data: Binary, key: KeyLike | SignPrivateKeyInput): Buffer;
|
||||||
|
|
||||||
|
interface VerifyKeyWithOptions extends KeyObject, SigningOptions {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates and returns the signature for `data` using the given private key and
|
||||||
|
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
|
||||||
|
* dependent upon the key type (especially Ed25519 and Ed448).
|
||||||
|
*
|
||||||
|
* If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
|
||||||
|
* passed to [`crypto.createPublicKey()`][].
|
||||||
|
*/
|
||||||
|
function verify(algorithm: string | null | undefined, data: Binary, key: KeyLike | VerifyKeyWithOptions, signature: Binary): Buffer;
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
declare module "dgram" {
|
||||||
|
import { AddressInfo } from "net";
|
||||||
|
import * as dns from "dns";
|
||||||
|
import * as events from "events";
|
||||||
|
|
||||||
|
interface RemoteInfo {
|
||||||
|
address: string;
|
||||||
|
family: 'IPv4' | 'IPv6';
|
||||||
|
port: number;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BindOptions {
|
||||||
|
port: number;
|
||||||
|
address?: string;
|
||||||
|
exclusive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
type SocketType = "udp4" | "udp6";
|
||||||
|
|
||||||
|
interface SocketOptions {
|
||||||
|
type: SocketType;
|
||||||
|
reuseAddr?: boolean;
|
||||||
|
/**
|
||||||
|
* @default false
|
||||||
|
*/
|
||||||
|
ipv6Only?: boolean;
|
||||||
|
recvBufferSize?: number;
|
||||||
|
sendBufferSize?: number;
|
||||||
|
lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
|
||||||
|
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
|
||||||
|
|
||||||
|
class Socket extends events.EventEmitter {
|
||||||
|
send(msg: string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
|
||||||
|
send(msg: string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
|
||||||
|
bind(port?: number, address?: string, callback?: () => void): void;
|
||||||
|
bind(port?: number, callback?: () => void): void;
|
||||||
|
bind(callback?: () => void): void;
|
||||||
|
bind(options: BindOptions, callback?: () => void): void;
|
||||||
|
close(callback?: () => void): void;
|
||||||
|
address(): AddressInfo | string;
|
||||||
|
setBroadcast(flag: boolean): void;
|
||||||
|
setTTL(ttl: number): void;
|
||||||
|
setMulticastTTL(ttl: number): void;
|
||||||
|
setMulticastInterface(multicastInterface: string): void;
|
||||||
|
setMulticastLoopback(flag: boolean): void;
|
||||||
|
addMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||||
|
dropMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||||
|
ref(): this;
|
||||||
|
unref(): this;
|
||||||
|
setRecvBufferSize(size: number): void;
|
||||||
|
setSendBufferSize(size: number): void;
|
||||||
|
getRecvBufferSize(): number;
|
||||||
|
getSendBufferSize(): number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* events.EventEmitter
|
||||||
|
* 1. close
|
||||||
|
* 2. error
|
||||||
|
* 3. listening
|
||||||
|
* 4. message
|
||||||
|
*/
|
||||||
|
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
addListener(event: "close", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "listening", listener: () => void): this;
|
||||||
|
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||||
|
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
emit(event: "close"): boolean;
|
||||||
|
emit(event: "error", err: Error): boolean;
|
||||||
|
emit(event: "listening"): boolean;
|
||||||
|
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean;
|
||||||
|
|
||||||
|
on(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
on(event: "close", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (err: Error) => void): this;
|
||||||
|
on(event: "listening", listener: () => void): this;
|
||||||
|
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||||
|
|
||||||
|
once(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
once(event: "close", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (err: Error) => void): this;
|
||||||
|
once(event: "listening", listener: () => void): this;
|
||||||
|
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependListener(event: "close", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "listening", listener: () => void): this;
|
||||||
|
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||||
|
prependOnceListener(event: "close", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "listening", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||||
|
}
|
||||||
|
}
|
||||||
+366
@@ -0,0 +1,366 @@
|
|||||||
|
declare module "dns" {
|
||||||
|
// Supported getaddrinfo flags.
|
||||||
|
const ADDRCONFIG: number;
|
||||||
|
const V4MAPPED: number;
|
||||||
|
|
||||||
|
interface LookupOptions {
|
||||||
|
family?: number;
|
||||||
|
hints?: number;
|
||||||
|
all?: boolean;
|
||||||
|
verbatim?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LookupOneOptions extends LookupOptions {
|
||||||
|
all?: false;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LookupAllOptions extends LookupOptions {
|
||||||
|
all: true;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LookupAddress {
|
||||||
|
address: string;
|
||||||
|
family: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
|
||||||
|
function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
|
||||||
|
function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void;
|
||||||
|
function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void;
|
||||||
|
function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace lookup {
|
||||||
|
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||||
|
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
|
||||||
|
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void;
|
||||||
|
|
||||||
|
namespace lookupService {
|
||||||
|
function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResolveOptions {
|
||||||
|
ttl: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResolveWithTtlOptions extends ResolveOptions {
|
||||||
|
ttl: true;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RecordWithTtl {
|
||||||
|
address: string;
|
||||||
|
ttl: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Use AnyARecord or AnyAaaaRecord instead. */
|
||||||
|
type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
|
||||||
|
|
||||||
|
interface AnyARecord extends RecordWithTtl {
|
||||||
|
type: "A";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyAaaaRecord extends RecordWithTtl {
|
||||||
|
type: "AAAA";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MxRecord {
|
||||||
|
priority: number;
|
||||||
|
exchange: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyMxRecord extends MxRecord {
|
||||||
|
type: "MX";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NaptrRecord {
|
||||||
|
flags: string;
|
||||||
|
service: string;
|
||||||
|
regexp: string;
|
||||||
|
replacement: string;
|
||||||
|
order: number;
|
||||||
|
preference: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyNaptrRecord extends NaptrRecord {
|
||||||
|
type: "NAPTR";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SoaRecord {
|
||||||
|
nsname: string;
|
||||||
|
hostmaster: string;
|
||||||
|
serial: number;
|
||||||
|
refresh: number;
|
||||||
|
retry: number;
|
||||||
|
expire: number;
|
||||||
|
minttl: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnySoaRecord extends SoaRecord {
|
||||||
|
type: "SOA";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SrvRecord {
|
||||||
|
priority: number;
|
||||||
|
weight: number;
|
||||||
|
port: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnySrvRecord extends SrvRecord {
|
||||||
|
type: "SRV";
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyTxtRecord {
|
||||||
|
type: "TXT";
|
||||||
|
entries: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyNsRecord {
|
||||||
|
type: "NS";
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyPtrRecord {
|
||||||
|
type: "PTR";
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnyCnameRecord {
|
||||||
|
type: "CNAME";
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnyRecord = AnyARecord |
|
||||||
|
AnyAaaaRecord |
|
||||||
|
AnyCnameRecord |
|
||||||
|
AnyMxRecord |
|
||||||
|
AnyNaptrRecord |
|
||||||
|
AnyNsRecord |
|
||||||
|
AnyPtrRecord |
|
||||||
|
AnySoaRecord |
|
||||||
|
AnySrvRecord |
|
||||||
|
AnyTxtRecord;
|
||||||
|
|
||||||
|
function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
|
||||||
|
function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
|
||||||
|
function resolve(
|
||||||
|
hostname: string,
|
||||||
|
rrtype: string,
|
||||||
|
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void,
|
||||||
|
): void;
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace resolve {
|
||||||
|
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||||
|
function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
|
||||||
|
function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace resolve4 {
|
||||||
|
function __promisify__(hostname: string): Promise<string[]>;
|
||||||
|
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||||
|
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
|
||||||
|
function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
|
||||||
|
|
||||||
|
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
|
||||||
|
namespace resolve6 {
|
||||||
|
function __promisify__(hostname: string): Promise<string[]>;
|
||||||
|
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||||
|
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
namespace resolveCname {
|
||||||
|
function __promisify__(hostname: string): Promise<string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
|
||||||
|
namespace resolveMx {
|
||||||
|
function __promisify__(hostname: string): Promise<MxRecord[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
|
||||||
|
namespace resolveNaptr {
|
||||||
|
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
namespace resolveNs {
|
||||||
|
function __promisify__(hostname: string): Promise<string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
|
||||||
|
namespace resolvePtr {
|
||||||
|
function __promisify__(hostname: string): Promise<string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void;
|
||||||
|
namespace resolveSoa {
|
||||||
|
function __promisify__(hostname: string): Promise<SoaRecord>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
|
||||||
|
namespace resolveSrv {
|
||||||
|
function __promisify__(hostname: string): Promise<SrvRecord[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
|
||||||
|
namespace resolveTxt {
|
||||||
|
function __promisify__(hostname: string): Promise<string[][]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
|
||||||
|
namespace resolveAny {
|
||||||
|
function __promisify__(hostname: string): Promise<AnyRecord[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void;
|
||||||
|
function setServers(servers: ReadonlyArray<string>): void;
|
||||||
|
function getServers(): string[];
|
||||||
|
|
||||||
|
// Error codes
|
||||||
|
const NODATA: string;
|
||||||
|
const FORMERR: string;
|
||||||
|
const SERVFAIL: string;
|
||||||
|
const NOTFOUND: string;
|
||||||
|
const NOTIMP: string;
|
||||||
|
const REFUSED: string;
|
||||||
|
const BADQUERY: string;
|
||||||
|
const BADNAME: string;
|
||||||
|
const BADFAMILY: string;
|
||||||
|
const BADRESP: string;
|
||||||
|
const CONNREFUSED: string;
|
||||||
|
const TIMEOUT: string;
|
||||||
|
const EOF: string;
|
||||||
|
const FILE: string;
|
||||||
|
const NOMEM: string;
|
||||||
|
const DESTRUCTION: string;
|
||||||
|
const BADSTR: string;
|
||||||
|
const BADFLAGS: string;
|
||||||
|
const NONAME: string;
|
||||||
|
const BADHINTS: string;
|
||||||
|
const NOTINITIALIZED: string;
|
||||||
|
const LOADIPHLPAPI: string;
|
||||||
|
const ADDRGETNETWORKPARAMS: string;
|
||||||
|
const CANCELLED: string;
|
||||||
|
|
||||||
|
class Resolver {
|
||||||
|
getServers: typeof getServers;
|
||||||
|
setServers: typeof setServers;
|
||||||
|
resolve: typeof resolve;
|
||||||
|
resolve4: typeof resolve4;
|
||||||
|
resolve6: typeof resolve6;
|
||||||
|
resolveAny: typeof resolveAny;
|
||||||
|
resolveCname: typeof resolveCname;
|
||||||
|
resolveMx: typeof resolveMx;
|
||||||
|
resolveNaptr: typeof resolveNaptr;
|
||||||
|
resolveNs: typeof resolveNs;
|
||||||
|
resolvePtr: typeof resolvePtr;
|
||||||
|
resolveSoa: typeof resolveSoa;
|
||||||
|
resolveSrv: typeof resolveSrv;
|
||||||
|
resolveTxt: typeof resolveTxt;
|
||||||
|
reverse: typeof reverse;
|
||||||
|
cancel(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace promises {
|
||||||
|
function getServers(): string[];
|
||||||
|
|
||||||
|
function lookup(hostname: string, family: number): Promise<LookupAddress>;
|
||||||
|
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
|
||||||
|
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||||
|
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||||
|
function lookup(hostname: string): Promise<LookupAddress>;
|
||||||
|
|
||||||
|
function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>;
|
||||||
|
|
||||||
|
function resolve(hostname: string): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "A"): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||||
|
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||||
|
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||||
|
function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
|
||||||
|
|
||||||
|
function resolve4(hostname: string): Promise<string[]>;
|
||||||
|
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||||
|
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||||
|
|
||||||
|
function resolve6(hostname: string): Promise<string[]>;
|
||||||
|
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||||
|
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||||
|
|
||||||
|
function resolveAny(hostname: string): Promise<AnyRecord[]>;
|
||||||
|
|
||||||
|
function resolveCname(hostname: string): Promise<string[]>;
|
||||||
|
|
||||||
|
function resolveMx(hostname: string): Promise<MxRecord[]>;
|
||||||
|
|
||||||
|
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
|
||||||
|
|
||||||
|
function resolveNs(hostname: string): Promise<string[]>;
|
||||||
|
|
||||||
|
function resolvePtr(hostname: string): Promise<string[]>;
|
||||||
|
|
||||||
|
function resolveSoa(hostname: string): Promise<SoaRecord>;
|
||||||
|
|
||||||
|
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
|
||||||
|
|
||||||
|
function resolveTxt(hostname: string): Promise<string[][]>;
|
||||||
|
|
||||||
|
function reverse(ip: string): Promise<string[]>;
|
||||||
|
|
||||||
|
function setServers(servers: ReadonlyArray<string>): void;
|
||||||
|
|
||||||
|
class Resolver {
|
||||||
|
getServers: typeof getServers;
|
||||||
|
resolve: typeof resolve;
|
||||||
|
resolve4: typeof resolve4;
|
||||||
|
resolve6: typeof resolve6;
|
||||||
|
resolveAny: typeof resolveAny;
|
||||||
|
resolveCname: typeof resolveCname;
|
||||||
|
resolveMx: typeof resolveMx;
|
||||||
|
resolveNaptr: typeof resolveNaptr;
|
||||||
|
resolveNs: typeof resolveNs;
|
||||||
|
resolvePtr: typeof resolvePtr;
|
||||||
|
resolveSoa: typeof resolveSoa;
|
||||||
|
resolveSrv: typeof resolveSrv;
|
||||||
|
resolveTxt: typeof resolveTxt;
|
||||||
|
reverse: typeof reverse;
|
||||||
|
setServers: typeof setServers;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
declare module "domain" {
|
||||||
|
import * as events from "events";
|
||||||
|
|
||||||
|
class Domain extends events.EventEmitter implements NodeJS.Domain {
|
||||||
|
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
|
||||||
|
add(emitter: events.EventEmitter | NodeJS.Timer): void;
|
||||||
|
remove(emitter: events.EventEmitter | NodeJS.Timer): void;
|
||||||
|
bind<T extends Function>(cb: T): T;
|
||||||
|
intercept<T extends Function>(cb: T): T;
|
||||||
|
members: Array<events.EventEmitter | NodeJS.Timer>;
|
||||||
|
enter(): void;
|
||||||
|
exit(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function create(): Domain;
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
declare module "events" {
|
||||||
|
class internal extends NodeJS.EventEmitter { }
|
||||||
|
|
||||||
|
namespace internal {
|
||||||
|
function once(emitter: EventEmitter, event: string | symbol): Promise<any[]>;
|
||||||
|
class EventEmitter extends internal {
|
||||||
|
/** @deprecated since v4.0.0 */
|
||||||
|
static listenerCount(emitter: EventEmitter, event: string | symbol): number;
|
||||||
|
static defaultMaxListeners: number;
|
||||||
|
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
off(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
removeAllListeners(event?: string | symbol): this;
|
||||||
|
setMaxListeners(n: number): this;
|
||||||
|
getMaxListeners(): number;
|
||||||
|
listeners(event: string | symbol): Function[];
|
||||||
|
rawListeners(event: string | symbol): Function[];
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
eventNames(): Array<string | symbol>;
|
||||||
|
listenerCount(type: string | symbol): number;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export = internal;
|
||||||
|
}
|
||||||
+2297
File diff suppressed because it is too large
Load Diff
+1180
File diff suppressed because it is too large
Load Diff
+370
@@ -0,0 +1,370 @@
|
|||||||
|
declare module "http" {
|
||||||
|
import * as events from "events";
|
||||||
|
import * as stream from "stream";
|
||||||
|
import { URL } from "url";
|
||||||
|
import { Socket, Server as NetServer } from "net";
|
||||||
|
|
||||||
|
// incoming headers will never contain number
|
||||||
|
interface IncomingHttpHeaders {
|
||||||
|
'accept'?: string;
|
||||||
|
'accept-language'?: string;
|
||||||
|
'accept-patch'?: string;
|
||||||
|
'accept-ranges'?: string;
|
||||||
|
'access-control-allow-credentials'?: string;
|
||||||
|
'access-control-allow-headers'?: string;
|
||||||
|
'access-control-allow-methods'?: string;
|
||||||
|
'access-control-allow-origin'?: string;
|
||||||
|
'access-control-expose-headers'?: string;
|
||||||
|
'access-control-max-age'?: string;
|
||||||
|
'age'?: string;
|
||||||
|
'allow'?: string;
|
||||||
|
'alt-svc'?: string;
|
||||||
|
'authorization'?: string;
|
||||||
|
'cache-control'?: string;
|
||||||
|
'connection'?: string;
|
||||||
|
'content-disposition'?: string;
|
||||||
|
'content-encoding'?: string;
|
||||||
|
'content-language'?: string;
|
||||||
|
'content-length'?: string;
|
||||||
|
'content-location'?: string;
|
||||||
|
'content-range'?: string;
|
||||||
|
'content-type'?: string;
|
||||||
|
'cookie'?: string;
|
||||||
|
'date'?: string;
|
||||||
|
'expect'?: string;
|
||||||
|
'expires'?: string;
|
||||||
|
'forwarded'?: string;
|
||||||
|
'from'?: string;
|
||||||
|
'host'?: string;
|
||||||
|
'if-match'?: string;
|
||||||
|
'if-modified-since'?: string;
|
||||||
|
'if-none-match'?: string;
|
||||||
|
'if-unmodified-since'?: string;
|
||||||
|
'last-modified'?: string;
|
||||||
|
'location'?: string;
|
||||||
|
'pragma'?: string;
|
||||||
|
'proxy-authenticate'?: string;
|
||||||
|
'proxy-authorization'?: string;
|
||||||
|
'public-key-pins'?: string;
|
||||||
|
'range'?: string;
|
||||||
|
'referer'?: string;
|
||||||
|
'retry-after'?: string;
|
||||||
|
'set-cookie'?: string[];
|
||||||
|
'strict-transport-security'?: string;
|
||||||
|
'tk'?: string;
|
||||||
|
'trailer'?: string;
|
||||||
|
'transfer-encoding'?: string;
|
||||||
|
'upgrade'?: string;
|
||||||
|
'user-agent'?: string;
|
||||||
|
'vary'?: string;
|
||||||
|
'via'?: string;
|
||||||
|
'warning'?: string;
|
||||||
|
'www-authenticate'?: string;
|
||||||
|
[header: string]: string | string[] | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// outgoing headers allows numbers (as they are converted internally to strings)
|
||||||
|
interface OutgoingHttpHeaders {
|
||||||
|
[header: string]: number | string | string[] | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientRequestArgs {
|
||||||
|
protocol?: string;
|
||||||
|
host?: string;
|
||||||
|
hostname?: string;
|
||||||
|
family?: number;
|
||||||
|
port?: number | string;
|
||||||
|
defaultPort?: number | string;
|
||||||
|
localAddress?: string;
|
||||||
|
socketPath?: string;
|
||||||
|
method?: string;
|
||||||
|
path?: string;
|
||||||
|
headers?: OutgoingHttpHeaders;
|
||||||
|
auth?: string;
|
||||||
|
agent?: Agent | boolean;
|
||||||
|
_defaultAgent?: Agent;
|
||||||
|
timeout?: number;
|
||||||
|
setHost?: boolean;
|
||||||
|
// https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278
|
||||||
|
createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServerOptions {
|
||||||
|
IncomingMessage?: typeof IncomingMessage;
|
||||||
|
ServerResponse?: typeof ServerResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;
|
||||||
|
|
||||||
|
class Server extends NetServer {
|
||||||
|
constructor(requestListener?: RequestListener);
|
||||||
|
constructor(options: ServerOptions, requestListener?: RequestListener);
|
||||||
|
|
||||||
|
setTimeout(msecs?: number, callback?: () => void): this;
|
||||||
|
setTimeout(callback: () => void): this;
|
||||||
|
/**
|
||||||
|
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
|
||||||
|
* @default 2000
|
||||||
|
* {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
|
||||||
|
*/
|
||||||
|
maxHeadersCount: number | null;
|
||||||
|
timeout: number;
|
||||||
|
/**
|
||||||
|
* Limit the amount of time the parser will wait to receive the complete HTTP headers.
|
||||||
|
* @default 40000
|
||||||
|
* {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
|
||||||
|
*/
|
||||||
|
headersTimeout: number;
|
||||||
|
keepAliveTimeout: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
|
||||||
|
class OutgoingMessage extends stream.Writable {
|
||||||
|
upgrading: boolean;
|
||||||
|
chunkedEncoding: boolean;
|
||||||
|
shouldKeepAlive: boolean;
|
||||||
|
useChunkedEncodingByDefault: boolean;
|
||||||
|
sendDate: boolean;
|
||||||
|
finished: boolean;
|
||||||
|
headersSent: boolean;
|
||||||
|
connection: Socket;
|
||||||
|
|
||||||
|
constructor();
|
||||||
|
|
||||||
|
setTimeout(msecs: number, callback?: () => void): this;
|
||||||
|
setHeader(name: string, value: number | string | string[]): void;
|
||||||
|
getHeader(name: string): number | string | string[] | undefined;
|
||||||
|
getHeaders(): OutgoingHttpHeaders;
|
||||||
|
getHeaderNames(): string[];
|
||||||
|
hasHeader(name: string): boolean;
|
||||||
|
removeHeader(name: string): void;
|
||||||
|
addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void;
|
||||||
|
flushHeaders(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256
|
||||||
|
class ServerResponse extends OutgoingMessage {
|
||||||
|
statusCode: number;
|
||||||
|
statusMessage: string;
|
||||||
|
writableFinished: boolean;
|
||||||
|
|
||||||
|
constructor(req: IncomingMessage);
|
||||||
|
|
||||||
|
assignSocket(socket: Socket): void;
|
||||||
|
detachSocket(socket: Socket): void;
|
||||||
|
// https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53
|
||||||
|
// no args in writeContinue callback
|
||||||
|
writeContinue(callback?: () => void): void;
|
||||||
|
writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): this;
|
||||||
|
writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InformationEvent {
|
||||||
|
statusCode: number;
|
||||||
|
statusMessage: string;
|
||||||
|
httpVersion: string;
|
||||||
|
httpVersionMajor: number;
|
||||||
|
httpVersionMinor: number;
|
||||||
|
headers: IncomingHttpHeaders;
|
||||||
|
rawHeaders: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77
|
||||||
|
class ClientRequest extends OutgoingMessage {
|
||||||
|
connection: Socket;
|
||||||
|
socket: Socket;
|
||||||
|
aborted: number;
|
||||||
|
|
||||||
|
constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
|
||||||
|
|
||||||
|
readonly path: string;
|
||||||
|
abort(): void;
|
||||||
|
onSocket(socket: Socket): void;
|
||||||
|
setTimeout(timeout: number, callback?: () => void): this;
|
||||||
|
setNoDelay(noDelay?: boolean): void;
|
||||||
|
setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
|
||||||
|
|
||||||
|
addListener(event: 'abort', listener: () => void): this;
|
||||||
|
addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
addListener(event: 'continue', listener: () => void): this;
|
||||||
|
addListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
||||||
|
addListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
||||||
|
addListener(event: 'socket', listener: (socket: Socket) => void): this;
|
||||||
|
addListener(event: 'timeout', listener: () => void): this;
|
||||||
|
addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
addListener(event: 'close', listener: () => void): this;
|
||||||
|
addListener(event: 'drain', listener: () => void): this;
|
||||||
|
addListener(event: 'error', listener: (err: Error) => void): this;
|
||||||
|
addListener(event: 'finish', listener: () => void): this;
|
||||||
|
addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
on(event: 'abort', listener: () => void): this;
|
||||||
|
on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
on(event: 'continue', listener: () => void): this;
|
||||||
|
on(event: 'information', listener: (info: InformationEvent) => void): this;
|
||||||
|
on(event: 'response', listener: (response: IncomingMessage) => void): this;
|
||||||
|
on(event: 'socket', listener: (socket: Socket) => void): this;
|
||||||
|
on(event: 'timeout', listener: () => void): this;
|
||||||
|
on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
on(event: 'close', listener: () => void): this;
|
||||||
|
on(event: 'drain', listener: () => void): this;
|
||||||
|
on(event: 'error', listener: (err: Error) => void): this;
|
||||||
|
on(event: 'finish', listener: () => void): this;
|
||||||
|
on(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: 'abort', listener: () => void): this;
|
||||||
|
once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
once(event: 'continue', listener: () => void): this;
|
||||||
|
once(event: 'information', listener: (info: InformationEvent) => void): this;
|
||||||
|
once(event: 'response', listener: (response: IncomingMessage) => void): this;
|
||||||
|
once(event: 'socket', listener: (socket: Socket) => void): this;
|
||||||
|
once(event: 'timeout', listener: () => void): this;
|
||||||
|
once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
once(event: 'close', listener: () => void): this;
|
||||||
|
once(event: 'drain', listener: () => void): this;
|
||||||
|
once(event: 'error', listener: (err: Error) => void): this;
|
||||||
|
once(event: 'finish', listener: () => void): this;
|
||||||
|
once(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: 'abort', listener: () => void): this;
|
||||||
|
prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
prependListener(event: 'continue', listener: () => void): this;
|
||||||
|
prependListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
||||||
|
prependListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
||||||
|
prependListener(event: 'socket', listener: (socket: Socket) => void): this;
|
||||||
|
prependListener(event: 'timeout', listener: () => void): this;
|
||||||
|
prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
prependListener(event: 'close', listener: () => void): this;
|
||||||
|
prependListener(event: 'drain', listener: () => void): this;
|
||||||
|
prependListener(event: 'error', listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: 'finish', listener: () => void): this;
|
||||||
|
prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: 'abort', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
prependOnceListener(event: 'continue', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this;
|
||||||
|
prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this;
|
||||||
|
prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this;
|
||||||
|
prependOnceListener(event: 'timeout', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
|
||||||
|
prependOnceListener(event: 'close', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'drain', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: 'finish', listener: () => void): this;
|
||||||
|
prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
class IncomingMessage extends stream.Readable {
|
||||||
|
constructor(socket: Socket);
|
||||||
|
|
||||||
|
httpVersion: string;
|
||||||
|
httpVersionMajor: number;
|
||||||
|
httpVersionMinor: number;
|
||||||
|
complete: boolean;
|
||||||
|
connection: Socket;
|
||||||
|
headers: IncomingHttpHeaders;
|
||||||
|
rawHeaders: string[];
|
||||||
|
trailers: { [key: string]: string | undefined };
|
||||||
|
rawTrailers: string[];
|
||||||
|
setTimeout(msecs: number, callback: () => void): this;
|
||||||
|
/**
|
||||||
|
* Only valid for request obtained from http.Server.
|
||||||
|
*/
|
||||||
|
method?: string;
|
||||||
|
/**
|
||||||
|
* Only valid for request obtained from http.Server.
|
||||||
|
*/
|
||||||
|
url?: string;
|
||||||
|
/**
|
||||||
|
* Only valid for response obtained from http.ClientRequest.
|
||||||
|
*/
|
||||||
|
statusCode?: number;
|
||||||
|
/**
|
||||||
|
* Only valid for response obtained from http.ClientRequest.
|
||||||
|
*/
|
||||||
|
statusMessage?: string;
|
||||||
|
socket: Socket;
|
||||||
|
destroy(error?: Error): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AgentOptions {
|
||||||
|
/**
|
||||||
|
* Keep sockets around in a pool to be used by other requests in the future. Default = false
|
||||||
|
*/
|
||||||
|
keepAlive?: boolean;
|
||||||
|
/**
|
||||||
|
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
|
||||||
|
* Only relevant if keepAlive is set to true.
|
||||||
|
*/
|
||||||
|
keepAliveMsecs?: number;
|
||||||
|
/**
|
||||||
|
* Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
|
||||||
|
*/
|
||||||
|
maxSockets?: number;
|
||||||
|
/**
|
||||||
|
* Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
|
||||||
|
*/
|
||||||
|
maxFreeSockets?: number;
|
||||||
|
/**
|
||||||
|
* Socket timeout in milliseconds. This will set the timeout after the socket is connected.
|
||||||
|
*/
|
||||||
|
timeout?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Agent {
|
||||||
|
maxFreeSockets: number;
|
||||||
|
maxSockets: number;
|
||||||
|
readonly sockets: {
|
||||||
|
readonly [key: string]: Socket[];
|
||||||
|
};
|
||||||
|
readonly requests: {
|
||||||
|
readonly [key: string]: IncomingMessage[];
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor(opts?: AgentOptions);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy any sockets that are currently in use by the agent.
|
||||||
|
* It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
|
||||||
|
* then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
|
||||||
|
* sockets may hang open for quite a long time before the server terminates them.
|
||||||
|
*/
|
||||||
|
destroy(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const METHODS: string[];
|
||||||
|
|
||||||
|
const STATUS_CODES: {
|
||||||
|
[errorCode: number]: string | undefined;
|
||||||
|
[errorCode: string]: string | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
function createServer(requestListener?: RequestListener): Server;
|
||||||
|
function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
|
||||||
|
|
||||||
|
// although RequestOptions are passed as ClientRequestArgs to ClientRequest directly,
|
||||||
|
// create interface RequestOptions would make the naming more clear to developers
|
||||||
|
interface RequestOptions extends ClientRequestArgs { }
|
||||||
|
function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
|
||||||
|
function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
|
||||||
|
function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
|
||||||
|
function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
|
||||||
|
let globalAgent: Agent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-only property specifying the maximum allowed size of HTTP headers in bytes.
|
||||||
|
* Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option.
|
||||||
|
*/
|
||||||
|
const maxHeaderSize: number;
|
||||||
|
}
|
||||||
+960
@@ -0,0 +1,960 @@
|
|||||||
|
declare module "http2" {
|
||||||
|
import * as events from "events";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import * as net from "net";
|
||||||
|
import * as stream from "stream";
|
||||||
|
import * as tls from "tls";
|
||||||
|
import * as url from "url";
|
||||||
|
|
||||||
|
import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from "http";
|
||||||
|
export { OutgoingHttpHeaders } from "http";
|
||||||
|
|
||||||
|
export interface IncomingHttpStatusHeader {
|
||||||
|
":status"?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders {
|
||||||
|
":path"?: string;
|
||||||
|
":method"?: string;
|
||||||
|
":authority"?: string;
|
||||||
|
":scheme"?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Http2Stream
|
||||||
|
|
||||||
|
export interface StreamPriorityOptions {
|
||||||
|
exclusive?: boolean;
|
||||||
|
parent?: number;
|
||||||
|
weight?: number;
|
||||||
|
silent?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StreamState {
|
||||||
|
localWindowSize?: number;
|
||||||
|
state?: number;
|
||||||
|
localClose?: number;
|
||||||
|
remoteClose?: number;
|
||||||
|
sumDependencyWeight?: number;
|
||||||
|
weight?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerStreamResponseOptions {
|
||||||
|
endStream?: boolean;
|
||||||
|
waitForTrailers?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatOptions {
|
||||||
|
offset: number;
|
||||||
|
length: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerStreamFileResponseOptions {
|
||||||
|
statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean;
|
||||||
|
waitForTrailers?: boolean;
|
||||||
|
offset?: number;
|
||||||
|
length?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions {
|
||||||
|
onError?: (err: NodeJS.ErrnoException) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2Stream extends stream.Duplex {
|
||||||
|
protected constructor();
|
||||||
|
|
||||||
|
readonly aborted: boolean;
|
||||||
|
readonly bufferSize: number;
|
||||||
|
readonly closed: boolean;
|
||||||
|
readonly destroyed: boolean;
|
||||||
|
/**
|
||||||
|
* Set the true if the END_STREAM flag was set in the request or response HEADERS frame received,
|
||||||
|
* indicating that no additional data should be received and the readable side of the Http2Stream will be closed.
|
||||||
|
*/
|
||||||
|
readonly endAfterHeaders: boolean;
|
||||||
|
readonly id?: number;
|
||||||
|
readonly pending: boolean;
|
||||||
|
readonly rstCode: number;
|
||||||
|
readonly sentHeaders: OutgoingHttpHeaders;
|
||||||
|
readonly sentInfoHeaders?: OutgoingHttpHeaders[];
|
||||||
|
readonly sentTrailers?: OutgoingHttpHeaders;
|
||||||
|
readonly session: Http2Session;
|
||||||
|
readonly state: StreamState;
|
||||||
|
|
||||||
|
close(code?: number, callback?: () => void): void;
|
||||||
|
priority(options: StreamPriorityOptions): void;
|
||||||
|
setTimeout(msecs: number, callback?: () => void): void;
|
||||||
|
sendTrailers(headers: OutgoingHttpHeaders): void;
|
||||||
|
|
||||||
|
addListener(event: "aborted", listener: () => void): this;
|
||||||
|
addListener(event: "close", listener: () => void): this;
|
||||||
|
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
addListener(event: "drain", listener: () => void): this;
|
||||||
|
addListener(event: "end", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "finish", listener: () => void): this;
|
||||||
|
addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
|
||||||
|
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: "streamClosed", listener: (code: number) => void): this;
|
||||||
|
addListener(event: "timeout", listener: () => void): this;
|
||||||
|
addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
addListener(event: "wantTrailers", listener: () => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "aborted"): boolean;
|
||||||
|
emit(event: "close"): boolean;
|
||||||
|
emit(event: "data", chunk: Buffer | string): boolean;
|
||||||
|
emit(event: "drain"): boolean;
|
||||||
|
emit(event: "end"): boolean;
|
||||||
|
emit(event: "error", err: Error): boolean;
|
||||||
|
emit(event: "finish"): boolean;
|
||||||
|
emit(event: "frameError", frameType: number, errorCode: number): boolean;
|
||||||
|
emit(event: "pipe", src: stream.Readable): boolean;
|
||||||
|
emit(event: "unpipe", src: stream.Readable): boolean;
|
||||||
|
emit(event: "streamClosed", code: number): boolean;
|
||||||
|
emit(event: "timeout"): boolean;
|
||||||
|
emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean;
|
||||||
|
emit(event: "wantTrailers"): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "aborted", listener: () => void): this;
|
||||||
|
on(event: "close", listener: () => void): this;
|
||||||
|
on(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
on(event: "drain", listener: () => void): this;
|
||||||
|
on(event: "end", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (err: Error) => void): this;
|
||||||
|
on(event: "finish", listener: () => void): this;
|
||||||
|
on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
|
||||||
|
on(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: "streamClosed", listener: (code: number) => void): this;
|
||||||
|
on(event: "timeout", listener: () => void): this;
|
||||||
|
on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
on(event: "wantTrailers", listener: () => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "aborted", listener: () => void): this;
|
||||||
|
once(event: "close", listener: () => void): this;
|
||||||
|
once(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
once(event: "drain", listener: () => void): this;
|
||||||
|
once(event: "end", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (err: Error) => void): this;
|
||||||
|
once(event: "finish", listener: () => void): this;
|
||||||
|
once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
|
||||||
|
once(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: "streamClosed", listener: (code: number) => void): this;
|
||||||
|
once(event: "timeout", listener: () => void): this;
|
||||||
|
once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
once(event: "wantTrailers", listener: () => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "aborted", listener: () => void): this;
|
||||||
|
prependListener(event: "close", listener: () => void): this;
|
||||||
|
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
prependListener(event: "drain", listener: () => void): this;
|
||||||
|
prependListener(event: "end", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "finish", listener: () => void): this;
|
||||||
|
prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
|
||||||
|
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: "streamClosed", listener: (code: number) => void): this;
|
||||||
|
prependListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependListener(event: "wantTrailers", listener: () => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "aborted", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "close", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
prependOnceListener(event: "drain", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "end", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "finish", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
|
||||||
|
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: "streamClosed", listener: (code: number) => void): this;
|
||||||
|
prependOnceListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: "wantTrailers", listener: () => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ClientHttp2Stream extends Http2Stream {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
addListener(event: "continue", listener: () => {}): this;
|
||||||
|
addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "continue"): boolean;
|
||||||
|
emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
|
||||||
|
emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean;
|
||||||
|
emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "continue", listener: () => {}): this;
|
||||||
|
on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "continue", listener: () => {}): this;
|
||||||
|
once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "continue", listener: () => {}): this;
|
||||||
|
prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "continue", listener: () => {}): this;
|
||||||
|
prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerHttp2Stream extends Http2Stream {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
additionalHeaders(headers: OutgoingHttpHeaders): void;
|
||||||
|
readonly headersSent: boolean;
|
||||||
|
readonly pushAllowed: boolean;
|
||||||
|
pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void;
|
||||||
|
pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void;
|
||||||
|
respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void;
|
||||||
|
respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void;
|
||||||
|
respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Http2Session
|
||||||
|
|
||||||
|
export interface Settings {
|
||||||
|
headerTableSize?: number;
|
||||||
|
enablePush?: boolean;
|
||||||
|
initialWindowSize?: number;
|
||||||
|
maxFrameSize?: number;
|
||||||
|
maxConcurrentStreams?: number;
|
||||||
|
maxHeaderListSize?: number;
|
||||||
|
enableConnectProtocol?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientSessionRequestOptions {
|
||||||
|
endStream?: boolean;
|
||||||
|
exclusive?: boolean;
|
||||||
|
parent?: number;
|
||||||
|
weight?: number;
|
||||||
|
waitForTrailers?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionState {
|
||||||
|
effectiveLocalWindowSize?: number;
|
||||||
|
effectiveRecvDataLength?: number;
|
||||||
|
nextStreamID?: number;
|
||||||
|
localWindowSize?: number;
|
||||||
|
lastProcStreamID?: number;
|
||||||
|
remoteWindowSize?: number;
|
||||||
|
outboundQueueSize?: number;
|
||||||
|
deflateDynamicTableSize?: number;
|
||||||
|
inflateDynamicTableSize?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2Session extends events.EventEmitter {
|
||||||
|
protected constructor();
|
||||||
|
|
||||||
|
readonly alpnProtocol?: string;
|
||||||
|
close(callback?: () => void): void;
|
||||||
|
readonly closed: boolean;
|
||||||
|
readonly connecting: boolean;
|
||||||
|
destroy(error?: Error, code?: number): void;
|
||||||
|
readonly destroyed: boolean;
|
||||||
|
readonly encrypted?: boolean;
|
||||||
|
goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void;
|
||||||
|
readonly localSettings: Settings;
|
||||||
|
readonly originSet?: string[];
|
||||||
|
readonly pendingSettingsAck: boolean;
|
||||||
|
ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean;
|
||||||
|
ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean;
|
||||||
|
ref(): void;
|
||||||
|
readonly remoteSettings: Settings;
|
||||||
|
setTimeout(msecs: number, callback?: () => void): void;
|
||||||
|
readonly socket: net.Socket | tls.TLSSocket;
|
||||||
|
readonly state: SessionState;
|
||||||
|
settings(settings: Settings): void;
|
||||||
|
readonly type: number;
|
||||||
|
unref(): void;
|
||||||
|
|
||||||
|
addListener(event: "close", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
|
||||||
|
addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this;
|
||||||
|
addListener(event: "localSettings", listener: (settings: Settings) => void): this;
|
||||||
|
addListener(event: "ping", listener: () => void): this;
|
||||||
|
addListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
|
||||||
|
addListener(event: "timeout", listener: () => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "close"): boolean;
|
||||||
|
emit(event: "error", err: Error): boolean;
|
||||||
|
emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean;
|
||||||
|
emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean;
|
||||||
|
emit(event: "localSettings", settings: Settings): boolean;
|
||||||
|
emit(event: "ping"): boolean;
|
||||||
|
emit(event: "remoteSettings", settings: Settings): boolean;
|
||||||
|
emit(event: "timeout"): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "close", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (err: Error) => void): this;
|
||||||
|
on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
|
||||||
|
on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this;
|
||||||
|
on(event: "localSettings", listener: (settings: Settings) => void): this;
|
||||||
|
on(event: "ping", listener: () => void): this;
|
||||||
|
on(event: "remoteSettings", listener: (settings: Settings) => void): this;
|
||||||
|
on(event: "timeout", listener: () => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "close", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (err: Error) => void): this;
|
||||||
|
once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
|
||||||
|
once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this;
|
||||||
|
once(event: "localSettings", listener: (settings: Settings) => void): this;
|
||||||
|
once(event: "ping", listener: () => void): this;
|
||||||
|
once(event: "remoteSettings", listener: (settings: Settings) => void): this;
|
||||||
|
once(event: "timeout", listener: () => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "close", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
|
||||||
|
prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this;
|
||||||
|
prependListener(event: "localSettings", listener: (settings: Settings) => void): this;
|
||||||
|
prependListener(event: "ping", listener: () => void): this;
|
||||||
|
prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
|
||||||
|
prependListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "close", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
|
||||||
|
prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this;
|
||||||
|
prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this;
|
||||||
|
prependOnceListener(event: "ping", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
|
||||||
|
prependOnceListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ClientHttp2Session extends Http2Session {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream;
|
||||||
|
|
||||||
|
addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
|
||||||
|
addListener(event: "origin", listener: (origins: string[]) => void): this;
|
||||||
|
addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "altsvc", alt: string, origin: string, stream: number): boolean;
|
||||||
|
emit(event: "origin", origins: string[]): boolean;
|
||||||
|
emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean;
|
||||||
|
emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
|
||||||
|
on(event: "origin", listener: (origins: string[]) => void): this;
|
||||||
|
on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
|
||||||
|
once(event: "origin", listener: (origins: string[]) => void): this;
|
||||||
|
once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
|
||||||
|
prependListener(event: "origin", listener: (origins: string[]) => void): this;
|
||||||
|
prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
|
||||||
|
prependOnceListener(event: "origin", listener: (origins: string[]) => void): this;
|
||||||
|
prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AlternativeServiceOptions {
|
||||||
|
origin: number | string | url.URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerHttp2Session extends Http2Session {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void;
|
||||||
|
origin(...args: Array<string | url.URL | { origin: string }>): void;
|
||||||
|
readonly server: Http2Server | Http2SecureServer;
|
||||||
|
|
||||||
|
addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean;
|
||||||
|
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
|
||||||
|
prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Http2Server
|
||||||
|
|
||||||
|
export interface SessionOptions {
|
||||||
|
maxDeflateDynamicTableSize?: number;
|
||||||
|
maxSessionMemory?: number;
|
||||||
|
maxHeaderListPairs?: number;
|
||||||
|
maxOutstandingPings?: number;
|
||||||
|
maxSendHeaderBlockLength?: number;
|
||||||
|
paddingStrategy?: number;
|
||||||
|
peerMaxConcurrentStreams?: number;
|
||||||
|
selectPadding?: (frameLen: number, maxFrameLen: number) => number;
|
||||||
|
settings?: Settings;
|
||||||
|
createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientSessionOptions extends SessionOptions {
|
||||||
|
maxReservedRemoteStreams?: number;
|
||||||
|
createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerSessionOptions extends SessionOptions {
|
||||||
|
Http1IncomingMessage?: typeof IncomingMessage;
|
||||||
|
Http1ServerResponse?: typeof ServerResponse;
|
||||||
|
Http2ServerRequest?: typeof Http2ServerRequest;
|
||||||
|
Http2ServerResponse?: typeof Http2ServerResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { }
|
||||||
|
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { }
|
||||||
|
|
||||||
|
export interface ServerOptions extends ServerSessionOptions { }
|
||||||
|
|
||||||
|
export interface SecureServerOptions extends SecureServerSessionOptions {
|
||||||
|
allowHTTP1?: boolean;
|
||||||
|
origins?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2Server extends net.Server {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
addListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
addListener(event: "timeout", listener: () => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
|
||||||
|
emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
|
||||||
|
emit(event: "session", session: ServerHttp2Session): boolean;
|
||||||
|
emit(event: "sessionError", err: Error): boolean;
|
||||||
|
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
|
||||||
|
emit(event: "timeout"): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
on(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
on(event: "timeout", listener: () => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
once(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
once(event: "timeout", listener: () => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
prependListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
setTimeout(msec?: number, callback?: () => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2SecureServer extends tls.Server {
|
||||||
|
private constructor();
|
||||||
|
|
||||||
|
addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
addListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
addListener(event: "timeout", listener: () => void): this;
|
||||||
|
addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
|
||||||
|
emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
|
||||||
|
emit(event: "session", session: ServerHttp2Session): boolean;
|
||||||
|
emit(event: "sessionError", err: Error): boolean;
|
||||||
|
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
|
||||||
|
emit(event: "timeout"): boolean;
|
||||||
|
emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
on(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
on(event: "timeout", listener: () => void): this;
|
||||||
|
on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
once(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
once(event: "timeout", listener: () => void): this;
|
||||||
|
once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
prependListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
|
||||||
|
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
|
||||||
|
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this;
|
||||||
|
prependOnceListener(event: "timeout", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
setTimeout(msec?: number, callback?: () => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2ServerRequest extends stream.Readable {
|
||||||
|
constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: string[]);
|
||||||
|
|
||||||
|
readonly aborted: boolean;
|
||||||
|
readonly authority: string;
|
||||||
|
readonly headers: IncomingHttpHeaders;
|
||||||
|
readonly httpVersion: string;
|
||||||
|
readonly method: string;
|
||||||
|
readonly rawHeaders: string[];
|
||||||
|
readonly rawTrailers: string[];
|
||||||
|
readonly scheme: string;
|
||||||
|
setTimeout(msecs: number, callback?: () => void): void;
|
||||||
|
readonly socket: net.Socket | tls.TLSSocket;
|
||||||
|
readonly stream: ServerHttp2Stream;
|
||||||
|
readonly trailers: IncomingHttpHeaders;
|
||||||
|
readonly url: string;
|
||||||
|
|
||||||
|
read(size?: number): Buffer | string | null;
|
||||||
|
|
||||||
|
addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
|
||||||
|
addListener(event: "close", listener: () => void): this;
|
||||||
|
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
addListener(event: "end", listener: () => void): this;
|
||||||
|
addListener(event: "readable", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "aborted", hadError: boolean, code: number): boolean;
|
||||||
|
emit(event: "close"): boolean;
|
||||||
|
emit(event: "data", chunk: Buffer | string): boolean;
|
||||||
|
emit(event: "end"): boolean;
|
||||||
|
emit(event: "readable"): boolean;
|
||||||
|
emit(event: "error", err: Error): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
|
||||||
|
on(event: "close", listener: () => void): this;
|
||||||
|
on(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
on(event: "end", listener: () => void): this;
|
||||||
|
on(event: "readable", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (err: Error) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
|
||||||
|
once(event: "close", listener: () => void): this;
|
||||||
|
once(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
once(event: "end", listener: () => void): this;
|
||||||
|
once(event: "readable", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (err: Error) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
|
||||||
|
prependListener(event: "close", listener: () => void): this;
|
||||||
|
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
prependListener(event: "end", listener: () => void): this;
|
||||||
|
prependListener(event: "readable", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
|
||||||
|
prependOnceListener(event: "close", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
|
||||||
|
prependOnceListener(event: "end", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "readable", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http2ServerResponse extends stream.Stream {
|
||||||
|
constructor(stream: ServerHttp2Stream);
|
||||||
|
|
||||||
|
addTrailers(trailers: OutgoingHttpHeaders): void;
|
||||||
|
readonly connection: net.Socket | tls.TLSSocket;
|
||||||
|
end(callback?: () => void): void;
|
||||||
|
end(data: string | Uint8Array, callback?: () => void): void;
|
||||||
|
end(data: string | Uint8Array, encoding: string, callback?: () => void): void;
|
||||||
|
readonly finished: boolean;
|
||||||
|
getHeader(name: string): string;
|
||||||
|
getHeaderNames(): string[];
|
||||||
|
getHeaders(): OutgoingHttpHeaders;
|
||||||
|
hasHeader(name: string): boolean;
|
||||||
|
readonly headersSent: boolean;
|
||||||
|
removeHeader(name: string): void;
|
||||||
|
sendDate: boolean;
|
||||||
|
setHeader(name: string, value: number | string | string[]): void;
|
||||||
|
setTimeout(msecs: number, callback?: () => void): void;
|
||||||
|
readonly socket: net.Socket | tls.TLSSocket;
|
||||||
|
statusCode: number;
|
||||||
|
statusMessage: '';
|
||||||
|
readonly stream: ServerHttp2Stream;
|
||||||
|
write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean;
|
||||||
|
write(chunk: string | Uint8Array, encoding: string, callback?: (err: Error) => void): boolean;
|
||||||
|
writeContinue(): void;
|
||||||
|
writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this;
|
||||||
|
writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this;
|
||||||
|
createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void;
|
||||||
|
|
||||||
|
addListener(event: "close", listener: () => void): this;
|
||||||
|
addListener(event: "drain", listener: () => void): this;
|
||||||
|
addListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
addListener(event: "finish", listener: () => void): this;
|
||||||
|
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
emit(event: "close"): boolean;
|
||||||
|
emit(event: "drain"): boolean;
|
||||||
|
emit(event: "error", error: Error): boolean;
|
||||||
|
emit(event: "finish"): boolean;
|
||||||
|
emit(event: "pipe", src: stream.Readable): boolean;
|
||||||
|
emit(event: "unpipe", src: stream.Readable): boolean;
|
||||||
|
emit(event: string | symbol, ...args: any[]): boolean;
|
||||||
|
|
||||||
|
on(event: "close", listener: () => void): this;
|
||||||
|
on(event: "drain", listener: () => void): this;
|
||||||
|
on(event: "error", listener: (error: Error) => void): this;
|
||||||
|
on(event: "finish", listener: () => void): this;
|
||||||
|
on(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
once(event: "close", listener: () => void): this;
|
||||||
|
once(event: "drain", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (error: Error) => void): this;
|
||||||
|
once(event: "finish", listener: () => void): this;
|
||||||
|
once(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependListener(event: "close", listener: () => void): this;
|
||||||
|
prependListener(event: "drain", listener: () => void): this;
|
||||||
|
prependListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
prependListener(event: "finish", listener: () => void): this;
|
||||||
|
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
|
||||||
|
prependOnceListener(event: "close", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "drain", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "error", listener: (error: Error) => void): this;
|
||||||
|
prependOnceListener(event: "finish", listener: () => void): this;
|
||||||
|
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
|
||||||
|
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public API
|
||||||
|
|
||||||
|
export namespace constants {
|
||||||
|
const NGHTTP2_SESSION_SERVER: number;
|
||||||
|
const NGHTTP2_SESSION_CLIENT: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_IDLE: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_OPEN: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number;
|
||||||
|
const NGHTTP2_STREAM_STATE_CLOSED: number;
|
||||||
|
const NGHTTP2_NO_ERROR: number;
|
||||||
|
const NGHTTP2_PROTOCOL_ERROR: number;
|
||||||
|
const NGHTTP2_INTERNAL_ERROR: number;
|
||||||
|
const NGHTTP2_FLOW_CONTROL_ERROR: number;
|
||||||
|
const NGHTTP2_SETTINGS_TIMEOUT: number;
|
||||||
|
const NGHTTP2_STREAM_CLOSED: number;
|
||||||
|
const NGHTTP2_FRAME_SIZE_ERROR: number;
|
||||||
|
const NGHTTP2_REFUSED_STREAM: number;
|
||||||
|
const NGHTTP2_CANCEL: number;
|
||||||
|
const NGHTTP2_COMPRESSION_ERROR: number;
|
||||||
|
const NGHTTP2_CONNECT_ERROR: number;
|
||||||
|
const NGHTTP2_ENHANCE_YOUR_CALM: number;
|
||||||
|
const NGHTTP2_INADEQUATE_SECURITY: number;
|
||||||
|
const NGHTTP2_HTTP_1_1_REQUIRED: number;
|
||||||
|
const NGHTTP2_ERR_FRAME_SIZE_ERROR: number;
|
||||||
|
const NGHTTP2_FLAG_NONE: number;
|
||||||
|
const NGHTTP2_FLAG_END_STREAM: number;
|
||||||
|
const NGHTTP2_FLAG_END_HEADERS: number;
|
||||||
|
const NGHTTP2_FLAG_ACK: number;
|
||||||
|
const NGHTTP2_FLAG_PADDED: number;
|
||||||
|
const NGHTTP2_FLAG_PRIORITY: number;
|
||||||
|
const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number;
|
||||||
|
const DEFAULT_SETTINGS_ENABLE_PUSH: number;
|
||||||
|
const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number;
|
||||||
|
const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number;
|
||||||
|
const MAX_MAX_FRAME_SIZE: number;
|
||||||
|
const MIN_MAX_FRAME_SIZE: number;
|
||||||
|
const MAX_INITIAL_WINDOW_SIZE: number;
|
||||||
|
const NGHTTP2_DEFAULT_WEIGHT: number;
|
||||||
|
const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number;
|
||||||
|
const NGHTTP2_SETTINGS_ENABLE_PUSH: number;
|
||||||
|
const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number;
|
||||||
|
const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number;
|
||||||
|
const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number;
|
||||||
|
const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number;
|
||||||
|
const PADDING_STRATEGY_NONE: number;
|
||||||
|
const PADDING_STRATEGY_MAX: number;
|
||||||
|
const PADDING_STRATEGY_CALLBACK: number;
|
||||||
|
const HTTP2_HEADER_STATUS: string;
|
||||||
|
const HTTP2_HEADER_METHOD: string;
|
||||||
|
const HTTP2_HEADER_AUTHORITY: string;
|
||||||
|
const HTTP2_HEADER_SCHEME: string;
|
||||||
|
const HTTP2_HEADER_PATH: string;
|
||||||
|
const HTTP2_HEADER_ACCEPT_CHARSET: string;
|
||||||
|
const HTTP2_HEADER_ACCEPT_ENCODING: string;
|
||||||
|
const HTTP2_HEADER_ACCEPT_LANGUAGE: string;
|
||||||
|
const HTTP2_HEADER_ACCEPT_RANGES: string;
|
||||||
|
const HTTP2_HEADER_ACCEPT: string;
|
||||||
|
const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string;
|
||||||
|
const HTTP2_HEADER_AGE: string;
|
||||||
|
const HTTP2_HEADER_ALLOW: string;
|
||||||
|
const HTTP2_HEADER_AUTHORIZATION: string;
|
||||||
|
const HTTP2_HEADER_CACHE_CONTROL: string;
|
||||||
|
const HTTP2_HEADER_CONNECTION: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_DISPOSITION: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_ENCODING: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_LANGUAGE: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_LENGTH: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_LOCATION: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_MD5: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_RANGE: string;
|
||||||
|
const HTTP2_HEADER_CONTENT_TYPE: string;
|
||||||
|
const HTTP2_HEADER_COOKIE: string;
|
||||||
|
const HTTP2_HEADER_DATE: string;
|
||||||
|
const HTTP2_HEADER_ETAG: string;
|
||||||
|
const HTTP2_HEADER_EXPECT: string;
|
||||||
|
const HTTP2_HEADER_EXPIRES: string;
|
||||||
|
const HTTP2_HEADER_FROM: string;
|
||||||
|
const HTTP2_HEADER_HOST: string;
|
||||||
|
const HTTP2_HEADER_IF_MATCH: string;
|
||||||
|
const HTTP2_HEADER_IF_MODIFIED_SINCE: string;
|
||||||
|
const HTTP2_HEADER_IF_NONE_MATCH: string;
|
||||||
|
const HTTP2_HEADER_IF_RANGE: string;
|
||||||
|
const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string;
|
||||||
|
const HTTP2_HEADER_LAST_MODIFIED: string;
|
||||||
|
const HTTP2_HEADER_LINK: string;
|
||||||
|
const HTTP2_HEADER_LOCATION: string;
|
||||||
|
const HTTP2_HEADER_MAX_FORWARDS: string;
|
||||||
|
const HTTP2_HEADER_PREFER: string;
|
||||||
|
const HTTP2_HEADER_PROXY_AUTHENTICATE: string;
|
||||||
|
const HTTP2_HEADER_PROXY_AUTHORIZATION: string;
|
||||||
|
const HTTP2_HEADER_RANGE: string;
|
||||||
|
const HTTP2_HEADER_REFERER: string;
|
||||||
|
const HTTP2_HEADER_REFRESH: string;
|
||||||
|
const HTTP2_HEADER_RETRY_AFTER: string;
|
||||||
|
const HTTP2_HEADER_SERVER: string;
|
||||||
|
const HTTP2_HEADER_SET_COOKIE: string;
|
||||||
|
const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string;
|
||||||
|
const HTTP2_HEADER_TRANSFER_ENCODING: string;
|
||||||
|
const HTTP2_HEADER_TE: string;
|
||||||
|
const HTTP2_HEADER_UPGRADE: string;
|
||||||
|
const HTTP2_HEADER_USER_AGENT: string;
|
||||||
|
const HTTP2_HEADER_VARY: string;
|
||||||
|
const HTTP2_HEADER_VIA: string;
|
||||||
|
const HTTP2_HEADER_WWW_AUTHENTICATE: string;
|
||||||
|
const HTTP2_HEADER_HTTP2_SETTINGS: string;
|
||||||
|
const HTTP2_HEADER_KEEP_ALIVE: string;
|
||||||
|
const HTTP2_HEADER_PROXY_CONNECTION: string;
|
||||||
|
const HTTP2_METHOD_ACL: string;
|
||||||
|
const HTTP2_METHOD_BASELINE_CONTROL: string;
|
||||||
|
const HTTP2_METHOD_BIND: string;
|
||||||
|
const HTTP2_METHOD_CHECKIN: string;
|
||||||
|
const HTTP2_METHOD_CHECKOUT: string;
|
||||||
|
const HTTP2_METHOD_CONNECT: string;
|
||||||
|
const HTTP2_METHOD_COPY: string;
|
||||||
|
const HTTP2_METHOD_DELETE: string;
|
||||||
|
const HTTP2_METHOD_GET: string;
|
||||||
|
const HTTP2_METHOD_HEAD: string;
|
||||||
|
const HTTP2_METHOD_LABEL: string;
|
||||||
|
const HTTP2_METHOD_LINK: string;
|
||||||
|
const HTTP2_METHOD_LOCK: string;
|
||||||
|
const HTTP2_METHOD_MERGE: string;
|
||||||
|
const HTTP2_METHOD_MKACTIVITY: string;
|
||||||
|
const HTTP2_METHOD_MKCALENDAR: string;
|
||||||
|
const HTTP2_METHOD_MKCOL: string;
|
||||||
|
const HTTP2_METHOD_MKREDIRECTREF: string;
|
||||||
|
const HTTP2_METHOD_MKWORKSPACE: string;
|
||||||
|
const HTTP2_METHOD_MOVE: string;
|
||||||
|
const HTTP2_METHOD_OPTIONS: string;
|
||||||
|
const HTTP2_METHOD_ORDERPATCH: string;
|
||||||
|
const HTTP2_METHOD_PATCH: string;
|
||||||
|
const HTTP2_METHOD_POST: string;
|
||||||
|
const HTTP2_METHOD_PRI: string;
|
||||||
|
const HTTP2_METHOD_PROPFIND: string;
|
||||||
|
const HTTP2_METHOD_PROPPATCH: string;
|
||||||
|
const HTTP2_METHOD_PUT: string;
|
||||||
|
const HTTP2_METHOD_REBIND: string;
|
||||||
|
const HTTP2_METHOD_REPORT: string;
|
||||||
|
const HTTP2_METHOD_SEARCH: string;
|
||||||
|
const HTTP2_METHOD_TRACE: string;
|
||||||
|
const HTTP2_METHOD_UNBIND: string;
|
||||||
|
const HTTP2_METHOD_UNCHECKOUT: string;
|
||||||
|
const HTTP2_METHOD_UNLINK: string;
|
||||||
|
const HTTP2_METHOD_UNLOCK: string;
|
||||||
|
const HTTP2_METHOD_UPDATE: string;
|
||||||
|
const HTTP2_METHOD_UPDATEREDIRECTREF: string;
|
||||||
|
const HTTP2_METHOD_VERSION_CONTROL: string;
|
||||||
|
const HTTP_STATUS_CONTINUE: number;
|
||||||
|
const HTTP_STATUS_SWITCHING_PROTOCOLS: number;
|
||||||
|
const HTTP_STATUS_PROCESSING: number;
|
||||||
|
const HTTP_STATUS_OK: number;
|
||||||
|
const HTTP_STATUS_CREATED: number;
|
||||||
|
const HTTP_STATUS_ACCEPTED: number;
|
||||||
|
const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number;
|
||||||
|
const HTTP_STATUS_NO_CONTENT: number;
|
||||||
|
const HTTP_STATUS_RESET_CONTENT: number;
|
||||||
|
const HTTP_STATUS_PARTIAL_CONTENT: number;
|
||||||
|
const HTTP_STATUS_MULTI_STATUS: number;
|
||||||
|
const HTTP_STATUS_ALREADY_REPORTED: number;
|
||||||
|
const HTTP_STATUS_IM_USED: number;
|
||||||
|
const HTTP_STATUS_MULTIPLE_CHOICES: number;
|
||||||
|
const HTTP_STATUS_MOVED_PERMANENTLY: number;
|
||||||
|
const HTTP_STATUS_FOUND: number;
|
||||||
|
const HTTP_STATUS_SEE_OTHER: number;
|
||||||
|
const HTTP_STATUS_NOT_MODIFIED: number;
|
||||||
|
const HTTP_STATUS_USE_PROXY: number;
|
||||||
|
const HTTP_STATUS_TEMPORARY_REDIRECT: number;
|
||||||
|
const HTTP_STATUS_PERMANENT_REDIRECT: number;
|
||||||
|
const HTTP_STATUS_BAD_REQUEST: number;
|
||||||
|
const HTTP_STATUS_UNAUTHORIZED: number;
|
||||||
|
const HTTP_STATUS_PAYMENT_REQUIRED: number;
|
||||||
|
const HTTP_STATUS_FORBIDDEN: number;
|
||||||
|
const HTTP_STATUS_NOT_FOUND: number;
|
||||||
|
const HTTP_STATUS_METHOD_NOT_ALLOWED: number;
|
||||||
|
const HTTP_STATUS_NOT_ACCEPTABLE: number;
|
||||||
|
const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number;
|
||||||
|
const HTTP_STATUS_REQUEST_TIMEOUT: number;
|
||||||
|
const HTTP_STATUS_CONFLICT: number;
|
||||||
|
const HTTP_STATUS_GONE: number;
|
||||||
|
const HTTP_STATUS_LENGTH_REQUIRED: number;
|
||||||
|
const HTTP_STATUS_PRECONDITION_FAILED: number;
|
||||||
|
const HTTP_STATUS_PAYLOAD_TOO_LARGE: number;
|
||||||
|
const HTTP_STATUS_URI_TOO_LONG: number;
|
||||||
|
const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number;
|
||||||
|
const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number;
|
||||||
|
const HTTP_STATUS_EXPECTATION_FAILED: number;
|
||||||
|
const HTTP_STATUS_TEAPOT: number;
|
||||||
|
const HTTP_STATUS_MISDIRECTED_REQUEST: number;
|
||||||
|
const HTTP_STATUS_UNPROCESSABLE_ENTITY: number;
|
||||||
|
const HTTP_STATUS_LOCKED: number;
|
||||||
|
const HTTP_STATUS_FAILED_DEPENDENCY: number;
|
||||||
|
const HTTP_STATUS_UNORDERED_COLLECTION: number;
|
||||||
|
const HTTP_STATUS_UPGRADE_REQUIRED: number;
|
||||||
|
const HTTP_STATUS_PRECONDITION_REQUIRED: number;
|
||||||
|
const HTTP_STATUS_TOO_MANY_REQUESTS: number;
|
||||||
|
const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number;
|
||||||
|
const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number;
|
||||||
|
const HTTP_STATUS_INTERNAL_SERVER_ERROR: number;
|
||||||
|
const HTTP_STATUS_NOT_IMPLEMENTED: number;
|
||||||
|
const HTTP_STATUS_BAD_GATEWAY: number;
|
||||||
|
const HTTP_STATUS_SERVICE_UNAVAILABLE: number;
|
||||||
|
const HTTP_STATUS_GATEWAY_TIMEOUT: number;
|
||||||
|
const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number;
|
||||||
|
const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number;
|
||||||
|
const HTTP_STATUS_INSUFFICIENT_STORAGE: number;
|
||||||
|
const HTTP_STATUS_LOOP_DETECTED: number;
|
||||||
|
const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number;
|
||||||
|
const HTTP_STATUS_NOT_EXTENDED: number;
|
||||||
|
const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDefaultSettings(): Settings;
|
||||||
|
export function getPackedSettings(settings: Settings): Buffer;
|
||||||
|
export function getUnpackedSettings(buf: Uint8Array): Settings;
|
||||||
|
|
||||||
|
export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server;
|
||||||
|
export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server;
|
||||||
|
|
||||||
|
export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer;
|
||||||
|
export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer;
|
||||||
|
|
||||||
|
export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session;
|
||||||
|
export function connect(
|
||||||
|
authority: string | url.URL,
|
||||||
|
options?: ClientSessionOptions | SecureClientSessionOptions,
|
||||||
|
listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
|
||||||
|
): ClientHttp2Session;
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
declare module "https" {
|
||||||
|
import * as tls from "tls";
|
||||||
|
import * as events from "events";
|
||||||
|
import * as http from "http";
|
||||||
|
import { URL } from "url";
|
||||||
|
|
||||||
|
type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions;
|
||||||
|
|
||||||
|
type RequestOptions = http.RequestOptions & tls.SecureContextOptions & {
|
||||||
|
rejectUnauthorized?: boolean; // Defaults to true
|
||||||
|
servername?: string; // SNI TLS Extension
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
|
||||||
|
rejectUnauthorized?: boolean;
|
||||||
|
maxCachedSessions?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Agent extends http.Agent {
|
||||||
|
constructor(options?: AgentOptions);
|
||||||
|
options: AgentOptions;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Server extends tls.Server {
|
||||||
|
constructor(requestListener?: http.RequestListener);
|
||||||
|
constructor(options: ServerOptions, requestListener?: http.RequestListener);
|
||||||
|
|
||||||
|
setTimeout(callback: () => void): this;
|
||||||
|
setTimeout(msecs?: number, callback?: () => void): this;
|
||||||
|
/**
|
||||||
|
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
|
||||||
|
* @default 2000
|
||||||
|
* {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
|
||||||
|
*/
|
||||||
|
maxHeadersCount: number | null;
|
||||||
|
timeout: number;
|
||||||
|
/**
|
||||||
|
* Limit the amount of time the parser will wait to receive the complete HTTP headers.
|
||||||
|
* @default 40000
|
||||||
|
* {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
|
||||||
|
*/
|
||||||
|
headersTimeout: number;
|
||||||
|
keepAliveTimeout: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createServer(requestListener?: http.RequestListener): Server;
|
||||||
|
function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server;
|
||||||
|
function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
|
||||||
|
function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
|
||||||
|
function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
|
||||||
|
function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
|
||||||
|
let globalAgent: Agent;
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
// Type definitions for non-npm package Node.js 12.7
|
||||||
|
// Project: http://nodejs.org/
|
||||||
|
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
|
||||||
|
// DefinitelyTyped <https://github.com/DefinitelyTyped>
|
||||||
|
// Alberto Schiabel <https://github.com/jkomyno>
|
||||||
|
// Alexander T. <https://github.com/a-tarasyuk>
|
||||||
|
// Alvis HT Tang <https://github.com/alvis>
|
||||||
|
// Andrew Makarov <https://github.com/r3nya>
|
||||||
|
// Benjamin Toueg <https://github.com/btoueg>
|
||||||
|
// Bruno Scheufler <https://github.com/brunoscheufler>
|
||||||
|
// Chigozirim C. <https://github.com/smac89>
|
||||||
|
// Christian Vaagland Tellnes <https://github.com/tellnes>
|
||||||
|
// David Junger <https://github.com/touffy>
|
||||||
|
// Deividas Bakanas <https://github.com/DeividasBakanas>
|
||||||
|
// Eugene Y. Q. Shen <https://github.com/eyqs>
|
||||||
|
// Flarna <https://github.com/Flarna>
|
||||||
|
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
|
||||||
|
// Hoàng Văn Khải <https://github.com/KSXGitHub>
|
||||||
|
// Huw <https://github.com/hoo29>
|
||||||
|
// Kelvin Jin <https://github.com/kjin>
|
||||||
|
// Klaus Meinhardt <https://github.com/ajafff>
|
||||||
|
// Lishude <https://github.com/islishude>
|
||||||
|
// Mariusz Wiktorczyk <https://github.com/mwiktorczyk>
|
||||||
|
// Matthieu Sieben <https://github.com/matthieusieben>
|
||||||
|
// Mohsen Azimi <https://github.com/mohsen1>
|
||||||
|
// Nicolas Even <https://github.com/n-e>
|
||||||
|
// Nicolas Voigt <https://github.com/octo-sniffle>
|
||||||
|
// Parambir Singh <https://github.com/parambirs>
|
||||||
|
// Sebastian Silbermann <https://github.com/eps1lon>
|
||||||
|
// Simon Schick <https://github.com/SimonSchick>
|
||||||
|
// Thomas den Hollander <https://github.com/ThomasdenH>
|
||||||
|
// Wilco Bakker <https://github.com/WilcoBakker>
|
||||||
|
// wwwy3y3 <https://github.com/wwwy3y3>
|
||||||
|
// Zane Hannan AU <https://github.com/ZaneHannanAU>
|
||||||
|
// Samuel Ainsworth <https://github.com/samuela>
|
||||||
|
// Kyle Uehlein <https://github.com/kuehlein>
|
||||||
|
// Jordi Oliveras Rovira <https://github.com/j-oliveras>
|
||||||
|
// Thanik Bhongbhibhat <https://github.com/bhongy>
|
||||||
|
// Marcin Kopacz <https://github.com/chyzwar>
|
||||||
|
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||||
|
|
||||||
|
// NOTE: These definitions support NodeJS and TypeScript 3.2.
|
||||||
|
|
||||||
|
// NOTE: TypeScript version-specific augmentations can be found in the following paths:
|
||||||
|
// - ~/base.d.ts - Shared definitions common to all TypeScript versions
|
||||||
|
// - ~/index.d.ts - Definitions specific to TypeScript 2.1
|
||||||
|
// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2
|
||||||
|
|
||||||
|
// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides
|
||||||
|
// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions
|
||||||
|
// prior to TypeScript 3.2, so the older definitions will be found here.
|
||||||
|
|
||||||
|
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
|
||||||
|
/// <reference path="base.d.ts" />
|
||||||
|
|
||||||
|
// TypeScript 2.1-specific augmentations:
|
||||||
|
|
||||||
|
// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`)
|
||||||
|
// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files
|
||||||
|
// just to ensure the names are known and node typings can be sued without importing these libs.
|
||||||
|
// if someone really needs these types the libs need to be added via --lib or in tsconfig.json
|
||||||
|
interface MapConstructor { }
|
||||||
|
interface WeakMapConstructor { }
|
||||||
|
interface SetConstructor { }
|
||||||
|
interface WeakSetConstructor { }
|
||||||
|
interface Set<T> {}
|
||||||
|
interface Map<K, V> {}
|
||||||
|
interface ReadonlySet<T> {}
|
||||||
|
interface IteratorResult<T> { }
|
||||||
|
interface Iterable<T> { }
|
||||||
|
interface AsyncIterable<T> { }
|
||||||
|
interface Iterator<T> {
|
||||||
|
next(value?: any): IteratorResult<T>;
|
||||||
|
}
|
||||||
|
interface IterableIterator<T> { }
|
||||||
|
interface AsyncIterableIterator<T> {}
|
||||||
|
interface SymbolConstructor {
|
||||||
|
readonly iterator: symbol;
|
||||||
|
readonly asyncIterator: symbol;
|
||||||
|
}
|
||||||
|
declare var Symbol: SymbolConstructor;
|
||||||
|
// even this is just a forward declaration some properties are added otherwise
|
||||||
|
// it would be allowed to pass anything to e.g. Buffer.from()
|
||||||
|
interface SharedArrayBuffer {
|
||||||
|
readonly byteLength: number;
|
||||||
|
slice(begin?: number, end?: number): SharedArrayBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "util" {
|
||||||
|
namespace inspect {
|
||||||
|
const custom: symbol;
|
||||||
|
}
|
||||||
|
namespace promisify {
|
||||||
|
const custom: symbol;
|
||||||
|
}
|
||||||
|
namespace types {
|
||||||
|
function isBigInt64Array(value: any): boolean;
|
||||||
|
function isBigUint64Array(value: any): boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
+3034
File diff suppressed because it is too large
Load Diff
+3
@@ -0,0 +1,3 @@
|
|||||||
|
declare module "module" {
|
||||||
|
export = NodeJS.Module;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user