1
0
mirror of https://github.com/winsw/winsw.git synced 2024-11-16 10:08:31 +02:00

Update Node.js packages (#1002)

This commit is contained in:
Next Turn 2023-01-29 15:55:49 +08:00 committed by GitHub
parent f8d2ae567c
commit a370d70e0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
209 changed files with 5934 additions and 113508 deletions

View File

@ -5,9 +5,13 @@
"requires": true,
"packages": {
"node_modules/@actions/core": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz",
"integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA=="
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz",
"integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==",
"dependencies": {
"@actions/http-client": "^2.0.1",
"uuid": "^8.3.2"
}
},
"node_modules/@actions/github": {
"version": "4.0.0",
@ -20,77 +24,86 @@
"@octokit/plugin-rest-endpoint-methods": "^4.0.0"
}
},
"node_modules/@actions/http-client": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.9.tgz",
"integrity": "sha512-0O4SsJ7q+MK0ycvXPl2e6bMXV7dxAXOGjrXS1eTF9s2S401Tp6c/P3c3Joz04QefC1J6Gt942Wl2jbm3f4mLcg==",
"node_modules/@actions/github/node_modules/@actions/http-client": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.11.tgz",
"integrity": "sha512-VRYHGQV1rqnROJqdMvGUbY/Kn8vriQe/F9HR2AlYHzmKuM/p3kjNuXhmdBfcVgsvRWTz5C5XW5xvndZrVBuAYg==",
"dependencies": {
"tunnel": "0.0.6"
}
},
"node_modules/@octokit/auth-token": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.4.tgz",
"integrity": "sha512-LNfGu3Ro9uFAYh10MUZVaT7X2CnNm2C8IDQmabx+3DygYIQjs9FwzFAHN/0t6mu5HEPhxcb1XOuxdpY82vCg2Q==",
"node_modules/@actions/http-client": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz",
"integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==",
"dependencies": {
"@octokit/types": "^6.0.0"
"tunnel": "^0.0.6"
}
},
"node_modules/@octokit/auth-token": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz",
"integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==",
"dependencies": {
"@octokit/types": "^6.0.3"
}
},
"node_modules/@octokit/core": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.2.4.tgz",
"integrity": "sha512-d9dTsqdePBqOn7aGkyRFe7pQpCXdibSJ5SFnrTr0axevObZrpz3qkWm7t/NjYv5a66z6vhfteriaq4FRz3e0Qg==",
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.6.0.tgz",
"integrity": "sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==",
"dependencies": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.4.12",
"@octokit/request": "^5.6.3",
"@octokit/request-error": "^2.0.5",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.1.0",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/endpoint": {
"version": "6.0.10",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.10.tgz",
"integrity": "sha512-9+Xef8nT7OKZglfkOMm7IL6VwxXUQyR7DUSU0LH/F7VNqs8vyd7es5pTfz9E7DwUIx7R3pGscxu1EBhYljyu7Q==",
"version": "6.0.12",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.12.tgz",
"integrity": "sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==",
"dependencies": {
"@octokit/types": "^6.0.0",
"@octokit/types": "^6.0.3",
"is-plain-object": "^5.0.0",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/graphql": {
"version": "4.5.8",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.8.tgz",
"integrity": "sha512-WnCtNXWOrupfPJgXe+vSmprZJUr0VIu14G58PMlkWGj3cH+KLZEfKMmbUQ6C3Wwx6fdhzVW1CD5RTnBdUHxhhA==",
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.8.0.tgz",
"integrity": "sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==",
"dependencies": {
"@octokit/request": "^5.3.0",
"@octokit/types": "^6.0.0",
"@octokit/request": "^5.6.0",
"@octokit/types": "^6.0.3",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/openapi-types": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.0.1.tgz",
"integrity": "sha512-9AuC04PUnZrjoLiw3uPtwGh9FE4Q3rTqs51oNlQ0rkwgE8ftYsOC+lsrQyvCvWm85smBbSc0FNRKKumvGyb44Q=="
"version": "12.11.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz",
"integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ=="
},
"node_modules/@octokit/plugin-paginate-rest": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.6.2.tgz",
"integrity": "sha512-3Dy7/YZAwdOaRpGQoNHPeT0VU1fYLpIUdPyvR37IyFLgd6XSij4j9V/xN/+eSjF2KKvmfIulEh9LF1tRPjIiDA==",
"version": "2.21.3",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz",
"integrity": "sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw==",
"dependencies": {
"@octokit/types": "^6.0.1"
"@octokit/types": "^6.40.0"
},
"peerDependencies": {
"@octokit/core": ">=2"
}
},
"node_modules/@octokit/plugin-rest-endpoint-methods": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.4.1.tgz",
"integrity": "sha512-+v5PcvrUcDeFXf8hv1gnNvNLdm4C0+2EiuWt9EatjjUmfriM1pTMM+r4j1lLHxeBQ9bVDmbywb11e3KjuavieA==",
"version": "4.15.1",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.15.1.tgz",
"integrity": "sha512-4gQg4ySoW7ktKB0Mf38fHzcSffVZd6mT5deJQtpqkuPuAqzlED5AJTeW8Uk7dPRn7KaOlWcXB0MedTFJU1j4qA==",
"dependencies": {
"@octokit/types": "^6.1.0",
"@octokit/types": "^6.13.0",
"deprecation": "^2.3.1"
},
"peerDependencies": {
@ -98,48 +111,40 @@
}
},
"node_modules/@octokit/request": {
"version": "5.4.12",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.12.tgz",
"integrity": "sha512-MvWYdxengUWTGFpfpefBBpVmmEYfkwMoxonIB3sUGp5rhdgwjXL1ejo6JbgzG/QD9B/NYt/9cJX1pxXeSIUCkg==",
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz",
"integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==",
"dependencies": {
"@octokit/endpoint": "^6.0.1",
"@octokit/request-error": "^2.0.0",
"@octokit/types": "^6.0.3",
"deprecation": "^2.0.0",
"@octokit/request-error": "^2.1.0",
"@octokit/types": "^6.16.1",
"is-plain-object": "^5.0.0",
"node-fetch": "^2.6.1",
"once": "^1.4.0",
"node-fetch": "^2.6.7",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/request-error": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.4.tgz",
"integrity": "sha512-LjkSiTbsxIErBiRh5wSZvpZqT4t0/c9+4dOe0PII+6jXR+oj/h66s7E4a/MghV7iT8W9ffoQ5Skoxzs96+gBPA==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz",
"integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==",
"dependencies": {
"@octokit/types": "^6.0.0",
"@octokit/types": "^6.0.3",
"deprecation": "^2.0.0",
"once": "^1.4.0"
}
},
"node_modules/@octokit/types": {
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.1.2.tgz",
"integrity": "sha512-LPCpcLbcky7fWfHCTuc7tMiSHFpFlrThJqVdaHgowBTMS0ijlZFfonQC/C1PrZOjD4xRCYgBqH9yttEATGE/nw==",
"version": "6.41.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz",
"integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==",
"dependencies": {
"@octokit/openapi-types": "^2.0.1",
"@types/node": ">= 8"
"@octokit/openapi-types": "^12.11.0"
}
},
"node_modules/@types/node": {
"version": "14.14.16",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.16.tgz",
"integrity": "sha512-naXYePhweTi+BMv11TgioE2/FXU4fSl29HAH1ffxVciNsH3rYXjNP2yM8wqmSm7jS20gM8TIklKiTen+1iVncw=="
},
"node_modules/before-after-hook": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz",
"integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A=="
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz",
"integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ=="
},
"node_modules/deprecation": {
"version": "2.3.1",
@ -155,21 +160,37 @@
}
},
"node_modules/node-fetch": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==",
"version": "2.6.8",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.8.tgz",
"integrity": "sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/tunnel": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz",
@ -183,10 +204,32 @@
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz",
"integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w=="
},
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}
}
}

View File

@ -16,11 +16,14 @@ import * as core from '@actions/core';
#### Inputs/Outputs
Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
Action inputs can be read with `getInput` which returns a `string` or `getBooleanInput` which parses a boolean based on the [yaml 1.2 specification](https://yaml.org/spec/1.2/spec.html#id2804923). If `required` set to be false, the input should have a default value in `action.yml`.
Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
```js
const myInput = core.getInput('inputName', { required: true });
const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true });
const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true });
core.setOutput('outputKey', 'outputVal');
```
@ -62,11 +65,10 @@ catch (err) {
// setFailed logs the message and sets a failing exit code
core.setFailed(`Action failed with error ${err}`);
}
```
Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned.
```
#### Logging
Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs).
@ -90,6 +92,8 @@ try {
// Do stuff
core.info('Output to the actions build log')
core.notice('This is a message that will also emit an annotation')
}
catch (err) {
core.error(`Error ${err}, action may still succeed though`);
@ -113,11 +117,123 @@ const result = await core.group('Do something async', async () => {
})
```
#### Annotations
This library has 3 methods that will produce [annotations](https://docs.github.com/en/rest/reference/checks#create-a-check-run).
```js
core.error('This is a bad error. This will also fail the build.')
core.warning('Something went wrong, but it\'s not bad enough to fail the build.')
core.notice('Something happened that you might want to know about.')
```
These will surface to the UI in the Actions page and on Pull Requests. They look something like this:
![Annotations Image](../../docs/assets/annotations.png)
These annotations can also be attached to particular lines and columns of your source files to show exactly where a problem is occuring.
These options are:
```typescript
export interface AnnotationProperties {
/**
* A title for the annotation.
*/
title?: string
/**
* The name of the file for which the annotation should be created.
*/
file?: string
/**
* The start line for the annotation.
*/
startLine?: number
/**
* The end line for the annotation. Defaults to `startLine` when `startLine` is provided.
*/
endLine?: number
/**
* The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
*/
startColumn?: number
/**
* The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
* Defaults to `startColumn` when `startColumn` is provided.
*/
endColumn?: number
}
```
#### Styling output
Colored output is supported in the Action logs via standard [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). 3/4 bit, 8 bit and 24 bit colors are all supported.
Foreground colors:
```js
// 3/4 bit
core.info('\u001b[35mThis foreground will be magenta')
// 8 bit
core.info('\u001b[38;5;6mThis foreground will be cyan')
// 24 bit
core.info('\u001b[38;2;255;0;0mThis foreground will be bright red')
```
Background colors:
```js
// 3/4 bit
core.info('\u001b[43mThis background will be yellow');
// 8 bit
core.info('\u001b[48;5;6mThis background will be cyan')
// 24 bit
core.info('\u001b[48;2;255;0;0mThis background will be bright red')
```
Special styles:
```js
core.info('\u001b[1mBold text')
core.info('\u001b[3mItalic text')
core.info('\u001b[4mUnderlined text')
```
ANSI escape codes can be combined with one another:
```js
core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end');
```
> Note: Escape codes reset at the start of each line
```js
core.info('\u001b[35mThis foreground will be magenta')
core.info('This foreground will reset to the default')
```
Manually typing escape codes can be a little difficult, but you can use third party modules such as [ansi-styles](https://github.com/chalk/ansi-styles).
```js
const style = require('ansi-styles');
core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!')
```
#### Action state
You can use this library to save state and get state for sharing information between a given wrapper action:
You can use this library to save state and get state for sharing information between a given wrapper action:
**action.yml**:
**action.yml**
```yaml
name: 'Wrapper action sample'
inputs:
@ -138,6 +254,7 @@ core.saveState("pidToKill", 12345);
```
In action's `cleanup.js`:
```js
const core = require('@actions/core');
@ -145,3 +262,74 @@ var pid = core.getState("pidToKill");
process.kill(pid);
```
#### OIDC Token
You can use these methods to interact with the GitHub OIDC provider and get a JWT ID token which would help to get access token from third party cloud providers.
**Method Name**: getIDToken()
**Inputs**
audience : optional
**Outputs**
A [JWT](https://jwt.io/) ID Token
In action's `main.ts`:
```js
const core = require('@actions/core');
async function getIDTokenAction(): Promise<void> {
const audience = core.getInput('audience', {required: false})
const id_token1 = await core.getIDToken() // ID Token with default audience
const id_token2 = await core.getIDToken(audience) // ID token with custom audience
// this id_token can be used to get access token from third party cloud providers
}
getIDTokenAction()
```
In action's `actions.yml`:
```yaml
name: 'GetIDToken'
description: 'Get ID token from Github OIDC provider'
inputs:
audience:
description: 'Audience for which the ID token is intended for'
required: false
outputs:
id_token1:
description: 'ID token obtained from OIDC provider'
id_token2:
description: 'ID token obtained from OIDC provider'
runs:
using: 'node12'
main: 'dist/index.js'
```
#### Filesystem path helpers
You can use these methods to manipulate file paths across operating systems.
The `toPosixPath` function converts input paths to Posix-style (Linux) paths.
The `toWin32Path` function converts input paths to Windows-style paths. These
functions work independently of the underlying runner operating system.
```js
toPosixPath('\\foo\\bar') // => /foo/bar
toWin32Path('/foo/bar') // => \foo\bar
```
The `toPlatformPath` function converts input paths to the expected value on the runner's operating system.
```js
// On a Windows runner.
toPlatformPath('/foo/bar') // => \foo\bar
// On a Linux runner.
toPlatformPath('\\foo\\bar') // => /foo/bar
```

View File

@ -1,4 +1,4 @@
interface CommandProperties {
export interface CommandProperties {
[key: string]: any;
}
/**
@ -13,4 +13,3 @@ interface CommandProperties {
*/
export declare function issueCommand(command: string, properties: CommandProperties, message: any): void;
export declare function issue(name: string, message?: string): void;
export {};

View File

@ -1,12 +1,25 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.issue = exports.issueCommand = void 0;
const os = __importStar(require("os"));
const utils_1 = require("./utils");
/**

View File

@ -1 +1 @@
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AACxB,mCAAsC;AAWtC;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AACxB,mCAAsC;AAWtC;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,OAAO,GAAG,EAAE;IAC9C,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}

View File

@ -4,6 +4,8 @@
export interface InputOptions {
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
required?: boolean;
/** Optional. Whether leading/trailing whitespace will be trimmed for the input. Defaults to true */
trimWhitespace?: boolean;
}
/**
* The code to exit an action
@ -18,6 +20,37 @@ export declare enum ExitCode {
*/
Failure = 1
}
/**
* Optional properties that can be sent with annotatation commands (notice, error, and warning)
* See: https://docs.github.com/en/rest/reference/checks#create-a-check-run for more information about annotations.
*/
export interface AnnotationProperties {
/**
* A title for the annotation.
*/
title?: string;
/**
* The path of the file for which the annotation should be created.
*/
file?: string;
/**
* The start line for the annotation.
*/
startLine?: number;
/**
* The end line for the annotation. Defaults to `startLine` when `startLine` is provided.
*/
endLine?: number;
/**
* The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
*/
startColumn?: number;
/**
* The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
* Defaults to `startColumn` when `startColumn` is provided.
*/
endColumn?: number;
}
/**
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
@ -35,13 +68,35 @@ export declare function setSecret(secret: string): void;
*/
export declare function addPath(inputPath: string): void;
/**
* Gets the value of an input. The value is also trimmed.
* Gets the value of an input.
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
* Returns an empty string if the value is not defined.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
export declare function getInput(name: string, options?: InputOptions): string;
/**
* Gets the values of an multiline input. Each value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string[]
*
*/
export declare function getMultilineInput(name: string, options?: InputOptions): string[];
/**
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
* The return value is also in boolean type.
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns boolean
*/
export declare function getBooleanInput(name: string, options?: InputOptions): boolean;
/**
* Sets the value of an output.
*
@ -73,13 +128,21 @@ export declare function debug(message: string): void;
/**
* Adds an error issue
* @param message error issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
export declare function error(message: string | Error): void;
export declare function error(message: string | Error, properties?: AnnotationProperties): void;
/**
* Adds an warning issue
* Adds a warning issue
* @param message warning issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
export declare function warning(message: string | Error): void;
export declare function warning(message: string | Error, properties?: AnnotationProperties): void;
/**
* Adds a notice issue
* @param message notice issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
export declare function notice(message: string | Error, properties?: AnnotationProperties): void;
/**
* Writes info to log with console.log.
* @param message info message
@ -120,3 +183,16 @@ export declare function saveState(name: string, value: any): void;
* @returns string
*/
export declare function getState(name: string): string;
export declare function getIDToken(aud?: string): Promise<string>;
/**
* Summary exports
*/
export { summary } from './summary';
/**
* @deprecated use core.summary
*/
export { markdownSummary } from './summary';
/**
* Path exports
*/
export { toPosixPath, toWin32Path, toPlatformPath } from './path-utils';

View File

@ -1,4 +1,23 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@ -8,19 +27,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
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 });
exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
const command_1 = require("./command");
const file_command_1 = require("./file-command");
const utils_1 = require("./utils");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const oidc_utils_1 = require("./oidc-utils");
/**
* The code to exit an action
*/
@ -49,13 +63,9 @@ function exportVariable(name, val) {
process.env[name] = convertedVal;
const filePath = process.env['GITHUB_ENV'] || '';
if (filePath) {
const delimiter = '_GitHubActionsFileCommandDelimeter_';
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;
file_command_1.issueCommand('ENV', commandValue);
}
else {
command_1.issueCommand('set-env', { name }, convertedVal);
return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));
}
command_1.issueCommand('set-env', { name }, convertedVal);
}
exports.exportVariable = exportVariable;
/**
@ -73,7 +83,7 @@ exports.setSecret = setSecret;
function addPath(inputPath) {
const filePath = process.env['GITHUB_PATH'] || '';
if (filePath) {
file_command_1.issueCommand('PATH', inputPath);
file_command_1.issueFileCommand('PATH', inputPath);
}
else {
command_1.issueCommand('add-path', {}, inputPath);
@ -82,7 +92,9 @@ function addPath(inputPath) {
}
exports.addPath = addPath;
/**
* Gets the value of an input. The value is also trimmed.
* Gets the value of an input.
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
* Returns an empty string if the value is not defined.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
@ -93,9 +105,52 @@ function getInput(name, options) {
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
if (options && options.trimWhitespace === false) {
return val;
}
return val.trim();
}
exports.getInput = getInput;
/**
* Gets the values of an multiline input. Each value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string[]
*
*/
function getMultilineInput(name, options) {
const inputs = getInput(name, options)
.split('\n')
.filter(x => x !== '');
if (options && options.trimWhitespace === false) {
return inputs;
}
return inputs.map(input => input.trim());
}
exports.getMultilineInput = getMultilineInput;
/**
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
* The return value is also in boolean type.
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns boolean
*/
function getBooleanInput(name, options) {
const trueValue = ['true', 'True', 'TRUE'];
const falseValue = ['false', 'False', 'FALSE'];
const val = getInput(name, options);
if (trueValue.includes(val))
return true;
if (falseValue.includes(val))
return false;
throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
}
exports.getBooleanInput = getBooleanInput;
/**
* Sets the value of an output.
*
@ -104,7 +159,12 @@ exports.getInput = getInput;
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
const filePath = process.env['GITHUB_OUTPUT'] || '';
if (filePath) {
return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));
}
process.stdout.write(os.EOL);
command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));
}
exports.setOutput = setOutput;
/**
@ -150,19 +210,30 @@ exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
function error(message) {
command_1.issue('error', message instanceof Error ? message.toString() : message);
function error(message, properties = {}) {
command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.error = error;
/**
* Adds an warning issue
* Adds a warning issue
* @param message warning issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
function warning(message) {
command_1.issue('warning', message instanceof Error ? message.toString() : message);
function warning(message, properties = {}) {
command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.warning = warning;
/**
* Adds a notice issue
* @param message notice issue message. Errors will be converted to string via toString()
* @param properties optional properties to add to the annotation.
*/
function notice(message, properties = {}) {
command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.notice = notice;
/**
* Writes info to log with console.log.
* @param message info message
@ -222,7 +293,11 @@ exports.group = group;
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function saveState(name, value) {
command_1.issueCommand('save-state', { name }, value);
const filePath = process.env['GITHUB_STATE'] || '';
if (filePath) {
return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));
}
command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));
}
exports.saveState = saveState;
/**
@ -235,4 +310,27 @@ function getState(name) {
return process.env[`STATE_${name}`] || '';
}
exports.getState = getState;
function getIDToken(aud) {
return __awaiter(this, void 0, void 0, function* () {
return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
}
exports.getIDToken = getIDToken;
/**
* Summary exports
*/
var summary_1 = require("./summary");
Object.defineProperty(exports, "summary", { enumerable: true, get: function () { return summary_1.summary; } });
/**
* @deprecated use core.summary
*/
var summary_2 = require("./summary");
Object.defineProperty(exports, "markdownSummary", { enumerable: true, get: function () { return summary_2.markdownSummary; } });
/**
* Path exports
*/
var path_utils_1 = require("./path-utils");
Object.defineProperty(exports, "toPosixPath", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });
Object.defineProperty(exports, "toWin32Path", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });
Object.defineProperty(exports, "toPlatformPath", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });
//# sourceMappingURL=core.js.map

File diff suppressed because one or more lines are too long

View File

@ -1 +1,2 @@
export declare function issueCommand(command: string, message: any): void;
export declare function issueFileCommand(command: string, message: any): void;
export declare function prepareKeyValueMessage(key: string, value: any): string;

View File

@ -1,19 +1,33 @@
"use strict";
// For internal use, subject to change.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const uuid_1 = require("uuid");
const utils_1 = require("./utils");
function issueCommand(command, message) {
function issueFileCommand(command, message) {
const filePath = process.env[`GITHUB_${command}`];
if (!filePath) {
throw new Error(`Unable to find environment variable for file command ${command}`);
@ -25,5 +39,20 @@ function issueCommand(command, message) {
encoding: 'utf8'
});
}
exports.issueCommand = issueCommand;
exports.issueFileCommand = issueFileCommand;
function prepareKeyValueMessage(key, value) {
const delimiter = `ghadelimiter_${uuid_1.v4()}`;
const convertedValue = utils_1.toCommandValue(value);
// These should realistically never happen, but just in case someone finds a
// way to exploit uuid generation let's not allow keys or values that contain
// the delimiter.
if (key.includes(delimiter)) {
throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
}
if (convertedValue.includes(delimiter)) {
throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
}
return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
}
exports.prepareKeyValueMessage = prepareKeyValueMessage;
//# sourceMappingURL=file-command.js.map

View File

@ -1 +1 @@
{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,mCAAsC;AAEtC,SAAgB,YAAY,CAAC,OAAe,EAAE,OAAY;IACxD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,oCAcC"}
{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;;;;;;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,+BAAiC;AACjC,mCAAsC;AAEtC,SAAgB,gBAAgB,CAAC,OAAe,EAAE,OAAY;IAC5D,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,4CAcC;AAED,SAAgB,sBAAsB,CAAC,GAAW,EAAE,KAAU;IAC5D,MAAM,SAAS,GAAG,gBAAgB,SAAM,EAAE,EAAE,CAAA;IAC5C,MAAM,cAAc,GAAG,sBAAc,CAAC,KAAK,CAAC,CAAA;IAE5C,4EAA4E;IAC5E,6EAA6E;IAC7E,iBAAiB;IACjB,IAAI,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAC3B,MAAM,IAAI,KAAK,CACb,4DAA4D,SAAS,GAAG,CACzE,CAAA;KACF;IAED,IAAI,cAAc,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QACtC,MAAM,IAAI,KAAK,CACb,6DAA6D,SAAS,GAAG,CAC1E,CAAA;KACF;IAED,OAAO,GAAG,GAAG,KAAK,SAAS,GAAG,EAAE,CAAC,GAAG,GAAG,cAAc,GAAG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;AAC9E,CAAC;AApBD,wDAoBC"}

View File

@ -1,5 +1,14 @@
import { AnnotationProperties } from './core';
import { CommandProperties } from './command';
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
export declare function toCommandValue(input: any): string;
/**
*
* @param annotationProperties
* @returns The command properties to send with the actual annotation command
* See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
*/
export declare function toCommandProperties(annotationProperties: AnnotationProperties): CommandProperties;

View File

@ -2,6 +2,7 @@
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", { value: true });
exports.toCommandProperties = exports.toCommandValue = void 0;
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
@ -16,4 +17,24 @@ function toCommandValue(input) {
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
/**
*
* @param annotationProperties
* @returns The command properties to send with the actual annotation command
* See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
*/
function toCommandProperties(annotationProperties) {
if (!Object.keys(annotationProperties).length) {
return {};
}
return {
title: annotationProperties.title,
file: annotationProperties.file,
line: annotationProperties.startLine,
endLine: annotationProperties.endLine,
col: annotationProperties.startColumn,
endColumn: annotationProperties.endColumn
};
}
exports.toCommandProperties = toCommandProperties;
//# sourceMappingURL=utils.js.map

View File

@ -1 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA,mCAAmC;AACnC,uDAAuD;;AAEvD;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC"}
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA,mCAAmC;AACnC,uDAAuD;;;AAKvD;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,oBAA0C;IAE1C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,MAAM,EAAE;QAC7C,OAAO,EAAE,CAAA;KACV;IAED,OAAO;QACL,KAAK,EAAE,oBAAoB,CAAC,KAAK;QACjC,IAAI,EAAE,oBAAoB,CAAC,IAAI;QAC/B,IAAI,EAAE,oBAAoB,CAAC,SAAS;QACpC,OAAO,EAAE,oBAAoB,CAAC,OAAO;QACrC,GAAG,EAAE,oBAAoB,CAAC,WAAW;QACrC,SAAS,EAAE,oBAAoB,CAAC,SAAS;KAC1C,CAAA;AACH,CAAC;AAfD,kDAeC"}

View File

@ -1,6 +1,6 @@
{
"name": "@actions/core",
"version": "1.2.6",
"version": "1.10.0",
"description": "Actions core lib",
"keywords": [
"github",
@ -35,7 +35,12 @@
"bugs": {
"url": "https://github.com/actions/toolkit/issues"
},
"dependencies": {
"@actions/http-client": "^2.0.1",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/node": "^12.0.2"
"@types/node": "^12.0.2",
"@types/uuid": "^8.3.4"
}
}

View File

@ -1,18 +1,11 @@
# `@actions/http-client`
<p align="center">
<img src="actions.png">
</p>
# Actions Http-Client
[![Http Status](https://github.com/actions/http-client/workflows/http-tests/badge.svg)](https://github.com/actions/http-client/actions)
A lightweight HTTP client optimized for use with actions, TypeScript with generics and async await.
A lightweight HTTP client optimized for building actions.
## 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)
- Typings included!
- [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.
@ -28,7 +21,7 @@ npm install @actions/http-client --save
## Samples
See the [HTTP](./__tests__) tests for detailed examples.
See the [tests](./__tests__) for detailed examples.
## Errors
@ -39,13 +32,13 @@ 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.
See the [tests](./__tests__) for detailed examples.
## Debugging
To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible:
```
```shell
export NODE_DEBUG=http
```
@ -63,17 +56,18 @@ We welcome PRs. Please create an issue and if applicable, a design before proce
once:
```bash
$ npm install
```
npm install
```
To build:
```bash
$ npm run build
```
npm run build
```
To run all tests:
```bash
$ npm test
```
npm test
```

View File

@ -1,22 +0,0 @@
## Releases
## 1.0.9
Throw HttpClientError instead of a generic Error from the \<verb>Json() helper methods when the server responds with a non-successful status code.
## 1.0.8
Fixed security issue where a redirect (e.g. 302) to another domain would pass headers. The fix was to strip the authorization header if the hostname was different. More [details in PR #27](https://github.com/actions/http-client/pull/27)
## 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.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

View File

@ -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>;
}

View File

@ -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;

View File

@ -1,124 +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 HttpClientError extends Error {
constructor(message: string, statusCode: number);
statusCode: number;
result?: any;
}
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;
}

View File

@ -1,535 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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(new URL(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 HttpClientError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'HttpClientError';
this.statusCode = statusCode;
Object.setPrototypeOf(this, HttpClientError.prototype);
}
}
exports.HttpClientError = HttpClientError;
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 = new URL(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, requestOptions) {
this._ignoreSslError = false;
this._allowRedirects = true;
this._allowRedirectDowngrade = false;
this._maxRedirects = 50;
this._allowRetries = false;
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
if (requestOptions.ignoreSslError != null) {
this._ignoreSslError = requestOptions.ignoreSslError;
}
this._socketTimeout = requestOptions.socketTimeout;
if (requestOptions.allowRedirects != null) {
this._allowRedirects = requestOptions.allowRedirects;
}
if (requestOptions.allowRedirectDowngrade != null) {
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
}
if (requestOptions.maxRedirects != null) {
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
}
if (requestOptions.keepAlive != null) {
this._keepAlive = requestOptions.keepAlive;
}
if (requestOptions.allowRetries != null) {
this._allowRetries = requestOptions.allowRetries;
}
if (requestOptions.maxRetries != null) {
this._maxRetries = requestOptions.maxRetries;
}
}
}
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 = new URL(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
? this._maxRetries + 1
: 1;
let numTries = 0;
let response;
while (numTries < maxTries) {
response = await this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) {
authenticationHandler = this.handlers[i];
break;
}
}
if (authenticationHandler) {
return authenticationHandler.handleAuthentication(this, info, data);
}
else {
// We have received an unauthorized response but have no handlers to handle it.
// Let the response return to the caller.
return response;
}
}
let redirectsRemaining = this._maxRedirects;
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
this._allowRedirects &&
redirectsRemaining > 0) {
const redirectUrl = response.message.headers['location'];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
let parsedRedirectUrl = new URL(redirectUrl);
if (parsedUrl.protocol == 'https:' &&
parsedUrl.protocol != parsedRedirectUrl.protocol &&
!this._allowRedirectDowngrade) {
throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
}
// we need to finish reading the response before reassigning response
// which will leak the open socket.
await response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (let header in headers) {
// header names are case insensitive
if (header.toLowerCase() === 'authorization') {
delete headers[header];
}
}
}
// let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = await this.requestRaw(info, data);
redirectsRemaining--;
}
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
await response.readBody();
await this._performExponentialBackoff(numTries);
}
}
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 = new URL(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.username}:${proxyUrl.password}`,
host: proxyUrl.hostname,
port: proxyUrl.port
}
};
let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
agent = tunnelAgent(agentOptions);
this._proxyAgent = agent;
}
// if reusing agent across request and tunneling agent isn't assigned create a new agent
if (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
// if not using private agent and tunnel agent isn't setup then use global agent
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
}
return agent;
}
_performExponentialBackoff(retryNumber) {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
}
static dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
async _processResponse(res, options) {
return new Promise(async (resolve, reject) => {
const statusCode = res.message.statusCode;
const response = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == HttpCodes.NotFound) {
resolve(response);
}
let obj;
let contents;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);
}
else {
obj = JSON.parse(contents);
}
response.result = obj;
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
}
else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
}
else {
msg = 'Failed request: (' + statusCode + ')';
}
let err = new HttpClientError(msg, statusCode);
err.result = response.result;
reject(err);
}
else {
resolve(response);
}
});
}
}
exports.HttpClient = HttpClient;

View File

@ -1,49 +0,0 @@
/// <reference types="node" />
import http = require('http');
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;
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;
}

View File

@ -1,2 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@ -1,39 +1,48 @@
{
"name": "@actions/http-client",
"version": "1.0.9",
"version": "2.0.1",
"description": "Actions Http Client",
"main": "index.js",
"scripts": {
"build": "rm -Rf ./_out && tsc && cp package*.json ./_out && cp *.md ./_out && cp LICENSE ./_out && cp actions.png ./_out",
"test": "jest",
"format": "prettier --write *.ts && prettier --write **/*.ts",
"format-check": "prettier --check *.ts && prettier --check **/*.ts",
"audit-check": "npm audit --audit-level=moderate"
"keywords": [
"github",
"actions",
"http"
],
"homepage": "https://github.com/actions/toolkit/tree/main/packages/http-client",
"license": "MIT",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib",
"!.DS_Store"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/http-client.git"
"url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/http-client"
},
"scripts": {
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
"test": "echo \"Error: run tests from root\" && exit 1",
"build": "tsc",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"tsc": "tsc"
},
"keywords": [
"Actions",
"Http"
],
"author": "GitHub, Inc.",
"license": "MIT",
"bugs": {
"url": "https://github.com/actions/http-client/issues"
"url": "https://github.com/actions/toolkit/issues"
},
"homepage": "https://github.com/actions/http-client#readme",
"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"
"@types/tunnel": "0.0.3",
"proxy": "^1.0.1"
},
"dependencies": {
"tunnel": "0.0.6"
"tunnel": "^0.0.6"
}
}

View File

@ -1,2 +0,0 @@
export declare function getProxyUrl(reqUrl: URL): URL | undefined;
export declare function checkBypass(reqUrl: URL): boolean;

View File

@ -1,57 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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 = new URL(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;

View File

@ -58,11 +58,11 @@ const { createTokenAuth } = require("@octokit/auth-token");
</table>
```js
const auth = createTokenAuth("1234567890abcdef1234567890abcdef12345678");
const auth = createTokenAuth("ghp_PersonalAccessToken01245678900000000");
const authentication = await auth();
// {
// type: 'token',
// token: '1234567890abcdef1234567890abcdef12345678',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
```
@ -73,17 +73,36 @@ The `createTokenAuth` method accepts a single argument of type string, which is
- [Personal access token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line)
- [OAuth access token](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)
- Installation access token ([GitHub App Installation](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation))
- [GITHUB_TOKEN provided to GitHub Actions](https://developer.github.com/actions/creating-github-actions/accessing-the-runtime-environment/#environment-variables)
- Installation access token ([server-to-server](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation))
- User authentication for installation ([user-to-server](https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps))
Examples
```js
// Personal access token or OAuth access token
createTokenAuth("1234567890abcdef1234567890abcdef12345678");
createTokenAuth("ghp_PersonalAccessToken01245678900000000");
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
// Installation access token or GitHub Action token
createTokenAuth("v1.d3d433526f780fbcc3129004e2731b3904ad0b86");
createTokenAuth("ghs_InstallallationOrActionToken00000000");
// {
// type: 'token',
// token: 'ghs_InstallallationOrActionToken00000000',
// tokenType: 'installation'
// }
// Installation access token or GitHub Action token
createTokenAuth("ghu_InstallationUserToServer000000000000");
// {
// type: 'token',
// token: 'ghu_InstallationUserToServer000000000000',
// tokenType: 'user-to-server'
// }
```
## `auth()`
@ -137,7 +156,7 @@ The `auth()` method has no options. It returns a promise which resolves with the
<code>string</code>
</th>
<td>
Can be either <code>"oauth"</code> for personal access tokens and OAuth tokens, or <code>"installation"</code> for installation access tokens (includes <code>GITHUB_TOKEN</code> provided to GitHub Actions)
Can be either <code>"oauth"</code> for personal access tokens and OAuth tokens, <code>"installation"</code> for installation access tokens (includes <code>GITHUB_TOKEN</code> provided to GitHub Actions), <code>"app"</code> for a GitHub App JSON Web Token, or <code>"user-to-server"</code> for a user authentication token through an app installation.
</td>
</tr>
</tbody>
@ -181,7 +200,7 @@ Here is a list of things you can do to retrieve further information
Note that this does not work for installations. There is no way to retrieve permissions based on an installation access tokens.
```js
const TOKEN = "1234567890abcdef1234567890abcdef12345678";
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
@ -203,7 +222,7 @@ if (scopes.length) {
### Find out if token is a personal access token or if it belongs to an OAuth app
```js
const TOKEN = "1234567890abcdef1234567890abcdef12345678";
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
@ -227,12 +246,12 @@ if (clientId) {
Note that the `permissions` key is not set when authenticated using an installation access token.
```js
const TOKEN = "1234567890abcdef1234567890abcdef12345678";
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("GET /repos/:owner/:repo", {
const response = await request("GET /repos/{owner}/{repo}", {
owner: 'octocat',
repo: 'hello-world'
headers: authentication.headers
@ -253,7 +272,7 @@ Both OAuth and installation access tokens can be used for git operations. Howeve
This example is using the [`execa`](https://github.com/sindresorhus/execa) package to run a `git push` command.
```js
const TOKEN = "1234567890abcdef1234567890abcdef12345678";
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();

View File

@ -2,8 +2,14 @@
Object.defineProperty(exports, '__esModule', { value: true });
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth";
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
return {
type: "token",
token: token,

View File

@ -1 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["export async function auth(token) {\n const tokenType = token.split(/\\./).length === 3\n ? \"app\"\n : /^v\\d+\\./.test(token)\n ? \"installation\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n"],"names":["auth","token","tokenType","split","length","test","type","withAuthorizationPrefix","hook","request","route","parameters","endpoint","merge","headers","authorization","createTokenAuth","Error","replace","Object","assign","bind"],"mappings":";;;;AAAO,eAAeA,IAAf,CAAoBC,KAApB,EAA2B;AAC9B,QAAMC,SAAS,GAAGD,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAA7B,GACZ,KADY,GAEZ,UAAUC,IAAV,CAAeJ,KAAf,IACI,cADJ,GAEI,OAJV;AAKA,SAAO;AACHK,IAAAA,IAAI,EAAE,OADH;AAEHL,IAAAA,KAAK,EAAEA,KAFJ;AAGHC,IAAAA;AAHG,GAAP;AAKH;;ACXD;;;;;AAKA,AAAO,SAASK,uBAAT,CAAiCN,KAAjC,EAAwC;AAC3C,MAAIA,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAAjC,EAAoC;AAChC,WAAQ,UAASH,KAAM,EAAvB;AACH;;AACD,SAAQ,SAAQA,KAAM,EAAtB;AACH;;ACTM,eAAeO,IAAf,CAAoBP,KAApB,EAA2BQ,OAA3B,EAAoCC,KAApC,EAA2CC,UAA3C,EAAuD;AAC1D,QAAMC,QAAQ,GAAGH,OAAO,CAACG,QAAR,CAAiBC,KAAjB,CAAuBH,KAAvB,EAA8BC,UAA9B,CAAjB;AACAC,EAAAA,QAAQ,CAACE,OAAT,CAAiBC,aAAjB,GAAiCR,uBAAuB,CAACN,KAAD,CAAxD;AACA,SAAOQ,OAAO,CAACG,QAAD,CAAd;AACH;;MCHYI,eAAe,GAAG,SAASA,eAAT,CAAyBf,KAAzB,EAAgC;AAC3D,MAAI,CAACA,KAAL,EAAY;AACR,UAAM,IAAIgB,KAAJ,CAAU,0DAAV,CAAN;AACH;;AACD,MAAI,OAAOhB,KAAP,KAAiB,QAArB,EAA+B;AAC3B,UAAM,IAAIgB,KAAJ,CAAU,uEAAV,CAAN;AACH;;AACDhB,EAAAA,KAAK,GAAGA,KAAK,CAACiB,OAAN,CAAc,oBAAd,EAAoC,EAApC,CAAR;AACA,SAAOC,MAAM,CAACC,MAAP,CAAcpB,IAAI,CAACqB,IAAL,CAAU,IAAV,EAAgBpB,KAAhB,CAAd,EAAsC;AACzCO,IAAAA,IAAI,EAAEA,IAAI,CAACa,IAAL,CAAU,IAAV,EAAgBpB,KAAhB;AADmC,GAAtC,CAAP;AAGH,CAXM;;;;"}
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["const REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nconst REGEX_IS_INSTALLATION = /^ghs_/;\nconst REGEX_IS_USER_TO_SERVER = /^ghu_/;\nexport async function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||\n REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp\n ? \"app\"\n : isInstallation\n ? \"installation\"\n : isUserToServer\n ? \"user-to-server\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType,\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token),\n });\n};\n"],"names":["REGEX_IS_INSTALLATION_LEGACY","REGEX_IS_INSTALLATION","REGEX_IS_USER_TO_SERVER","auth","token","isApp","split","length","isInstallation","test","isUserToServer","tokenType","type","withAuthorizationPrefix","hook","request","route","parameters","endpoint","merge","headers","authorization","createTokenAuth","Error","replace","Object","assign","bind"],"mappings":";;;;AAAA,MAAMA,4BAA4B,GAAG,OAArC;AACA,MAAMC,qBAAqB,GAAG,OAA9B;AACA,MAAMC,uBAAuB,GAAG,OAAhC;AACO,eAAeC,IAAf,CAAoBC,KAApB,EAA2B;AAC9B,QAAMC,KAAK,GAAGD,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAA3C;AACA,QAAMC,cAAc,GAAGR,4BAA4B,CAACS,IAA7B,CAAkCL,KAAlC,KACnBH,qBAAqB,CAACQ,IAAtB,CAA2BL,KAA3B,CADJ;AAEA,QAAMM,cAAc,GAAGR,uBAAuB,CAACO,IAAxB,CAA6BL,KAA7B,CAAvB;AACA,QAAMO,SAAS,GAAGN,KAAK,GACjB,KADiB,GAEjBG,cAAc,GACV,cADU,GAEVE,cAAc,GACV,gBADU,GAEV,OANd;AAOA,SAAO;AACHE,IAAAA,IAAI,EAAE,OADH;AAEHR,IAAAA,KAAK,EAAEA,KAFJ;AAGHO,IAAAA;AAHG,GAAP;AAKH;;ACpBD;AACA;AACA;AACA;AACA;AACA,AAAO,SAASE,uBAAT,CAAiCT,KAAjC,EAAwC;AAC3C,MAAIA,KAAK,CAACE,KAAN,CAAY,IAAZ,EAAkBC,MAAlB,KAA6B,CAAjC,EAAoC;AAChC,WAAQ,UAASH,KAAM,EAAvB;AACH;;AACD,SAAQ,SAAQA,KAAM,EAAtB;AACH;;ACTM,eAAeU,IAAf,CAAoBV,KAApB,EAA2BW,OAA3B,EAAoCC,KAApC,EAA2CC,UAA3C,EAAuD;AAC1D,QAAMC,QAAQ,GAAGH,OAAO,CAACG,QAAR,CAAiBC,KAAjB,CAAuBH,KAAvB,EAA8BC,UAA9B,CAAjB;AACAC,EAAAA,QAAQ,CAACE,OAAT,CAAiBC,aAAjB,GAAiCR,uBAAuB,CAACT,KAAD,CAAxD;AACA,SAAOW,OAAO,CAACG,QAAD,CAAd;AACH;;MCHYI,eAAe,GAAG,SAASA,eAAT,CAAyBlB,KAAzB,EAAgC;AAC3D,MAAI,CAACA,KAAL,EAAY;AACR,UAAM,IAAImB,KAAJ,CAAU,0DAAV,CAAN;AACH;;AACD,MAAI,OAAOnB,KAAP,KAAiB,QAArB,EAA+B;AAC3B,UAAM,IAAImB,KAAJ,CAAU,uEAAV,CAAN;AACH;;AACDnB,EAAAA,KAAK,GAAGA,KAAK,CAACoB,OAAN,CAAc,oBAAd,EAAoC,EAApC,CAAR;AACA,SAAOC,MAAM,CAACC,MAAP,CAAcvB,IAAI,CAACwB,IAAL,CAAU,IAAV,EAAgBvB,KAAhB,CAAd,EAAsC;AACzCU,IAAAA,IAAI,EAAEA,IAAI,CAACa,IAAL,CAAU,IAAV,EAAgBvB,KAAhB;AADmC,GAAtC,CAAP;AAGH,CAXM;;;;"}

View File

@ -1,12 +1,21 @@
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
export async function auth(token) {
const tokenType = token.split(/\./).length === 3
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||
REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp
? "app"
: /^v\d+\./.test(token)
: isInstallation
? "installation"
: "oauth";
: isUserToServer
? "user-to-server"
: "oauth";
return {
type: "token",
token: token,
tokenType
tokenType,
};
}

View File

@ -9,6 +9,6 @@ export const createTokenAuth = function createTokenAuth(token) {
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
hook: hook.bind(null, token),
});
};

View File

@ -0,0 +1 @@
export {};

View File

@ -1,6 +1,9 @@
import * as OctokitTypes from "@octokit/types";
export declare type AnyResponse = OctokitTypes.OctokitResponse<any>;
export declare type StrategyInterface = OctokitTypes.StrategyInterface<[Token], [], Authentication>;
export declare type StrategyInterface = OctokitTypes.StrategyInterface<[
Token
], [
], Authentication>;
export declare type EndpointDefaults = OctokitTypes.EndpointDefaults;
export declare type EndpointOptions = OctokitTypes.EndpointOptions;
export declare type RequestParameters = OctokitTypes.RequestParameters;
@ -22,4 +25,9 @@ export declare type AppAuthentication = {
tokenType: "app";
token: Token;
};
export declare type Authentication = OAuthTokenAuthentication | InstallationTokenAuthentication | AppAuthentication;
export declare type UserToServerAuthentication = {
type: "token";
tokenType: "user-to-server";
token: Token;
};
export declare type Authentication = OAuthTokenAuthentication | InstallationTokenAuthentication | AppAuthentication | UserToServerAuthentication;

View File

@ -1,13 +1,22 @@
const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
const REGEX_IS_INSTALLATION = /^ghs_/;
const REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
const tokenType = token.split(/\./).length === 3
const isApp = token.split(/\./).length === 3;
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||
REGEX_IS_INSTALLATION.test(token);
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
const tokenType = isApp
? "app"
: /^v\d+\./.test(token)
: isInstallation
? "installation"
: "oauth";
: isUserToServer
? "user-to-server"
: "oauth";
return {
type: "token",
token: token,
tokenType
tokenType,
};
}
@ -38,7 +47,7 @@ const createTokenAuth = function createTokenAuth(token) {
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
hook: hook.bind(null, token),
});
};

View File

@ -1 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["export async function auth(token) {\n const tokenType = token.split(/\\./).length === 3\n ? \"app\"\n : /^v\\d+\\./.test(token)\n ? \"installation\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n"],"names":[],"mappings":"AAAO,eAAe,IAAI,CAAC,KAAK,EAAE;AAClC,IAAI,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC;AACpD,UAAU,KAAK;AACf,UAAU,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;AAC/B,cAAc,cAAc;AAC5B,cAAc,OAAO,CAAC;AACtB,IAAI,OAAO;AACX,QAAQ,IAAI,EAAE,OAAO;AACrB,QAAQ,KAAK,EAAE,KAAK;AACpB,QAAQ,SAAS;AACjB,KAAK,CAAC;AACN;;ACXA;AACA;AACA;AACA;AACA;AACA,AAAO,SAAS,uBAAuB,CAAC,KAAK,EAAE;AAC/C,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;AACxC,QAAQ,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACjC,KAAK;AACL,IAAI,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;AAC5B,CAAC;;ACTM,eAAe,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE;AAC9D,IAAI,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AAC/D,IAAI,QAAQ,CAAC,OAAO,CAAC,aAAa,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;AACpE,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC7B,CAAC;;ACHW,MAAC,eAAe,GAAG,SAAS,eAAe,CAAC,KAAK,EAAE;AAC/D,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;AACpF,KAAK;AACL,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACnC,QAAQ,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;AACjG,KAAK;AACL,IAAI,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;AACpD,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;AACjD,QAAQ,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC;AACpC,KAAK,CAAC,CAAC;AACP,CAAC;;;;"}
{"version":3,"file":"index.js","sources":["../dist-src/auth.js","../dist-src/with-authorization-prefix.js","../dist-src/hook.js","../dist-src/index.js"],"sourcesContent":["const REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nconst REGEX_IS_INSTALLATION = /^ghs_/;\nconst REGEX_IS_USER_TO_SERVER = /^ghu_/;\nexport async function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||\n REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp\n ? \"app\"\n : isInstallation\n ? \"installation\"\n : isUserToServer\n ? \"user-to-server\"\n : \"oauth\";\n return {\n type: \"token\",\n token: token,\n tokenType,\n };\n}\n","/**\n * Prefix token for usage in the Authorization header\n *\n * @param token OAuth token or JSON Web Token\n */\nexport function withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n","import { withAuthorizationPrefix } from \"./with-authorization-prefix\";\nexport async function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(route, parameters);\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n","import { auth } from \"./auth\";\nimport { hook } from \"./hook\";\nexport const createTokenAuth = function createTokenAuth(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\"[@octokit/auth-token] Token passed to createTokenAuth is not a string\");\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token),\n });\n};\n"],"names":[],"mappings":"AAAA,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAC7C,MAAM,qBAAqB,GAAG,OAAO,CAAC;AACtC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AACjC,eAAe,IAAI,CAAC,KAAK,EAAE;AAClC,IAAI,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AACjD,IAAI,MAAM,cAAc,GAAG,4BAA4B,CAAC,IAAI,CAAC,KAAK,CAAC;AACnE,QAAQ,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC1C,IAAI,MAAM,cAAc,GAAG,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC/D,IAAI,MAAM,SAAS,GAAG,KAAK;AAC3B,UAAU,KAAK;AACf,UAAU,cAAc;AACxB,cAAc,cAAc;AAC5B,cAAc,cAAc;AAC5B,kBAAkB,gBAAgB;AAClC,kBAAkB,OAAO,CAAC;AAC1B,IAAI,OAAO;AACX,QAAQ,IAAI,EAAE,OAAO;AACrB,QAAQ,KAAK,EAAE,KAAK;AACpB,QAAQ,SAAS;AACjB,KAAK,CAAC;AACN;;ACpBA;AACA;AACA;AACA;AACA;AACA,AAAO,SAAS,uBAAuB,CAAC,KAAK,EAAE;AAC/C,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;AACxC,QAAQ,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACjC,KAAK;AACL,IAAI,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;AAC5B,CAAC;;ACTM,eAAe,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE;AAC9D,IAAI,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AAC/D,IAAI,QAAQ,CAAC,OAAO,CAAC,aAAa,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;AACpE,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC7B,CAAC;;ACHW,MAAC,eAAe,GAAG,SAAS,eAAe,CAAC,KAAK,EAAE;AAC/D,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;AACpF,KAAK;AACL,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACnC,QAAQ,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;AACjG,KAAK;AACL,IAAI,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;AACpD,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;AACjD,QAAQ,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC;AACpC,KAAK,CAAC,CAAC;AACP,CAAC;;;;"}

View File

@ -1,7 +1,7 @@
{
"name": "@octokit/auth-token",
"description": "GitHub API token authentication for browsers and Node.js",
"version": "2.4.4",
"version": "2.5.0",
"license": "MIT",
"files": [
"dist-*/",
@ -15,13 +15,9 @@
"authentication",
"api"
],
"homepage": "https://github.com/octokit/auth-token.js#readme",
"bugs": {
"url": "https://github.com/octokit/auth-token.js/issues"
},
"repository": "https://github.com/octokit/auth-token.js",
"repository": "github:octokit/auth-token.js",
"dependencies": {
"@octokit/types": "^6.0.0"
"@octokit/types": "^6.0.3"
},
"devDependencies": {
"@octokit/core": "^3.0.0",
@ -31,12 +27,13 @@
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^26.0.0",
"@types/jest": "^27.0.0",
"fetch-mock": "^9.0.0",
"jest": "^25.1.0",
"jest": "^27.0.0",
"prettier": "2.4.1",
"semantic-release": "^17.0.0",
"ts-jest": "^25.1.0",
"typescript": "^3.7.2"
"ts-jest": "^27.0.0-next.12",
"typescript": "^4.0.0"
},
"publishConfig": {
"access": "public"

View File

@ -298,7 +298,9 @@ const octokit = new Octokit({
const { data } = await octokit.request("/user");
```
To use a different authentication strategy, set `options.authStrategy`. A set of officially supported authentication strategies can be retrieved from [`@octokit/auth`](https://github.com/octokit/auth-app.js#readme). Example
To use a different authentication strategy, set `options.authStrategy`. A list of authentication strategies is available at [octokit/authentication-strategies.js](https://github.com/octokit/authentication-strategies.js/#readme).
Example
```js
import { Octokit } from "@octokit/core";
@ -358,7 +360,7 @@ octokit.hook.after("request", async (response, options) => {
});
octokit.hook.error("request", async (error, options) => {
if (error.status === 304) {
return findInCache(error.headers.etag);
return findInCache(error.response.headers.etag);
}
throw error;
@ -421,11 +423,19 @@ You can build your own Octokit class with preset default options and plugins. In
```js
const { Octokit } = require("@octokit/core");
const MyActionOctokit = Octokit.plugin(
require("@octokit/plugin-paginate-rest"),
require("@octokit/plugin-throttling"),
require("@octokit/plugin-retry")
require("@octokit/plugin-paginate-rest").paginateRest,
require("@octokit/plugin-throttling").throttling,
require("@octokit/plugin-retry").retry
).defaults({
authStrategy: require("@octokit/auth-action"),
throttle: {
onAbuseLimit: (retryAfter, options) => {
/* ... */
},
onRateLimit: (retryAfter, options) => {
/* ... */
},
},
authStrategy: require("@octokit/auth-action").createActionAuth,
userAgent: `my-octokit-action/v1.2.3`,
});

View File

@ -44,8 +44,9 @@ function _objectWithoutProperties(source, excluded) {
return target;
}
const VERSION = "3.2.4";
const VERSION = "3.6.0";
const _excluded = ["authStrategy"];
class Octokit {
constructor(options = {}) {
const hook = new beforeAfterHook.Collection();
@ -53,6 +54,7 @@ class Octokit {
baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request")
}),
mediaType: {
@ -106,7 +108,7 @@ class Octokit {
const {
authStrategy
} = options,
otherOptions = _objectWithoutProperties(options, ["authStrategy"]);
otherOptions = _objectWithoutProperties(options, _excluded);
const auth = authStrategy(Object.assign({
request: this.request,

File diff suppressed because one or more lines are too long

View File

@ -11,6 +11,7 @@ export class Octokit {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request"),
}),
mediaType: {

View File

@ -1 +1 @@
export const VERSION = "3.2.4";
export const VERSION = "3.6.0";

View File

@ -1,14 +1,10 @@
import { HookCollection } from "before-after-hook";
import { request } from "@octokit/request";
import { graphql } from "@octokit/graphql";
import { Constructor, OctokitOptions, OctokitPlugin, ReturnTypeOf, UnionToIntersection } from "./types";
import { Constructor, Hooks, OctokitOptions, OctokitPlugin, ReturnTypeOf, UnionToIntersection } from "./types";
export declare class Octokit {
static VERSION: string;
static defaults<S extends Constructor<any>>(this: S, defaults: OctokitOptions | Function): {
new (...args: any[]): {
[x: string]: any;
};
} & S;
static defaults<S extends Constructor<any>>(this: S, defaults: OctokitOptions | Function): S;
static plugins: OctokitPlugin[];
/**
* Attach a plugin (or many) to your Octokit instance.
@ -18,12 +14,7 @@ export declare class Octokit {
*/
static plugin<S extends Constructor<any> & {
plugins: any[];
}, T extends OctokitPlugin[]>(this: S, ...newPlugins: T): {
new (...args: any[]): {
[x: string]: any;
};
plugins: any[];
} & S & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;
}, T extends OctokitPlugin[]>(this: S, ...newPlugins: T): S & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;
constructor(options?: OctokitOptions);
request: typeof request;
graphql: typeof graphql;
@ -34,7 +25,6 @@ export declare class Octokit {
error: (message: string, additionalInfo?: object) => any;
[key: string]: any;
};
hook: HookCollection;
hook: HookCollection<Hooks>;
auth: (...args: unknown[]) => Promise<unknown>;
[key: string]: any;
}

View File

@ -1,7 +1,8 @@
import * as OctokitTypes from "@octokit/types";
import { RequestError } from "@octokit/request-error";
import { Octokit } from ".";
export declare type RequestParameters = OctokitTypes.RequestParameters;
export declare type OctokitOptions = {
export interface OctokitOptions {
authStrategy?: any;
auth?: any;
userAgent?: string;
@ -16,9 +17,9 @@ export declare type OctokitOptions = {
request?: OctokitTypes.RequestRequestOptions;
timeZone?: string;
[option: string]: any;
};
}
export declare type Constructor<T> = new (...args: any[]) => T;
export declare type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> = T extends AnyFunction ? ReturnType<T> : T extends AnyFunction[] ? UnionToIntersection<ReturnType<T[number]>> : never;
export declare type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> = T extends AnyFunction ? ReturnType<T> : T extends AnyFunction[] ? UnionToIntersection<Exclude<ReturnType<T[number]>, void>> : never;
/**
* @author https://stackoverflow.com/users/2887218/jcalz
* @see https://stackoverflow.com/a/50375286/10325032
@ -28,4 +29,16 @@ declare type AnyFunction = (...args: any) => any;
export declare type OctokitPlugin = (octokit: Octokit, options: OctokitOptions) => {
[key: string]: any;
} | void;
export declare type Hooks = {
request: {
Options: Required<OctokitTypes.EndpointDefaults>;
Result: OctokitTypes.OctokitResponse<any>;
Error: RequestError | Error;
};
[key: string]: {
Options: unknown;
Result: unknown;
Error: unknown;
};
};
export {};

View File

@ -1 +1 @@
export declare const VERSION = "3.2.4";
export declare const VERSION = "3.6.0";

View File

@ -4,7 +4,7 @@ import { request } from '@octokit/request';
import { withCustomRequest } from '@octokit/graphql';
import { createTokenAuth } from '@octokit/auth-token';
const VERSION = "3.2.4";
const VERSION = "3.6.0";
class Octokit {
constructor(options = {}) {
@ -13,6 +13,7 @@ class Octokit {
baseUrl: request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
// @ts-ignore internal usage only, no need to type
hook: hook.bind(null, "request"),
}),
mediaType: {

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
{
"name": "@octokit/core",
"description": "Extendable client for GitHub's REST & GraphQL APIs",
"version": "3.2.4",
"version": "3.6.0",
"license": "MIT",
"files": [
"dist-*/",
@ -16,35 +16,35 @@
"sdk",
"toolkit"
],
"repository": "https://github.com/octokit/core.js",
"repository": "github:octokit/core.js",
"dependencies": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.4.12",
"@octokit/request": "^5.6.3",
"@octokit/request-error": "^2.0.5",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.1.0",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
},
"devDependencies": {
"@octokit/auth": "^2.0.0",
"@octokit/auth": "^3.0.1",
"@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.9.0",
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^26.0.0",
"@types/jest": "^27.0.0",
"@types/lolex": "^5.1.0",
"@types/node": "^14.0.4",
"@types/node-fetch": "^2.5.0",
"fetch-mock": "^9.0.0",
"http-proxy-agent": "^4.0.1",
"jest": "^26.1.0",
"http-proxy-agent": "^5.0.0",
"jest": "^27.0.0",
"lolex": "^6.0.0",
"prettier": "^2.0.4",
"prettier": "2.4.1",
"proxy": "^1.0.1",
"semantic-release": "^17.0.0",
"semantic-release": "^18.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^26.1.3",
"ts-jest": "^27.0.0",
"typescript": "^4.0.2"
},
"publishConfig": {

View File

@ -59,7 +59,7 @@ const { endpoint } = require("@octokit/endpoint");
Example for [List organization repositories](https://developer.github.com/v3/repos/#list-organization-repositories)
```js
const requestOptions = endpoint("GET /orgs/:org/repos", {
const requestOptions = endpoint("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
@ -123,7 +123,7 @@ axios(requestOptions);
String
</td>
<td>
If set, it has to be a string consisting of URL and the request method, e.g., <code>GET /orgs/:org</code>. If it’s set to a URL, only the method defaults to <code>GET</code>.
If set, it has to be a string consisting of URL and the request method, e.g., <code>GET /orgs/{org}</code>. If it’s set to a URL, only the method defaults to <code>GET</code>.
</td>
</tr>
<tr>
@ -146,7 +146,7 @@ axios(requestOptions);
</td>
<td>
<strong>Required unless <code>route</code> is set.</strong> A path or full URL which may contain <code>:variable</code> or <code>{variable}</code> placeholders,
e.g., <code>/orgs/:org/repos</code>. The <code>url</code> is parsed using <a href="https://github.com/bramstein/url-template">url-template</a>.
e.g., <code>/orgs/{org}/repos</code>. The <code>url</code> is parsed using <a href="https://github.com/bramstein/url-template">url-template</a>.
</td>
</tr>
<tr>
@ -222,7 +222,7 @@ axios(requestOptions);
All other options will be passed depending on the `method` and `url` options.
1. If the option key has a placeholder in the `url`, it will be used as the replacement. For example, if the passed options are `{url: '/orgs/:org/repos', org: 'foo'}` the returned `options.url` is `https://api.github.com/orgs/foo/repos`.
1. If the option key has a placeholder in the `url`, it will be used as the replacement. For example, if the passed options are `{url: '/orgs/{org}/repos', org: 'foo'}` the returned `options.url` is `https://api.github.com/orgs/foo/repos`.
2. If the `method` is `GET` or `HEAD`, the option is passed as a query parameter.
3. Otherwise, the parameter is passed in the request body as a JSON key.
@ -289,7 +289,7 @@ const myEndpoint = require("@octokit/endpoint").defaults({
per_page: 100,
});
request(myEndpoint(`GET /orgs/:org/repos`));
request(myEndpoint(`GET /orgs/{org}/repos`));
```
You can call `.defaults()` again on the returned method, the defaults will cascade.
@ -337,7 +337,7 @@ const myProjectEndpoint = endpoint.defaults({
},
org: "my-project",
});
myProjectEndpoint.merge("GET /orgs/:org/repos", {
myProjectEndpoint.merge("GET /orgs/{org}/repos", {
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
@ -348,7 +348,7 @@ myProjectEndpoint.merge("GET /orgs/:org/repos", {
// {
// baseUrl: 'https://github-enterprise.acme-inc.com/api/v3',
// method: 'GET',
// url: '/orgs/:org/repos',
// url: '/orgs/{org}/repos',
// headers: {
// accept: 'application/vnd.github.v3+json',
// authorization: `token 0000000000000000000000000000000000000001`,

View File

@ -366,7 +366,7 @@ function withDefaults(oldDefaults, newDefaults) {
});
}
const VERSION = "6.0.10";
const VERSION = "6.0.12";
const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property.

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
export const VERSION = "6.0.10";
export const VERSION = "6.0.12";

View File

@ -1 +1 @@
export declare const VERSION = "6.0.10";
export declare const VERSION = "6.0.12";

View File

@ -357,7 +357,7 @@ function withDefaults(oldDefaults, newDefaults) {
});
}
const VERSION = "6.0.10";
const VERSION = "6.0.12";
const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
// DEFAULTS has all properties set that EndpointOptions has, except url.

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
{
"name": "@octokit/endpoint",
"description": "Turns REST API endpoints into generic request options",
"version": "6.0.10",
"version": "6.0.12",
"license": "MIT",
"files": [
"dist-*/",
@ -15,16 +15,9 @@
"api",
"rest"
],
"homepage": "https://github.com/octokit/endpoint.js#readme",
"bugs": {
"url": "https://github.com/octokit/endpoint.js/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/octokit/endpoint.js.git"
},
"repository": "github:octokit/endpoint.js",
"dependencies": {
"@octokit/types": "^6.0.0",
"@octokit/types": "^6.0.3",
"is-plain-object": "^5.0.0",
"universal-user-agent": "^6.0.0"
},
@ -34,11 +27,11 @@
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/jest": "^26.0.0",
"jest": "^26.0.1",
"prettier": "2.2.1",
"jest": "^27.0.0",
"prettier": "2.3.1",
"semantic-release": "^17.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^26.0.0",
"ts-jest": "^27.0.0-next.12",
"typescript": "^4.0.2"
},
"publishConfig": {

View File

@ -14,6 +14,8 @@
- [Pass query together with headers and variables](#pass-query-together-with-headers-and-variables)
- [Use with GitHub Enterprise](#use-with-github-enterprise)
- [Use custom `@octokit/request` instance](#use-custom-octokitrequest-instance)
- [TypeScript](#typescript)
- [Additional Types](#additional-types)
- [Errors](#errors)
- [Partial responses](#partial-responses)
- [Writing tests](#writing-tests)
@ -33,7 +35,7 @@ Load `@octokit/graphql` directly from [cdn.skypack.dev](https://cdn.skypack.dev)
```html
<script type="module">
import { endpoint } from "https://cdn.skypack.dev/@octokit/graphql";
import { graphql } from "https://cdn.skypack.dev/@octokit/graphql";
</script>
```
@ -247,12 +249,25 @@ await myGraphql(`
// requestCounter is now 2
```
## TypeScript
`@octokit/graphql` is exposing proper types for its usage with TypeScript projects.
### Additional Types
Additionally, `GraphQlQueryResponseData` has been exposed to users:
```ts
import type { GraphQlQueryResponseData } from "@octokit/graphql";
```
## Errors
In case of a GraphQL error, `error.message` is set to the first error from the response’s `errors` array. All errors can be accessed at `error.errors`. `error.request` has the request options such as query, variables and headers set for easier debugging.
In case of a GraphQL error, `error.message` is set to a combined message describing all errors returned by the endpoint.
All errors can be accessed at `error.errors`. `error.request` has the request options such as query, variables and headers set for easier debugging.
```js
let { graphql } = require("@octokit/graphql");
let { graphql, GraphqlResponseError } = require("@octokit/graphql");
graphqlt = graphql.defaults({
headers: {
authorization: `token secret123`,
@ -267,20 +282,30 @@ const query = `{
try {
const result = await graphql(query);
} catch (error) {
// server responds with
// {
// "data": null,
// "errors": [{
// "message": "Field 'bioHtml' doesn't exist on type 'User'",
// "locations": [{
// "line": 3,
// "column": 5
// }]
// }]
// }
if (error instanceof GraphqlResponseError) {
// do something with the error, allowing you to detect a graphql response error,
// compared to accidentally catching unrelated errors.
console.log("Request failed:", error.request); // { query, variables: {}, headers: { authorization: 'token secret123' } }
console.log(error.message); // Field 'bioHtml' doesn't exist on type 'User'
// server responds with an object like the following (as an example)
// class GraphqlResponseError {
// "headers": {
// "status": "403",
// },
// "data": null,
// "errors": [{
// "message": "Field 'bioHtml' doesn't exist on type 'User'",
// "locations": [{
// "line": 3,
// "column": 5
// }]
// }]
// }
console.log("Request failed:", error.request); // { query, variables: {}, headers: { authorization: 'token secret123' } }
console.log(error.message); // Field 'bioHtml' doesn't exist on type 'User'
} else {
// handle non-GraphQL error
}
}
```

View File

@ -5,18 +5,22 @@ Object.defineProperty(exports, '__esModule', { value: true });
var request = require('@octokit/request');
var universalUserAgent = require('universal-user-agent');
const VERSION = "4.5.8";
const VERSION = "4.8.0";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, {
headers: response.headers
});
this.name = "GraphqlError";
this.request = request; // Maintains proper stack trace (only available on V8)
function _buildMessageForResponseErrors(data) {
return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n");
}
class GraphqlResponseError extends Error {
constructor(request, headers, response) {
super(_buildMessageForResponseErrors(response));
this.request = request;
this.headers = headers;
this.response = response;
this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties.
this.errors = response.errors;
this.data = response.data; // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
@ -28,10 +32,18 @@ class GraphqlError extends Error {
}
const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
if (options) {
if (typeof query === "string" && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
for (const key in options) {
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
}
}
const parsedOptions = typeof query === "string" ? Object.assign({
@ -66,10 +78,7 @@ function graphql(request, query, options) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data
});
throw new GraphqlResponseError(requestOptions, headers, response.data);
}
return response.data.data;
@ -103,6 +112,7 @@ function withCustomRequest(customRequest) {
});
}
exports.GraphqlResponseError = GraphqlResponseError;
exports.graphql = graphql$1;
exports.withCustomRequest = withCustomRequest;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,11 +1,17 @@
export class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
function _buildMessageForResponseErrors(data) {
return (`Request failed due to following response errors:\n` +
data.errors.map((e) => ` - ${e.message}`).join("\n"));
}
export class GraphqlResponseError extends Error {
constructor(request, headers, response) {
super(_buildMessageForResponseErrors(response));
this.request = request;
this.headers = headers;
this.response = response;
this.name = "GraphqlResponseError";
// Expose the errors and response data in their shorthand properties.
this.errors = response.errors;
this.data = response.data;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {

View File

@ -1,4 +1,4 @@
import { GraphqlError } from "./error";
import { GraphqlResponseError } from "./error";
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
@ -8,10 +8,18 @@ const NON_VARIABLE_OPTIONS = [
"query",
"mediaType",
];
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
export function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
if (options) {
if (typeof query === "string" && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
for (const key in options) {
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
continue;
return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
}
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
@ -37,10 +45,7 @@ export function graphql(request, query, options) {
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
throw new GraphqlResponseError(requestOptions, headers, response.data);
}
return response.data.data;
});

View File

@ -9,6 +9,7 @@ export const graphql = withDefaults(request, {
method: "POST",
url: "/graphql",
});
export { GraphqlResponseError } from "./error";
export function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",

View File

@ -0,0 +1 @@
export {};

View File

@ -1 +1 @@
export const VERSION = "4.5.8";
export const VERSION = "4.8.0";

View File

@ -1,9 +1,13 @@
import { ResponseHeaders } from "@octokit/types";
import { GraphQlEndpointOptions, GraphQlQueryResponse } from "./types";
export declare class GraphqlError<ResponseData> extends Error {
request: GraphQlEndpointOptions;
constructor(request: GraphQlEndpointOptions, response: {
headers: ResponseHeaders;
data: Required<GraphQlQueryResponse<ResponseData>>;
});
declare type ServerResponseData<T> = Required<GraphQlQueryResponse<T>>;
export declare class GraphqlResponseError<ResponseData> extends Error {
readonly request: GraphQlEndpointOptions;
readonly headers: ResponseHeaders;
readonly response: ServerResponseData<ResponseData>;
name: string;
readonly errors: GraphQlQueryResponse<never>["errors"];
readonly data: ResponseData;
constructor(request: GraphQlEndpointOptions, headers: ResponseHeaders, response: ServerResponseData<ResponseData>);
}
export {};

View File

@ -1,3 +1,5 @@
import { request } from "@octokit/request";
export declare const graphql: import("./types").graphql;
export { GraphQlQueryResponseData } from "./types";
export { GraphqlResponseError } from "./error";
export declare function withCustomRequest(customRequest: typeof request): import("./types").graphql;

View File

@ -36,15 +36,20 @@ export declare type GraphQlQueryResponseData = {
};
export declare type GraphQlQueryResponse<ResponseData> = {
data: ResponseData;
errors?: [{
message: string;
path: [string];
extensions: {
[key: string]: any;
};
locations: [{
line: number;
column: number;
}];
}];
errors?: [
{
type: string;
message: string;
path: [string];
extensions: {
[key: string]: any;
};
locations: [
{
line: number;
column: number;
}
];
}
];
};

View File

@ -1 +1 @@
export declare const VERSION = "4.5.8";
export declare const VERSION = "4.8.0";

View File

@ -1,16 +1,22 @@
import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.8";
const VERSION = "4.8.0";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
function _buildMessageForResponseErrors(data) {
return (`Request failed due to following response errors:\n` +
data.errors.map((e) => ` - ${e.message}`).join("\n"));
}
class GraphqlResponseError extends Error {
constructor(request, headers, response) {
super(_buildMessageForResponseErrors(response));
this.request = request;
this.headers = headers;
this.response = response;
this.name = "GraphqlResponseError";
// Expose the errors and response data in their shorthand properties.
this.errors = response.errors;
this.data = response.data;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
@ -28,10 +34,18 @@ const NON_VARIABLE_OPTIONS = [
"query",
"mediaType",
];
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
if (options) {
if (typeof query === "string" && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
for (const key in options) {
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
continue;
return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
}
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
@ -57,10 +71,7 @@ function graphql(request, query, options) {
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
throw new GraphqlResponseError(requestOptions, headers, response.data);
}
return response.data.data;
});
@ -91,5 +102,5 @@ function withCustomRequest(customRequest) {
});
}
export { graphql$1 as graphql, withCustomRequest };
export { GraphqlResponseError, graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
{
"name": "@octokit/graphql",
"description": "GitHub GraphQL API client for browsers and Node",
"version": "4.5.8",
"version": "4.8.0",
"license": "MIT",
"files": [
"dist-*/",
@ -15,17 +15,10 @@
"api",
"graphql"
],
"homepage": "https://github.com/octokit/graphql.js#readme",
"bugs": {
"url": "https://github.com/octokit/graphql.js/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/octokit/graphql.js.git"
},
"repository": "github:octokit/graphql.js",
"dependencies": {
"@octokit/request": "^5.3.0",
"@octokit/types": "^6.0.0",
"@octokit/request": "^5.6.0",
"@octokit/types": "^6.0.3",
"universal-user-agent": "^6.0.0"
},
"devDependencies": {
@ -34,15 +27,15 @@
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.2.5",
"@types/jest": "^26.0.0",
"@types/jest": "^27.0.0",
"@types/node": "^14.0.4",
"fetch-mock": "^9.0.0",
"jest": "^25.1.0",
"prettier": "^2.0.0",
"jest": "^27.0.0",
"prettier": "2.3.2",
"semantic-release": "^17.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^25.1.0",
"typescript": "^3.4.5"
"ts-jest": "^27.0.0-next.12",
"typescript": "^4.0.0"
},
"publishConfig": {
"access": "public"

View File

@ -1,18 +0,0 @@
name: Release notification
on:
release:
types:
- published
jobs:
notify:
runs-on: ubuntu-latest
steps:
- uses: gr2m/await-npm-package-version-action@v1
with:
package: "@octokit/openapi-types"
version: ${{ github.event.release.tag_name }}
- uses: gr2m/release-notifier-action@v1
with:
app_id: ${{ secrets.RELEASE_NOTIFIER_APP_ID }}
private_key: ${{ secrets.RELEASE_NOTIFIER_APP_PRIVATE_KEY }}

View File

@ -1,21 +0,0 @@
name: Release
on:
push:
branches:
- main
- next
- beta
- "*.x" # maintenance releases
jobs:
release:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2.1.3
- run: npm ci
- run: npx semantic-release
env:
GITHUB_TOKEN: ${{ secrets.OCTOKITBOT_PAT }}
NPM_TOKEN: ${{ secrets.OCTOKITBOT_NPM_TOKEN }}

View File

@ -1,82 +0,0 @@
name: Update
on:
repository_dispatch:
types: ["octokit/openapi release"]
push:
branches:
- dependabot/npm_and_yarn/openapi-typescript-*
workflow_dispatch:
inputs:
version:
description: "Version of https://www.npmjs.com/package/@octokit/openapi"
required: true
jobs:
update:
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || github.event.client_payload.action == 'published'
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2.1.3
- run: npm ci
# do not update cache for dependabot update
- run: |
npm run download
npm run generate-types
if: github.event_name == 'repository_dispatch'
env:
VERSION: ${{ github.event.client_payload.release.tag_name }}
- run: |
npm run download
npm run generate-types
if: github.event_name == 'workflow_dispatch'
env:
VERSION: ${{ github.event.inputs.version }}
# create/update pull request for dispatch event update
- name: Create Pull Request
if: github.event_name != 'push'
uses: gr2m/create-or-update-pull-request-action@v1.x
env:
GITHUB_TOKEN: ${{ secrets.OCTOKITBOT_PAT }}
with:
title: "🚧 OpenAPI types changed"
body: |
Make sure to update the commits so that the merge results in helpful release notes, see [Merging the Pull Request & releasing a new version](https://github.com/octokit/rest.js/blob/master/CONTRIBUTING.md#merging-the-pull-request--releasing-a-new-version).
In general
- Avoid breaking changes at all costs
- If there are no typescript changes, use `build: cache` as commit message
- If there are there are only updates, use `fix: ...`
- If there are any new additions, use `feat: ...`
- If there are breaking changes, keep the previous ones and deprecate them. Only if there is no other way, add `BREAKING CHANGE: ...` to the commit body (not subject!) to trigger a breaking change.
branch: "openapi-update"
commit-message: "WIP"
author: "Octokit Bot <33075676+octokitbot@users.noreply.github.com>"
labels: "maintenance"
# update pull request for dependabot update
- name: Create Pull Request
if: github.event_name == 'push'
uses: gr2m/create-or-update-pull-request-action@v1.x
env:
GITHUB_TOKEN: ${{ secrets.OCTOKITBOT_PAT }}
with:
title: "🚧 OpenAPI types changed"
body: |
Make sure to update the commits so that the merge results in helpful release notes, see [Merging the Pull Request & releasing a new version](https://github.com/octokit/rest.js/blob/master/CONTRIBUTING.md#merging-the-pull-request--releasing-a-new-version).
In general
- Avoid breaking changes at all costs
- If there are no typescript changes, use `build: cache` as commit message
- If there are there are only updates, use `fix: ...`
- If there are any new additions, use `feat: ...`
- If there are breaking changes, keep the previous ones and deprecate them. Only if there is no other way, add `BREAKING CHANGE: ...` to the commit body (not subject!) to trigger a breaking change.
branch: "${{ github.ref }}"
commit-message: "WIP"
author: "Octokit Bot <33075676+octokitbot@users.noreply.github.com>"
labels: "maintenance"

View File

@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at opensource+coc@martynus.net. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [https://contributor-covenant.org/version/1/4][version]
[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/

View File

@ -1,8 +1,16 @@
# openapi-types.ts
# @octokit/openapi-types
> Generated TypeScript definitions based on GitHub's OpenAPI spec
This repository continously converts [GitHub's OpenAPI specification](https://github.com/github/rest-api-description/) into TypeScript definitions and publishes them to npm as `@octokit/openapi-types`
This package is continously updated based on [GitHub's OpenAPI specification](https://github.com/github/rest-api-description/)
## Usage
```ts
import { components } from "@octokit/openapi-types";
type Repository = components["schemas"]["full-repository"];
```
## License

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,20 @@
{
"name": "@octokit/openapi-types",
"description": "Generated TypeScript definitions based on GitHub's OpenAPI spec for api.github.com",
"repository": {
"type": "git",
"url": "https://github.com/octokit/openapi-types.ts.git",
"directory": "packages/openapi-types"
},
"publishConfig": {
"access": "public"
},
"version": "2.0.1",
"description": "Generated TypeScript definitions based on GitHub's OpenAPI spec",
"main": "generated/types.ts",
"types": "generated/types.ts",
"repository": "https://github.com/octokit/openapi-types.ts",
"keywords": [],
"version": "12.11.0",
"main": "",
"types": "types.d.ts",
"author": "Gregor Martynus (https://twitter.com/gr2m)",
"license": "MIT",
"scripts": {
"download": "node scripts/download",
"generate-types": "npx openapi-typescript cache/openapi-schema.json -o generated/types.ts",
"postgenerate-types": "node scripts/update-package"
},
"devDependencies": {
"openapi-typescript": "^2.4.2"
},
"release": {
"branches": "main"
},
"octokit": {
"openapi-version": "2.0.0"
"openapi-version": "6.8.0"
}
}

View File

@ -1,35 +0,0 @@
const { get } = require("https");
const fs = require("fs");
if (!process.env.VERSION) {
throw new Error("VERSION is not set");
}
download(process.env.VERSION.replace(/^v/, "")).then(
() => console.log("done"),
console.error
);
function download(version) {
const path = `cache/openapi-schema.json`;
const url = `https://unpkg.com/@octokit/openapi@${version}/generated/api.github.com.json`;
const file = fs.createWriteStream(path);
console.log("Downloading %s", url);
return new Promise((resolve, reject) => {
get(url, (response) => {
response.pipe(file);
file
.on("finish", () =>
file.close((error) => {
if (error) return reject(error);
console.log("%s written", path);
resolve();
})
)
.on("error", (error) => reject(error.message));
});
});
}

View File

@ -1,15 +0,0 @@
const { writeFileSync } = require("fs");
if (!process.env.VERSION) {
throw new Error("VERSION is not set");
}
const pkg = require("../package.json");
if (!pkg.octokit) {
pkg.octokit = {};
}
pkg.octokit["openapi-version"] = process.env.VERSION.replace(/^v/, "");
writeFileSync("package.json", JSON.stringify(pkg, null, 2) + "\n");

View File

@ -106,7 +106,7 @@ const issues = await octokit.paginate(
per_page: 100,
},
(response, done) => {
if (response.data.find((issues) => issue.title.includes("something"))) {
if (response.data.find((issue) => issue.title.includes("something"))) {
done();
}
return response.data;
@ -117,7 +117,7 @@ const issues = await octokit.paginate(
Alternatively you can pass a `request` method as first argument. This is great when using in combination with [`@octokit/plugin-rest-endpoint-methods`](https://github.com/octokit/plugin-rest-endpoint-methods.js/):
```js
const issues = await octokit.paginate(octokit.issues.listForRepo, {
const issues = await octokit.paginate(octokit.rest.issues.listForRepo, {
owner: "octocat",
repo: "hello-world",
since: "2010-10-01",
@ -141,7 +141,8 @@ for await (const response of octokit.paginate.iterator(
parameters
)) {
// do whatever you want with each response, break out of the loop, etc.
console.log(response.data.title);
const issues = response.data;
console.log("%d issues found", issues.length);
}
```
@ -155,11 +156,12 @@ const parameters = {
per_page: 100,
};
for await (const response of octokit.paginate.iterator(
octokit.issues.listForRepo,
octokit.rest.issues.listForRepo,
parameters
)) {
// do whatever you want with each response, break out of the loop, etc.
console.log(response.data.title);
const issues = response.data;
console.log("%d issues found", issues.length);
}
```
@ -183,6 +185,81 @@ Most of GitHub's paginating REST API endpoints return an array, but there are a
If a response is lacking the `Link` header, `octokit.paginate()` still resolves with an array, even if the response returns a single object.
## Types
The plugin also exposes some types and runtime type guards for TypeScript projects.
<table>
<tbody valign=top align=left>
<tr><th>
Types
</th><td>
```typescript
import {
PaginateInterface,
PaginatingEndpoints,
} from "@octokit/plugin-paginate-rest";
```
</td></tr>
<tr><th>
Guards
</th><td>
```typescript
import { isPaginatingEndpoint } from "@octokit/plugin-paginate-rest";
```
</td></tr>
</tbody>
</table>
### PaginateInterface
An `interface` that declares all the overloads of the `.paginate` method.
### PaginatingEndpoints
An `interface` which describes all API endpoints supported by the plugin. Some overloads of `.paginate()` method and `composePaginateRest()` function depend on `PaginatingEndpoints`, using the `keyof PaginatingEndpoints` as a type for one of its arguments.
```typescript
import { Octokit } from "@octokit/core";
import {
PaginatingEndpoints,
composePaginateRest,
} from "@octokit/plugin-paginate-rest";
type DataType<T> = "data" extends keyof T ? T["data"] : unknown;
async function myPaginatePlugin<E extends keyof PaginatingEndpoints>(
octokit: Octokit,
endpoint: E,
parameters?: PaginatingEndpoints[E]["parameters"]
): Promise<DataType<PaginatingEndpoints[E]["response"]>> {
return await composePaginateRest(octokit, endpoint, parameters);
}
```
### isPaginatingEndpoint
A type guard, `isPaginatingEndpoint(arg)` returns `true` if `arg` is one of the keys in `PaginatingEndpoints` (is `keyof PaginatingEndpoints`).
```typescript
import { Octokit } from "@octokit/core";
import {
isPaginatingEndpoint,
composePaginateRest,
} from "@octokit/plugin-paginate-rest";
async function myPlugin(octokit: Octokit, arg: unknown) {
if (isPaginatingEndpoint(arg)) {
return await composePaginateRest(octokit, arg);
}
// ...
}
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1,216 @@
export {};
export const paginatingEndpoints = [
"GET /app/hook/deliveries",
"GET /app/installations",
"GET /applications/grants",
"GET /authorizations",
"GET /enterprises/{enterprise}/actions/permissions/organizations",
"GET /enterprises/{enterprise}/actions/runner-groups",
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations",
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners",
"GET /enterprises/{enterprise}/actions/runners",
"GET /enterprises/{enterprise}/audit-log",
"GET /enterprises/{enterprise}/secret-scanning/alerts",
"GET /enterprises/{enterprise}/settings/billing/advanced-security",
"GET /events",
"GET /gists",
"GET /gists/public",
"GET /gists/starred",
"GET /gists/{gist_id}/comments",
"GET /gists/{gist_id}/commits",
"GET /gists/{gist_id}/forks",
"GET /installation/repositories",
"GET /issues",
"GET /licenses",
"GET /marketplace_listing/plans",
"GET /marketplace_listing/plans/{plan_id}/accounts",
"GET /marketplace_listing/stubbed/plans",
"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
"GET /networks/{owner}/{repo}/events",
"GET /notifications",
"GET /organizations",
"GET /orgs/{org}/actions/cache/usage-by-repository",
"GET /orgs/{org}/actions/permissions/repositories",
"GET /orgs/{org}/actions/runner-groups",
"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories",
"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners",
"GET /orgs/{org}/actions/runners",
"GET /orgs/{org}/actions/secrets",
"GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
"GET /orgs/{org}/audit-log",
"GET /orgs/{org}/blocks",
"GET /orgs/{org}/code-scanning/alerts",
"GET /orgs/{org}/codespaces",
"GET /orgs/{org}/credential-authorizations",
"GET /orgs/{org}/dependabot/secrets",
"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
"GET /orgs/{org}/events",
"GET /orgs/{org}/external-groups",
"GET /orgs/{org}/failed_invitations",
"GET /orgs/{org}/hooks",
"GET /orgs/{org}/hooks/{hook_id}/deliveries",
"GET /orgs/{org}/installations",
"GET /orgs/{org}/invitations",
"GET /orgs/{org}/invitations/{invitation_id}/teams",
"GET /orgs/{org}/issues",
"GET /orgs/{org}/members",
"GET /orgs/{org}/migrations",
"GET /orgs/{org}/migrations/{migration_id}/repositories",
"GET /orgs/{org}/outside_collaborators",
"GET /orgs/{org}/packages",
"GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
"GET /orgs/{org}/projects",
"GET /orgs/{org}/public_members",
"GET /orgs/{org}/repos",
"GET /orgs/{org}/secret-scanning/alerts",
"GET /orgs/{org}/settings/billing/advanced-security",
"GET /orgs/{org}/team-sync/groups",
"GET /orgs/{org}/teams",
"GET /orgs/{org}/teams/{team_slug}/discussions",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
"GET /orgs/{org}/teams/{team_slug}/invitations",
"GET /orgs/{org}/teams/{team_slug}/members",
"GET /orgs/{org}/teams/{team_slug}/projects",
"GET /orgs/{org}/teams/{team_slug}/repos",
"GET /orgs/{org}/teams/{team_slug}/teams",
"GET /projects/columns/{column_id}/cards",
"GET /projects/{project_id}/collaborators",
"GET /projects/{project_id}/columns",
"GET /repos/{owner}/{repo}/actions/artifacts",
"GET /repos/{owner}/{repo}/actions/caches",
"GET /repos/{owner}/{repo}/actions/runners",
"GET /repos/{owner}/{repo}/actions/runs",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
"GET /repos/{owner}/{repo}/actions/secrets",
"GET /repos/{owner}/{repo}/actions/workflows",
"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
"GET /repos/{owner}/{repo}/assignees",
"GET /repos/{owner}/{repo}/branches",
"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
"GET /repos/{owner}/{repo}/code-scanning/alerts",
"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
"GET /repos/{owner}/{repo}/code-scanning/analyses",
"GET /repos/{owner}/{repo}/codespaces",
"GET /repos/{owner}/{repo}/codespaces/devcontainers",
"GET /repos/{owner}/{repo}/codespaces/secrets",
"GET /repos/{owner}/{repo}/collaborators",
"GET /repos/{owner}/{repo}/comments",
"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/commits",
"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
"GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
"GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
"GET /repos/{owner}/{repo}/commits/{ref}/status",
"GET /repos/{owner}/{repo}/commits/{ref}/statuses",
"GET /repos/{owner}/{repo}/contributors",
"GET /repos/{owner}/{repo}/dependabot/secrets",
"GET /repos/{owner}/{repo}/deployments",
"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
"GET /repos/{owner}/{repo}/environments",
"GET /repos/{owner}/{repo}/events",
"GET /repos/{owner}/{repo}/forks",
"GET /repos/{owner}/{repo}/git/matching-refs/{ref}",
"GET /repos/{owner}/{repo}/hooks",
"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
"GET /repos/{owner}/{repo}/invitations",
"GET /repos/{owner}/{repo}/issues",
"GET /repos/{owner}/{repo}/issues/comments",
"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/issues/events",
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
"GET /repos/{owner}/{repo}/issues/{issue_number}/events",
"GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
"GET /repos/{owner}/{repo}/keys",
"GET /repos/{owner}/{repo}/labels",
"GET /repos/{owner}/{repo}/milestones",
"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
"GET /repos/{owner}/{repo}/notifications",
"GET /repos/{owner}/{repo}/pages/builds",
"GET /repos/{owner}/{repo}/projects",
"GET /repos/{owner}/{repo}/pulls",
"GET /repos/{owner}/{repo}/pulls/comments",
"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
"GET /repos/{owner}/{repo}/releases",
"GET /repos/{owner}/{repo}/releases/{release_id}/assets",
"GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
"GET /repos/{owner}/{repo}/secret-scanning/alerts",
"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
"GET /repos/{owner}/{repo}/stargazers",
"GET /repos/{owner}/{repo}/subscribers",
"GET /repos/{owner}/{repo}/tags",
"GET /repos/{owner}/{repo}/teams",
"GET /repos/{owner}/{repo}/topics",
"GET /repositories",
"GET /repositories/{repository_id}/environments/{environment_name}/secrets",
"GET /search/code",
"GET /search/commits",
"GET /search/issues",
"GET /search/labels",
"GET /search/repositories",
"GET /search/topics",
"GET /search/users",
"GET /teams/{team_id}/discussions",
"GET /teams/{team_id}/discussions/{discussion_number}/comments",
"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
"GET /teams/{team_id}/discussions/{discussion_number}/reactions",
"GET /teams/{team_id}/invitations",
"GET /teams/{team_id}/members",
"GET /teams/{team_id}/projects",
"GET /teams/{team_id}/repos",
"GET /teams/{team_id}/teams",
"GET /user/blocks",
"GET /user/codespaces",
"GET /user/codespaces/secrets",
"GET /user/emails",
"GET /user/followers",
"GET /user/following",
"GET /user/gpg_keys",
"GET /user/installations",
"GET /user/installations/{installation_id}/repositories",
"GET /user/issues",
"GET /user/keys",
"GET /user/marketplace_purchases",
"GET /user/marketplace_purchases/stubbed",
"GET /user/memberships/orgs",
"GET /user/migrations",
"GET /user/migrations/{migration_id}/repositories",
"GET /user/orgs",
"GET /user/packages",
"GET /user/packages/{package_type}/{package_name}/versions",
"GET /user/public_emails",
"GET /user/repos",
"GET /user/repository_invitations",
"GET /user/starred",
"GET /user/subscriptions",
"GET /user/teams",
"GET /users",
"GET /users/{username}/events",
"GET /users/{username}/events/orgs/{org}",
"GET /users/{username}/events/public",
"GET /users/{username}/followers",
"GET /users/{username}/following",
"GET /users/{username}/gists",
"GET /users/{username}/gpg_keys",
"GET /users/{username}/keys",
"GET /users/{username}/orgs",
"GET /users/{username}/packages",
"GET /users/{username}/projects",
"GET /users/{username}/received_events",
"GET /users/{username}/received_events/public",
"GET /users/{username}/repos",
"GET /users/{username}/starred",
"GET /users/{username}/subscriptions",
];

View File

@ -2,6 +2,7 @@ import { VERSION } from "./version";
import { paginate } from "./paginate";
import { iterator } from "./iterator";
export { composePaginateRest } from "./compose-paginate";
export { isPaginatingEndpoint, paginatingEndpoints, } from "./paginating-endpoints";
/**
* @param octokit Octokit instance
* @param options Options passed to Octokit constructor

View File

@ -12,13 +12,27 @@ export function iterator(octokit, route, parameters) {
async next() {
if (!url)
return { done: true };
const response = await requestMethod({ method, url, headers });
const normalizedResponse = normalizePaginatedListResponse(response);
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return { value: normalizedResponse };
try {
const response = await requestMethod({ method, url, headers });
const normalizedResponse = normalizePaginatedListResponse(response);
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return { value: normalizedResponse };
}
catch (error) {
if (error.status !== 409)
throw error;
url = "";
return {
value: {
status: 200,
headers: {},
data: [],
},
};
}
},
}),
};

View File

@ -15,6 +15,13 @@
* otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
*/
export function normalizePaginatedListResponse(response) {
// endpoints can respond with 204 if repository is empty
if (!response.data) {
return {
...response,
data: [],
};
}
const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
if (!responseNeedsNormalization)
return response;

View File

@ -1 +1 @@
export const VERSION = "2.6.2";
export const VERSION = "2.21.3";

View File

@ -1,7 +1,14 @@
import { Endpoints } from "@octokit/types";
export interface PaginatingEndpoints {
/**
* @see https://docs.github.com/v3/apps/#list-installations-for-the-authenticated-app
* @see https://docs.github.com/rest/reference/apps#list-deliveries-for-an-app-webhook
*/
"GET /app/hook/deliveries": {
parameters: Endpoints["GET /app/hook/deliveries"]["parameters"];
response: Endpoints["GET /app/hook/deliveries"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/apps#list-installations-for-the-authenticated-app
*/
"GET /app/installations": {
parameters: Endpoints["GET /app/installations"]["parameters"];
@ -22,7 +29,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /authorizations"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-selected-organizations-enabled-for-github-actions-in-an-enterprise
* @see https://docs.github.com/rest/reference/actions#list-selected-organizations-enabled-for-github-actions-in-an-enterprise
*/
"GET /enterprises/{enterprise}/actions/permissions/organizations": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/permissions/organizations"]["parameters"];
@ -31,7 +38,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runner-groups-for-an-enterprise
* @see https://docs.github.com/rest/reference/actions#list-self-hosted-runner-groups-for-an-enterprise
*/
"GET /enterprises/{enterprise}/actions/runner-groups": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups"]["parameters"];
@ -40,7 +47,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise
* @see https://docs.github.com/rest/reference/actions#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise
*/
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations"]["parameters"];
@ -49,7 +56,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runners-in-a-group-for-an-enterprise
* @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-enterprise
*/
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners"]["parameters"];
@ -58,7 +65,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-self-hosted-runners-for-an-enterprise
* @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-for-an-enterprise
*/
"GET /enterprises/{enterprise}/actions/runners": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/runners"]["parameters"];
@ -67,11 +74,27 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-runner-applications-for-an-enterprise
* @see https://docs.github.com/rest/reference/enterprise-admin#get-the-audit-log-for-an-enterprise
*/
"GET /enterprises/{enterprise}/actions/runners/downloads": {
parameters: Endpoints["GET /enterprises/{enterprise}/actions/runners/downloads"]["parameters"];
response: Endpoints["GET /enterprises/{enterprise}/actions/runners/downloads"]["response"];
"GET /enterprises/{enterprise}/audit-log": {
parameters: Endpoints["GET /enterprises/{enterprise}/audit-log"]["parameters"];
response: Endpoints["GET /enterprises/{enterprise}/audit-log"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/secret-scanning#list-secret-scanning-alerts-for-an-enterprise
*/
"GET /enterprises/{enterprise}/secret-scanning/alerts": {
parameters: Endpoints["GET /enterprises/{enterprise}/secret-scanning/alerts"]["parameters"];
response: Endpoints["GET /enterprises/{enterprise}/secret-scanning/alerts"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/billing#export-advanced-security-active-committers-data-for-enterprise
*/
"GET /enterprises/{enterprise}/settings/billing/advanced-security": {
parameters: Endpoints["GET /enterprises/{enterprise}/settings/billing/advanced-security"]["parameters"];
response: Endpoints["GET /enterprises/{enterprise}/settings/billing/advanced-security"]["response"] & {
data: Endpoints["GET /enterprises/{enterprise}/settings/billing/advanced-security"]["response"]["data"]["repositories"];
};
};
/**
* @see https://docs.github.com/rest/reference/activity#list-public-events
@ -81,21 +104,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /events"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-gists-for-the-authenticated-user
* @see https://docs.github.com/rest/reference/gists#list-gists-for-the-authenticated-user
*/
"GET /gists": {
parameters: Endpoints["GET /gists"]["parameters"];
response: Endpoints["GET /gists"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-public-gists
* @see https://docs.github.com/rest/reference/gists#list-public-gists
*/
"GET /gists/public": {
parameters: Endpoints["GET /gists/public"]["parameters"];
response: Endpoints["GET /gists/public"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-starred-gists
* @see https://docs.github.com/rest/reference/gists#list-starred-gists
*/
"GET /gists/starred": {
parameters: Endpoints["GET /gists/starred"]["parameters"];
@ -109,14 +132,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /gists/{gist_id}/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-gist-commits
* @see https://docs.github.com/rest/reference/gists#list-gist-commits
*/
"GET /gists/{gist_id}/commits": {
parameters: Endpoints["GET /gists/{gist_id}/commits"]["parameters"];
response: Endpoints["GET /gists/{gist_id}/commits"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-gist-forks
* @see https://docs.github.com/rest/reference/gists#list-gist-forks
*/
"GET /gists/{gist_id}/forks": {
parameters: Endpoints["GET /gists/{gist_id}/forks"]["parameters"];
@ -132,12 +155,19 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/issues/#list-issues-assigned-to-the-authenticated-user
* @see https://docs.github.com/rest/reference/issues#list-issues-assigned-to-the-authenticated-user
*/
"GET /issues": {
parameters: Endpoints["GET /issues"]["parameters"];
response: Endpoints["GET /issues"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/licenses#get-all-commonly-used-licenses
*/
"GET /licenses": {
parameters: Endpoints["GET /licenses"]["parameters"];
response: Endpoints["GET /licenses"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/apps#list-plans
*/
@ -181,12 +211,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /notifications"]["response"];
};
/**
* @see https://docs.github.com/v3/orgs/#list-organizations
* @see https://docs.github.com/rest/reference/orgs#list-organizations
*/
"GET /organizations": {
parameters: Endpoints["GET /organizations"]["parameters"];
response: Endpoints["GET /organizations"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/actions#list-repositories-with-github-actions-cache-usage-for-an-organization
*/
"GET /orgs/{org}/actions/cache/usage-by-repository": {
parameters: Endpoints["GET /orgs/{org}/actions/cache/usage-by-repository"]["parameters"];
response: Endpoints["GET /orgs/{org}/actions/cache/usage-by-repository"]["response"] & {
data: Endpoints["GET /orgs/{org}/actions/cache/usage-by-repository"]["response"]["data"]["repository_cache_usages"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-selected-repositories-enabled-for-github-actions-in-an-organization
*/
@ -232,13 +271,6 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /orgs/{org}/actions/runners"]["response"]["data"]["runners"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-runner-applications-for-an-organization
*/
"GET /orgs/{org}/actions/runners/downloads": {
parameters: Endpoints["GET /orgs/{org}/actions/runners/downloads"]["parameters"];
response: Endpoints["GET /orgs/{org}/actions/runners/downloads"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/actions#list-organization-secrets
*/
@ -257,6 +289,13 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"]["response"]["data"]["repositories"];
};
};
/**
* @see https://docs.github.com/rest/reference/orgs#get-audit-log
*/
"GET /orgs/{org}/audit-log": {
parameters: Endpoints["GET /orgs/{org}/audit-log"]["parameters"];
response: Endpoints["GET /orgs/{org}/audit-log"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/orgs#list-users-blocked-by-an-organization
*/
@ -265,12 +304,46 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/blocks"]["response"];
};
/**
* @see https://docs.github.com/v3/orgs/#list-saml-sso-authorizations-for-an-organization
* @see https://docs.github.com/rest/reference/code-scanning#list-code-scanning-alerts-by-organization
*/
"GET /orgs/{org}/code-scanning/alerts": {
parameters: Endpoints["GET /orgs/{org}/code-scanning/alerts"]["parameters"];
response: Endpoints["GET /orgs/{org}/code-scanning/alerts"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-in-organization
*/
"GET /orgs/{org}/codespaces": {
parameters: Endpoints["GET /orgs/{org}/codespaces"]["parameters"];
response: Endpoints["GET /orgs/{org}/codespaces"]["response"] & {
data: Endpoints["GET /orgs/{org}/codespaces"]["response"]["data"]["codespaces"];
};
};
/**
* @see https://docs.github.com/rest/reference/orgs#list-saml-sso-authorizations-for-an-organization
*/
"GET /orgs/{org}/credential-authorizations": {
parameters: Endpoints["GET /orgs/{org}/credential-authorizations"]["parameters"];
response: Endpoints["GET /orgs/{org}/credential-authorizations"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/dependabot#list-organization-secrets
*/
"GET /orgs/{org}/dependabot/secrets": {
parameters: Endpoints["GET /orgs/{org}/dependabot/secrets"]["parameters"];
response: Endpoints["GET /orgs/{org}/dependabot/secrets"]["response"] & {
data: Endpoints["GET /orgs/{org}/dependabot/secrets"]["response"]["data"]["secrets"];
};
};
/**
* @see https://docs.github.com/rest/reference/dependabot#list-selected-repositories-for-an-organization-secret
*/
"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories": {
parameters: Endpoints["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]["parameters"];
response: Endpoints["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]["response"] & {
data: Endpoints["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]["response"]["data"]["repositories"];
};
};
/**
* @see https://docs.github.com/rest/reference/activity#list-public-organization-events
*/
@ -278,6 +351,22 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /orgs/{org}/events"]["parameters"];
response: Endpoints["GET /orgs/{org}/events"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/teams#list-external-idp-groups-for-an-organization
*/
"GET /orgs/{org}/external-groups": {
parameters: Endpoints["GET /orgs/{org}/external-groups"]["parameters"];
response: Endpoints["GET /orgs/{org}/external-groups"]["response"] & {
data: Endpoints["GET /orgs/{org}/external-groups"]["response"]["data"]["groups"];
};
};
/**
* @see https://docs.github.com/rest/reference/orgs#list-failed-organization-invitations
*/
"GET /orgs/{org}/failed_invitations": {
parameters: Endpoints["GET /orgs/{org}/failed_invitations"]["parameters"];
response: Endpoints["GET /orgs/{org}/failed_invitations"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/orgs#list-organization-webhooks
*/
@ -286,7 +375,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/hooks"]["response"];
};
/**
* @see https://docs.github.com/v3/orgs/#list-app-installations-for-an-organization
* @see https://docs.github.com/rest/reference/orgs#list-deliveries-for-an-organization-webhook
*/
"GET /orgs/{org}/hooks/{hook_id}/deliveries": {
parameters: Endpoints["GET /orgs/{org}/hooks/{hook_id}/deliveries"]["parameters"];
response: Endpoints["GET /orgs/{org}/hooks/{hook_id}/deliveries"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/orgs#list-app-installations-for-an-organization
*/
"GET /orgs/{org}/installations": {
parameters: Endpoints["GET /orgs/{org}/installations"]["parameters"];
@ -309,7 +405,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/invitations/{invitation_id}/teams"]["response"];
};
/**
* @see https://docs.github.com/v3/issues/#list-organization-issues-assigned-to-the-authenticated-user
* @see https://docs.github.com/rest/reference/issues#list-organization-issues-assigned-to-the-authenticated-user
*/
"GET /orgs/{org}/issues": {
parameters: Endpoints["GET /orgs/{org}/issues"]["parameters"];
@ -344,7 +440,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/outside_collaborators"]["response"];
};
/**
* @see https://docs.github.com/v3/projects/#list-organization-projects
* @see https://docs.github.com/rest/reference/packages#list-packages-for-an-organization
*/
"GET /orgs/{org}/packages": {
parameters: Endpoints["GET /orgs/{org}/packages"]["parameters"];
response: Endpoints["GET /orgs/{org}/packages"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/packages#get-all-package-versions-for-a-package-owned-by-an-organization
*/
"GET /orgs/{org}/packages/{package_type}/{package_name}/versions": {
parameters: Endpoints["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"]["parameters"];
response: Endpoints["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/projects#list-organization-projects
*/
"GET /orgs/{org}/projects": {
parameters: Endpoints["GET /orgs/{org}/projects"]["parameters"];
@ -358,12 +468,28 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/public_members"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-organization-repositories
* @see https://docs.github.com/rest/reference/repos#list-organization-repositories
*/
"GET /orgs/{org}/repos": {
parameters: Endpoints["GET /orgs/{org}/repos"]["parameters"];
response: Endpoints["GET /orgs/{org}/repos"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/secret-scanning#list-secret-scanning-alerts-for-an-organization
*/
"GET /orgs/{org}/secret-scanning/alerts": {
parameters: Endpoints["GET /orgs/{org}/secret-scanning/alerts"]["parameters"];
response: Endpoints["GET /orgs/{org}/secret-scanning/alerts"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/billing#get-github-advanced-security-active-committers-for-an-organization
*/
"GET /orgs/{org}/settings/billing/advanced-security": {
parameters: Endpoints["GET /orgs/{org}/settings/billing/advanced-security"]["parameters"];
response: Endpoints["GET /orgs/{org}/settings/billing/advanced-security"]["response"] & {
data: Endpoints["GET /orgs/{org}/settings/billing/advanced-security"]["response"]["data"]["repositories"];
};
};
/**
* @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-an-organization
*/
@ -374,7 +500,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/teams/#list-teams
* @see https://docs.github.com/rest/reference/teams#list-teams
*/
"GET /orgs/{org}/teams": {
parameters: Endpoints["GET /orgs/{org}/teams"]["parameters"];
@ -395,14 +521,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-team-discussion-comment
*/
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["parameters"];
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-team-discussion
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-team-discussion
*/
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]["parameters"];
@ -423,30 +549,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/members"]["response"];
};
/**
* @see https://docs.github.com/v3/teams/#list-team-projects
* @see https://docs.github.com/rest/reference/teams#list-team-projects
*/
"GET /orgs/{org}/teams/{team_slug}/projects": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/projects"]["parameters"];
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/projects"]["response"];
};
/**
* @see https://docs.github.com/v3/teams/#list-team-repositories
* @see https://docs.github.com/rest/reference/teams#list-team-repositories
*/
"GET /orgs/{org}/teams/{team_slug}/repos": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/repos"]["parameters"];
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/repos"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-a-team
*/
"GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["parameters"];
response: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["response"] & {
data: Endpoints["GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings"]["response"]["data"]["groups"];
};
};
/**
* @see https://docs.github.com/v3/teams/#list-child-teams
* @see https://docs.github.com/rest/reference/teams#list-child-teams
*/
"GET /orgs/{org}/teams/{team_slug}/teams": {
parameters: Endpoints["GET /orgs/{org}/teams/{team_slug}/teams"]["parameters"];
@ -482,6 +599,15 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /repos/{owner}/{repo}/actions/artifacts"]["response"]["data"]["artifacts"];
};
};
/**
* @see https://docs.github.com/rest/actions/cache#list-github-actions-caches-for-a-repository
*/
"GET /repos/{owner}/{repo}/actions/caches": {
parameters: Endpoints["GET /repos/{owner}/{repo}/actions/caches"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/actions/caches"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/actions/caches"]["response"]["data"]["actions_caches"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-self-hosted-runners-for-a-repository
*/
@ -491,13 +617,6 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /repos/{owner}/{repo}/actions/runners"]["response"]["data"]["runners"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-runner-applications-for-a-repository
*/
"GET /repos/{owner}/{repo}/actions/runners/downloads": {
parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runners/downloads"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/actions/runners/downloads"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/actions#list-workflow-runs-for-a-repository
*/
@ -516,6 +635,15 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"]["response"]["data"]["artifacts"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-jobs-for-a-workflow-run-attempt
*/
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs": {
parameters: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"]["response"]["data"]["jobs"];
};
};
/**
* @see https://docs.github.com/rest/reference/actions#list-jobs-for-a-workflow-run
*/
@ -583,19 +711,53 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/code-scanning/#list-code-scanning-alerts-for-a-repository
* @see https://docs.github.com/rest/reference/code-scanning#list-code-scanning-alerts-for-a-repository
*/
"GET /repos/{owner}/{repo}/code-scanning/alerts": {
parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts"]["response"];
};
/**
* @see https://docs.github.com/v3/code-scanning/#list-recent-analyses
* @see https://docs.github.com/rest/reference/code-scanning#list-instances-of-a-code-scanning-alert
*/
"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances": {
parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/code-scanning#list-code-scanning-analyses-for-a-repository
*/
"GET /repos/{owner}/{repo}/code-scanning/analyses": {
parameters: Endpoints["GET /repos/{owner}/{repo}/code-scanning/analyses"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/code-scanning/analyses"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-codespaces-in-a-repository-for-the-authenticated-user
*/
"GET /repos/{owner}/{repo}/codespaces": {
parameters: Endpoints["GET /repos/{owner}/{repo}/codespaces"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/codespaces"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/codespaces"]["response"]["data"]["codespaces"];
};
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-devcontainers-in-a-repository-for-the-authenticated-user
*/
"GET /repos/{owner}/{repo}/codespaces/devcontainers": {
parameters: Endpoints["GET /repos/{owner}/{repo}/codespaces/devcontainers"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/codespaces/devcontainers"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/codespaces/devcontainers"]["response"]["data"]["devcontainers"];
};
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-repository-secrets
*/
"GET /repos/{owner}/{repo}/codespaces/secrets": {
parameters: Endpoints["GET /repos/{owner}/{repo}/codespaces/secrets"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/codespaces/secrets"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/codespaces/secrets"]["response"]["data"]["secrets"];
};
};
/**
* @see https://docs.github.com/rest/reference/repos#list-repository-collaborators
*/
@ -611,7 +773,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-commit-comment
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-commit-comment
*/
"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions": {
parameters: Endpoints["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"]["parameters"];
@ -624,13 +786,6 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /repos/{owner}/{repo}/commits"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/commits"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/repos#list-branches-for-head-commit
*/
"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head": {
parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/repos#list-commit-comments
*/
@ -663,6 +818,15 @@ export interface PaginatingEndpoints {
data: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"]["response"]["data"]["check_suites"];
};
};
/**
* @see https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference
*/
"GET /repos/{owner}/{repo}/commits/{ref}/status": {
parameters: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/status"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/status"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/status"]["response"]["data"]["statuses"];
};
};
/**
* @see https://docs.github.com/rest/reference/repos#list-commit-statuses-for-a-reference
*/
@ -671,12 +835,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/commits/{ref}/statuses"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-repository-contributors
* @see https://docs.github.com/rest/reference/repos#list-repository-contributors
*/
"GET /repos/{owner}/{repo}/contributors": {
parameters: Endpoints["GET /repos/{owner}/{repo}/contributors"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/contributors"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/dependabot#list-repository-secrets
*/
"GET /repos/{owner}/{repo}/dependabot/secrets": {
parameters: Endpoints["GET /repos/{owner}/{repo}/dependabot/secrets"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/dependabot/secrets"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/dependabot/secrets"]["response"]["data"]["secrets"];
};
};
/**
* @see https://docs.github.com/rest/reference/repos#list-deployments
*/
@ -691,6 +864,15 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/repos#get-all-environments
*/
"GET /repos/{owner}/{repo}/environments": {
parameters: Endpoints["GET /repos/{owner}/{repo}/environments"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/environments"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/environments"]["response"]["data"]["environments"];
};
};
/**
* @see https://docs.github.com/rest/reference/activity#list-repository-events
*/
@ -719,6 +901,13 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /repos/{owner}/{repo}/hooks"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/hooks"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/repos#list-deliveries-for-a-repository-webhook
*/
"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries": {
parameters: Endpoints["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/repos#list-repository-invitations
*/
@ -727,7 +916,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/invitations"]["response"];
};
/**
* @see https://docs.github.com/v3/issues/#list-repository-issues
* @see https://docs.github.com/rest/reference/issues#list-repository-issues
*/
"GET /repos/{owner}/{repo}/issues": {
parameters: Endpoints["GET /repos/{owner}/{repo}/issues"]["parameters"];
@ -741,7 +930,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/issues/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-an-issue-comment
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-an-issue-comment
*/
"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions": {
parameters: Endpoints["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"]["parameters"];
@ -776,7 +965,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-an-issue
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-an-issue
*/
"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions": {
parameters: Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"]["parameters"];
@ -832,14 +1021,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/pages/builds"]["response"];
};
/**
* @see https://docs.github.com/v3/projects/#list-repository-projects
* @see https://docs.github.com/rest/reference/projects#list-repository-projects
*/
"GET /repos/{owner}/{repo}/projects": {
parameters: Endpoints["GET /repos/{owner}/{repo}/projects"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/projects"]["response"];
};
/**
* @see https://docs.github.com/v3/pulls/#list-pull-requests
* @see https://docs.github.com/rest/reference/pulls#list-pull-requests
*/
"GET /repos/{owner}/{repo}/pulls": {
parameters: Endpoints["GET /repos/{owner}/{repo}/pulls"]["parameters"];
@ -853,7 +1042,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/pulls/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-pull-request-review-comment
* @see https://docs.github.com/rest/reference/reactions#list-reactions-for-a-pull-request-review-comment
*/
"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions": {
parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"]["parameters"];
@ -867,14 +1056,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/pulls/#list-commits-on-a-pull-request
* @see https://docs.github.com/rest/reference/pulls#list-commits-on-a-pull-request
*/
"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits": {
parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"]["response"];
};
/**
* @see https://docs.github.com/v3/pulls/#list-pull-requests-files
* @see https://docs.github.com/rest/reference/pulls#list-pull-requests-files
*/
"GET /repos/{owner}/{repo}/pulls/{pull_number}/files": {
parameters: Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"]["parameters"];
@ -917,6 +1106,27 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/assets"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/assets"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/reactions/#list-reactions-for-a-release
*/
"GET /repos/{owner}/{repo}/releases/{release_id}/reactions": {
parameters: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/secret-scanning#list-secret-scanning-alerts-for-a-repository
*/
"GET /repos/{owner}/{repo}/secret-scanning/alerts": {
parameters: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/secret-scanning#list-locations-for-a-secret-scanning-alert
*/
"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations": {
parameters: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/activity#list-stargazers
*/
@ -932,55 +1142,46 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /repos/{owner}/{repo}/subscribers"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-repository-tags
* @see https://docs.github.com/rest/reference/repos#list-repository-tags
*/
"GET /repos/{owner}/{repo}/tags": {
parameters: Endpoints["GET /repos/{owner}/{repo}/tags"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/tags"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-repository-teams
* @see https://docs.github.com/rest/reference/repos#list-repository-teams
*/
"GET /repos/{owner}/{repo}/teams": {
parameters: Endpoints["GET /repos/{owner}/{repo}/teams"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/teams"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-public-repositories
* @see https://docs.github.com/rest/reference/repos#get-all-repository-topics
*/
"GET /repos/{owner}/{repo}/topics": {
parameters: Endpoints["GET /repos/{owner}/{repo}/topics"]["parameters"];
response: Endpoints["GET /repos/{owner}/{repo}/topics"]["response"] & {
data: Endpoints["GET /repos/{owner}/{repo}/topics"]["response"]["data"]["names"];
};
};
/**
* @see https://docs.github.com/rest/reference/repos#list-public-repositories
*/
"GET /repositories": {
parameters: Endpoints["GET /repositories"]["parameters"];
response: Endpoints["GET /repositories"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-provisioned-scim groups-for-an-enterprise
* @see https://docs.github.com/rest/reference/actions#list-environment-secrets
*/
"GET /scim/v2/enterprises/{enterprise}/Groups": {
parameters: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["parameters"];
response: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["response"] & {
data: Endpoints["GET /scim/v2/enterprises/{enterprise}/Groups"]["response"]["data"]["Resources"];
"GET /repositories/{repository_id}/environments/{environment_name}/secrets": {
parameters: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["parameters"];
response: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["response"] & {
data: Endpoints["GET /repositories/{repository_id}/environments/{environment_name}/secrets"]["response"]["data"]["secrets"];
};
};
/**
* @see https://docs.github.com/rest/reference/enterprise-admin#list-scim-provisioned-identities-for-an-enterprise
*/
"GET /scim/v2/enterprises/{enterprise}/Users": {
parameters: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["parameters"];
response: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["response"] & {
data: Endpoints["GET /scim/v2/enterprises/{enterprise}/Users"]["response"]["data"]["Resources"];
};
};
/**
* @see https://docs.github.com/v3/scim/#list-scim-provisioned-identities
*/
"GET /scim/v2/organizations/{org}/Users": {
parameters: Endpoints["GET /scim/v2/organizations/{org}/Users"]["parameters"];
response: Endpoints["GET /scim/v2/organizations/{org}/Users"]["response"] & {
data: Endpoints["GET /scim/v2/organizations/{org}/Users"]["response"]["data"]["Resources"];
};
};
/**
* @see https://docs.github.com/v3/search/#search-code
* @see https://docs.github.com/rest/reference/search#search-code
*/
"GET /search/code": {
parameters: Endpoints["GET /search/code"]["parameters"];
@ -989,7 +1190,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-commits
* @see https://docs.github.com/rest/reference/search#search-commits
*/
"GET /search/commits": {
parameters: Endpoints["GET /search/commits"]["parameters"];
@ -998,7 +1199,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-issues-and-pull-requests
* @see https://docs.github.com/rest/reference/search#search-issues-and-pull-requests
*/
"GET /search/issues": {
parameters: Endpoints["GET /search/issues"]["parameters"];
@ -1007,7 +1208,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-labels
* @see https://docs.github.com/rest/reference/search#search-labels
*/
"GET /search/labels": {
parameters: Endpoints["GET /search/labels"]["parameters"];
@ -1016,7 +1217,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-repositories
* @see https://docs.github.com/rest/reference/search#search-repositories
*/
"GET /search/repositories": {
parameters: Endpoints["GET /search/repositories"]["parameters"];
@ -1025,7 +1226,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-topics
* @see https://docs.github.com/rest/reference/search#search-topics
*/
"GET /search/topics": {
parameters: Endpoints["GET /search/topics"]["parameters"];
@ -1034,7 +1235,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/search/#search-users
* @see https://docs.github.com/rest/reference/search#search-users
*/
"GET /search/users": {
parameters: Endpoints["GET /search/users"]["parameters"];
@ -1057,14 +1258,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment-legacy
* @see https://docs.github.com/rest/reference/reactions/#list-reactions-for-a-team-discussion-comment-legacy
*/
"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions": {
parameters: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["parameters"];
response: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions"]["response"];
};
/**
* @see https://docs.github.com/v3/reactions/#list-reactions-for-a-team-discussion-legacy
* @see https://docs.github.com/rest/reference/reactions/#list-reactions-for-a-team-discussion-legacy
*/
"GET /teams/{team_id}/discussions/{discussion_number}/reactions": {
parameters: Endpoints["GET /teams/{team_id}/discussions/{discussion_number}/reactions"]["parameters"];
@ -1085,30 +1286,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /teams/{team_id}/members"]["response"];
};
/**
* @see https://docs.github.com/v3/teams/#list-team-projects-legacy
* @see https://docs.github.com/rest/reference/teams/#list-team-projects-legacy
*/
"GET /teams/{team_id}/projects": {
parameters: Endpoints["GET /teams/{team_id}/projects"]["parameters"];
response: Endpoints["GET /teams/{team_id}/projects"]["response"];
};
/**
* @see https://docs.github.com/v3/teams/#list-team-repositories-legacy
* @see https://docs.github.com/rest/reference/teams/#list-team-repositories-legacy
*/
"GET /teams/{team_id}/repos": {
parameters: Endpoints["GET /teams/{team_id}/repos"]["parameters"];
response: Endpoints["GET /teams/{team_id}/repos"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/teams#list-idp-groups-for-a-team-legacy
*/
"GET /teams/{team_id}/team-sync/group-mappings": {
parameters: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["parameters"];
response: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["response"] & {
data: Endpoints["GET /teams/{team_id}/team-sync/group-mappings"]["response"]["data"]["groups"];
};
};
/**
* @see https://docs.github.com/v3/teams/#list-child-teams-legacy
* @see https://docs.github.com/rest/reference/teams/#list-child-teams-legacy
*/
"GET /teams/{team_id}/teams": {
parameters: Endpoints["GET /teams/{team_id}/teams"]["parameters"];
@ -1121,6 +1313,24 @@ export interface PaginatingEndpoints {
parameters: Endpoints["GET /user/blocks"]["parameters"];
response: Endpoints["GET /user/blocks"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-codespaces-for-the-authenticated-user
*/
"GET /user/codespaces": {
parameters: Endpoints["GET /user/codespaces"]["parameters"];
response: Endpoints["GET /user/codespaces"]["response"] & {
data: Endpoints["GET /user/codespaces"]["response"]["data"]["codespaces"];
};
};
/**
* @see https://docs.github.com/rest/reference/codespaces#list-secrets-for-the-authenticated-user
*/
"GET /user/codespaces/secrets": {
parameters: Endpoints["GET /user/codespaces/secrets"]["parameters"];
response: Endpoints["GET /user/codespaces/secrets"]["response"] & {
data: Endpoints["GET /user/codespaces/secrets"]["response"]["data"]["secrets"];
};
};
/**
* @see https://docs.github.com/rest/reference/users#list-email-addresses-for-the-authenticated-user
*/
@ -1168,7 +1378,7 @@ export interface PaginatingEndpoints {
};
};
/**
* @see https://docs.github.com/v3/issues/#list-user-account-issues-assigned-to-the-authenticated-user
* @see https://docs.github.com/rest/reference/issues#list-user-account-issues-assigned-to-the-authenticated-user
*/
"GET /user/issues": {
parameters: Endpoints["GET /user/issues"]["parameters"];
@ -1217,12 +1427,26 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /user/migrations/{migration_id}/repositories"]["response"];
};
/**
* @see https://docs.github.com/v3/orgs/#list-organizations-for-the-authenticated-user
* @see https://docs.github.com/rest/reference/orgs#list-organizations-for-the-authenticated-user
*/
"GET /user/orgs": {
parameters: Endpoints["GET /user/orgs"]["parameters"];
response: Endpoints["GET /user/orgs"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/packages#list-packages-for-the-authenticated-user
*/
"GET /user/packages": {
parameters: Endpoints["GET /user/packages"]["parameters"];
response: Endpoints["GET /user/packages"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/packages#get-all-package-versions-for-a-package-owned-by-the-authenticated-user
*/
"GET /user/packages/{package_type}/{package_name}/versions": {
parameters: Endpoints["GET /user/packages/{package_type}/{package_name}/versions"]["parameters"];
response: Endpoints["GET /user/packages/{package_type}/{package_name}/versions"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/users#list-public-email-addresses-for-the-authenticated-user
*/
@ -1231,7 +1455,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /user/public_emails"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-repositories-for-the-authenticated-user
* @see https://docs.github.com/rest/reference/repos#list-repositories-for-the-authenticated-user
*/
"GET /user/repos": {
parameters: Endpoints["GET /user/repos"]["parameters"];
@ -1259,14 +1483,14 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /user/subscriptions"]["response"];
};
/**
* @see https://docs.github.com/v3/teams/#list-teams-for-the-authenticated-user
* @see https://docs.github.com/rest/reference/teams#list-teams-for-the-authenticated-user
*/
"GET /user/teams": {
parameters: Endpoints["GET /user/teams"]["parameters"];
response: Endpoints["GET /user/teams"]["response"];
};
/**
* @see https://docs.github.com/v3/users/#list-users
* @see https://docs.github.com/rest/reference/users#list-users
*/
"GET /users": {
parameters: Endpoints["GET /users"]["parameters"];
@ -1308,7 +1532,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /users/{username}/following"]["response"];
};
/**
* @see https://docs.github.com/v3/gists/#list-gists-for-a-user
* @see https://docs.github.com/rest/reference/gists#list-gists-for-a-user
*/
"GET /users/{username}/gists": {
parameters: Endpoints["GET /users/{username}/gists"]["parameters"];
@ -1329,14 +1553,21 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /users/{username}/keys"]["response"];
};
/**
* @see https://docs.github.com/v3/orgs/#list-organizations-for-a-user
* @see https://docs.github.com/rest/reference/orgs#list-organizations-for-a-user
*/
"GET /users/{username}/orgs": {
parameters: Endpoints["GET /users/{username}/orgs"]["parameters"];
response: Endpoints["GET /users/{username}/orgs"]["response"];
};
/**
* @see https://docs.github.com/v3/projects/#list-user-projects
* @see https://docs.github.com/rest/reference/packages#list-packages-for-user
*/
"GET /users/{username}/packages": {
parameters: Endpoints["GET /users/{username}/packages"]["parameters"];
response: Endpoints["GET /users/{username}/packages"]["response"];
};
/**
* @see https://docs.github.com/rest/reference/projects#list-user-projects
*/
"GET /users/{username}/projects": {
parameters: Endpoints["GET /users/{username}/projects"]["parameters"];
@ -1357,7 +1588,7 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /users/{username}/received_events/public"]["response"];
};
/**
* @see https://docs.github.com/v3/repos/#list-repositories-for-a-user
* @see https://docs.github.com/rest/reference/repos#list-repositories-for-a-user
*/
"GET /users/{username}/repos": {
parameters: Endpoints["GET /users/{username}/repos"]["parameters"];
@ -1378,3 +1609,4 @@ export interface PaginatingEndpoints {
response: Endpoints["GET /users/{username}/subscriptions"]["response"];
};
}
export declare const paginatingEndpoints: (keyof PaginatingEndpoints)[];

View File

@ -1,7 +1,9 @@
import { Octokit } from "@octokit/core";
import { PaginateInterface } from "./types";
export { PaginateInterface } from "./types";
export { PaginatingEndpoints } from "./types";
export { composePaginateRest } from "./compose-paginate";
export { isPaginatingEndpoint, paginatingEndpoints, } from "./paginating-endpoints";
/**
* @param octokit Octokit instance
* @param options Options passed to Octokit constructor

View File

@ -8,6 +8,13 @@ export declare function iterator(octokit: Octokit, route: Route | RequestInterfa
} | {
value: import("@octokit/types/dist-types/OctokitResponse").OctokitResponse<any, number>;
done?: undefined;
} | {
value: {
status: number;
headers: {};
data: never[];
};
done?: undefined;
}>;
};
};

View File

@ -1,6 +1,7 @@
import { Octokit } from "@octokit/core";
import * as OctokitTypes from "@octokit/types";
export { EndpointOptions, RequestInterface, OctokitResponse, RequestParameters, Route, } from "@octokit/types";
export { PaginatingEndpoints } from "./generated/paginating-endpoints";
import { PaginatingEndpoints } from "./generated/paginating-endpoints";
declare type KnownKeys<T> = Extract<{
[K in keyof T]: string extends K ? never : number extends K ? never : K;
@ -20,22 +21,22 @@ declare type NormalizeResponse<T> = T & {
data: GetResultsType<T>;
};
declare type DataType<T> = "data" extends keyof T ? T["data"] : unknown;
export interface MapFunction<T = unknown, R = unknown> {
(response: OctokitTypes.OctokitResponse<PaginationResults<T>>, done: () => void): R[];
export interface MapFunction<T = OctokitTypes.OctokitResponse<PaginationResults<unknown>>, M = unknown[]> {
(response: T, done: () => void): M;
}
export declare type PaginationResults<T = unknown> = T[];
export interface PaginateInterface {
/**
* Paginate a request using endpoint options and map each response to a custom array
*
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<T, R>(options: OctokitTypes.EndpointOptions, mapFn: MapFunction<T, R>): Promise<PaginationResults<R>>;
<T, M>(options: OctokitTypes.EndpointOptions, mapFn: MapFunction<OctokitTypes.OctokitResponse<PaginationResults<T>>, M[]>): Promise<PaginationResults<M>>;
/**
* Paginate a request using endpoint options
*
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(options: OctokitTypes.EndpointOptions): Promise<PaginationResults<T>>;
/**
@ -44,7 +45,7 @@ export interface PaginateInterface {
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(route: R, mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
<R extends keyof PaginatingEndpoints, M extends unknown[]>(route: R, mapFn: MapFunction<PaginatingEndpoints[R]["response"], M>): Promise<M>;
/**
* Paginate a request using a known endpoint route string and parameters, and map each response to a custom array
*
@ -52,7 +53,7 @@ export interface PaginateInterface {
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
<R extends keyof PaginatingEndpoints, M extends unknown[]>(route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: MapFunction<PaginatingEndpoints[R]["response"], M>): Promise<M>;
/**
* Paginate a request using an known endpoint route string
*
@ -73,7 +74,7 @@ export interface PaginateInterface {
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(request: R, mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
<R extends OctokitTypes.RequestInterface, M extends unknown[]>(request: R, mapFn: MapFunction<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, M>): Promise<M>;
/**
* Paginate a request using an endpoint method, parameters, and a map function
*
@ -81,7 +82,7 @@ export interface PaginateInterface {
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(request: R, parameters: Parameters<R>[0], mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done?: () => void) => MR): Promise<MR>;
<R extends OctokitTypes.RequestInterface, M extends unknown[]>(request: R, parameters: Parameters<R>[0], mapFn: MapFunction<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, M>): Promise<M>;
/**
* Paginate a request using an endpoint method and parameters
*
@ -94,9 +95,9 @@ export interface PaginateInterface {
* Get an async iterator to paginate a request using endpoint options
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(EndpointOptions: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
<T>(options: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a known endpoint route string and optional parameters
*
@ -128,15 +129,15 @@ export interface ComposePaginateInterface {
* Paginate a request using endpoint options and map each response to a custom array
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<T, R>(octokit: Octokit, options: OctokitTypes.EndpointOptions, mapFn: MapFunction<T, R>): Promise<PaginationResults<R>>;
<T, M>(octokit: Octokit, options: OctokitTypes.EndpointOptions, mapFn: MapFunction<OctokitTypes.OctokitResponse<PaginationResults<T>>, M[]>): Promise<PaginationResults<M>>;
/**
* Paginate a request using endpoint options
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(octokit: Octokit, options: OctokitTypes.EndpointOptions): Promise<PaginationResults<T>>;
/**
@ -146,7 +147,7 @@ export interface ComposePaginateInterface {
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(octokit: Octokit, route: R, mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
<R extends keyof PaginatingEndpoints, M extends unknown[]>(octokit: Octokit, route: R, mapFn: MapFunction<PaginatingEndpoints[R]["response"], M>): Promise<M>;
/**
* Paginate a request using a known endpoint route string and parameters, and map each response to a custom array
*
@ -155,7 +156,7 @@ export interface ComposePaginateInterface {
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(octokit: Octokit, route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
<R extends keyof PaginatingEndpoints, M extends unknown[]>(octokit: Octokit, route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: MapFunction<PaginatingEndpoints[R]["response"], M>): Promise<M>;
/**
* Paginate a request using an known endpoint route string
*
@ -179,7 +180,7 @@ export interface ComposePaginateInterface {
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(octokit: Octokit, request: R, mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
<R extends OctokitTypes.RequestInterface, M extends unknown[]>(octokit: Octokit, request: R, mapFn: MapFunction<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, M>): Promise<M>;
/**
* Paginate a request using an endpoint method, parameters, and a map function
*
@ -188,7 +189,7 @@ export interface ComposePaginateInterface {
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(octokit: Octokit, request: R, parameters: Parameters<R>[0], mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done?: () => void) => MR): Promise<MR>;
<R extends OctokitTypes.RequestInterface, M extends unknown[]>(octokit: Octokit, request: R, parameters: Parameters<R>[0], mapFn: MapFunction<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, M>): Promise<M>;
/**
* Paginate a request using an endpoint method and parameters
*
@ -204,9 +205,9 @@ export interface ComposePaginateInterface {
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {object} options Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(octokit: Octokit, EndpointOptions: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
<T>(octokit: Octokit, options: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a known endpoint route string and optional parameters
*

View File

@ -1 +1 @@
export declare const VERSION = "2.6.2";
export declare const VERSION = "2.21.3";

View File

@ -1,4 +1,4 @@
const VERSION = "2.6.2";
const VERSION = "2.21.3";
/**
* Some list response that can be paginated have a different response structure
@ -17,6 +17,13 @@ const VERSION = "2.6.2";
* otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
*/
function normalizePaginatedListResponse(response) {
// endpoints can respond with 204 if repository is empty
if (!response.data) {
return {
...response,
data: [],
};
}
const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
if (!responseNeedsNormalization)
return response;
@ -54,13 +61,27 @@ function iterator(octokit, route, parameters) {
async next() {
if (!url)
return { done: true };
const response = await requestMethod({ method, url, headers });
const normalizedResponse = normalizePaginatedListResponse(response);
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return { value: normalizedResponse };
try {
const response = await requestMethod({ method, url, headers });
const normalizedResponse = normalizePaginatedListResponse(response);
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return { value: normalizedResponse };
}
catch (error) {
if (error.status !== 409)
throw error;
url = "";
return {
value: {
status: 200,
headers: {},
data: [],
},
};
}
},
}),
};
@ -94,6 +115,232 @@ const composePaginateRest = Object.assign(paginate, {
iterator,
});
const paginatingEndpoints = [
"GET /app/hook/deliveries",
"GET /app/installations",
"GET /applications/grants",
"GET /authorizations",
"GET /enterprises/{enterprise}/actions/permissions/organizations",
"GET /enterprises/{enterprise}/actions/runner-groups",
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations",
"GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners",
"GET /enterprises/{enterprise}/actions/runners",
"GET /enterprises/{enterprise}/audit-log",
"GET /enterprises/{enterprise}/secret-scanning/alerts",
"GET /enterprises/{enterprise}/settings/billing/advanced-security",
"GET /events",
"GET /gists",
"GET /gists/public",
"GET /gists/starred",
"GET /gists/{gist_id}/comments",
"GET /gists/{gist_id}/commits",
"GET /gists/{gist_id}/forks",
"GET /installation/repositories",
"GET /issues",
"GET /licenses",
"GET /marketplace_listing/plans",
"GET /marketplace_listing/plans/{plan_id}/accounts",
"GET /marketplace_listing/stubbed/plans",
"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
"GET /networks/{owner}/{repo}/events",
"GET /notifications",
"GET /organizations",
"GET /orgs/{org}/actions/cache/usage-by-repository",
"GET /orgs/{org}/actions/permissions/repositories",
"GET /orgs/{org}/actions/runner-groups",
"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories",
"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners",
"GET /orgs/{org}/actions/runners",
"GET /orgs/{org}/actions/secrets",
"GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
"GET /orgs/{org}/audit-log",
"GET /orgs/{org}/blocks",
"GET /orgs/{org}/code-scanning/alerts",
"GET /orgs/{org}/codespaces",
"GET /orgs/{org}/credential-authorizations",
"GET /orgs/{org}/dependabot/secrets",
"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
"GET /orgs/{org}/events",
"GET /orgs/{org}/external-groups",
"GET /orgs/{org}/failed_invitations",
"GET /orgs/{org}/hooks",
"GET /orgs/{org}/hooks/{hook_id}/deliveries",
"GET /orgs/{org}/installations",
"GET /orgs/{org}/invitations",
"GET /orgs/{org}/invitations/{invitation_id}/teams",
"GET /orgs/{org}/issues",
"GET /orgs/{org}/members",
"GET /orgs/{org}/migrations",
"GET /orgs/{org}/migrations/{migration_id}/repositories",
"GET /orgs/{org}/outside_collaborators",
"GET /orgs/{org}/packages",
"GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
"GET /orgs/{org}/projects",
"GET /orgs/{org}/public_members",
"GET /orgs/{org}/repos",
"GET /orgs/{org}/secret-scanning/alerts",
"GET /orgs/{org}/settings/billing/advanced-security",
"GET /orgs/{org}/team-sync/groups",
"GET /orgs/{org}/teams",
"GET /orgs/{org}/teams/{team_slug}/discussions",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
"GET /orgs/{org}/teams/{team_slug}/invitations",
"GET /orgs/{org}/teams/{team_slug}/members",
"GET /orgs/{org}/teams/{team_slug}/projects",
"GET /orgs/{org}/teams/{team_slug}/repos",
"GET /orgs/{org}/teams/{team_slug}/teams",
"GET /projects/columns/{column_id}/cards",
"GET /projects/{project_id}/collaborators",
"GET /projects/{project_id}/columns",
"GET /repos/{owner}/{repo}/actions/artifacts",
"GET /repos/{owner}/{repo}/actions/caches",
"GET /repos/{owner}/{repo}/actions/runners",
"GET /repos/{owner}/{repo}/actions/runs",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
"GET /repos/{owner}/{repo}/actions/secrets",
"GET /repos/{owner}/{repo}/actions/workflows",
"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
"GET /repos/{owner}/{repo}/assignees",
"GET /repos/{owner}/{repo}/branches",
"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
"GET /repos/{owner}/{repo}/code-scanning/alerts",
"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
"GET /repos/{owner}/{repo}/code-scanning/analyses",
"GET /repos/{owner}/{repo}/codespaces",
"GET /repos/{owner}/{repo}/codespaces/devcontainers",
"GET /repos/{owner}/{repo}/codespaces/secrets",
"GET /repos/{owner}/{repo}/collaborators",
"GET /repos/{owner}/{repo}/comments",
"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/commits",
"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
"GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
"GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
"GET /repos/{owner}/{repo}/commits/{ref}/status",
"GET /repos/{owner}/{repo}/commits/{ref}/statuses",
"GET /repos/{owner}/{repo}/contributors",
"GET /repos/{owner}/{repo}/dependabot/secrets",
"GET /repos/{owner}/{repo}/deployments",
"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
"GET /repos/{owner}/{repo}/environments",
"GET /repos/{owner}/{repo}/events",
"GET /repos/{owner}/{repo}/forks",
"GET /repos/{owner}/{repo}/git/matching-refs/{ref}",
"GET /repos/{owner}/{repo}/hooks",
"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
"GET /repos/{owner}/{repo}/invitations",
"GET /repos/{owner}/{repo}/issues",
"GET /repos/{owner}/{repo}/issues/comments",
"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/issues/events",
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
"GET /repos/{owner}/{repo}/issues/{issue_number}/events",
"GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
"GET /repos/{owner}/{repo}/keys",
"GET /repos/{owner}/{repo}/labels",
"GET /repos/{owner}/{repo}/milestones",
"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
"GET /repos/{owner}/{repo}/notifications",
"GET /repos/{owner}/{repo}/pages/builds",
"GET /repos/{owner}/{repo}/projects",
"GET /repos/{owner}/{repo}/pulls",
"GET /repos/{owner}/{repo}/pulls/comments",
"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
"GET /repos/{owner}/{repo}/releases",
"GET /repos/{owner}/{repo}/releases/{release_id}/assets",
"GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
"GET /repos/{owner}/{repo}/secret-scanning/alerts",
"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
"GET /repos/{owner}/{repo}/stargazers",
"GET /repos/{owner}/{repo}/subscribers",
"GET /repos/{owner}/{repo}/tags",
"GET /repos/{owner}/{repo}/teams",
"GET /repos/{owner}/{repo}/topics",
"GET /repositories",
"GET /repositories/{repository_id}/environments/{environment_name}/secrets",
"GET /search/code",
"GET /search/commits",
"GET /search/issues",
"GET /search/labels",
"GET /search/repositories",
"GET /search/topics",
"GET /search/users",
"GET /teams/{team_id}/discussions",
"GET /teams/{team_id}/discussions/{discussion_number}/comments",
"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
"GET /teams/{team_id}/discussions/{discussion_number}/reactions",
"GET /teams/{team_id}/invitations",
"GET /teams/{team_id}/members",
"GET /teams/{team_id}/projects",
"GET /teams/{team_id}/repos",
"GET /teams/{team_id}/teams",
"GET /user/blocks",
"GET /user/codespaces",
"GET /user/codespaces/secrets",
"GET /user/emails",
"GET /user/followers",
"GET /user/following",
"GET /user/gpg_keys",
"GET /user/installations",
"GET /user/installations/{installation_id}/repositories",
"GET /user/issues",
"GET /user/keys",
"GET /user/marketplace_purchases",
"GET /user/marketplace_purchases/stubbed",
"GET /user/memberships/orgs",
"GET /user/migrations",
"GET /user/migrations/{migration_id}/repositories",
"GET /user/orgs",
"GET /user/packages",
"GET /user/packages/{package_type}/{package_name}/versions",
"GET /user/public_emails",
"GET /user/repos",
"GET /user/repository_invitations",
"GET /user/starred",
"GET /user/subscriptions",
"GET /user/teams",
"GET /users",
"GET /users/{username}/events",
"GET /users/{username}/events/orgs/{org}",
"GET /users/{username}/events/public",
"GET /users/{username}/followers",
"GET /users/{username}/following",
"GET /users/{username}/gists",
"GET /users/{username}/gpg_keys",
"GET /users/{username}/keys",
"GET /users/{username}/orgs",
"GET /users/{username}/packages",
"GET /users/{username}/projects",
"GET /users/{username}/received_events",
"GET /users/{username}/received_events/public",
"GET /users/{username}/repos",
"GET /users/{username}/starred",
"GET /users/{username}/subscriptions",
];
function isPaginatingEndpoint(arg) {
if (typeof arg === "string") {
return paginatingEndpoints.includes(arg);
}
else {
return false;
}
}
/**
* @param octokit Octokit instance
* @param options Options passed to Octokit constructor
@ -107,5 +354,5 @@ function paginateRest(octokit) {
}
paginateRest.VERSION = VERSION;
export { composePaginateRest, paginateRest };
export { composePaginateRest, isPaginatingEndpoint, paginateRest, paginatingEndpoints };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,12 +1,16 @@
{
"name": "@octokit/plugin-paginate-rest",
"description": "Octokit plugin to paginate REST API endpoint responses",
"version": "2.6.2",
"version": "2.21.3",
"license": "MIT",
"files": [
"dist-*/",
"bin/"
],
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"pika": true,
"sideEffects": false,
"keywords": [
@ -15,37 +19,33 @@
"sdk",
"toolkit"
],
"repository": "https://github.com/octokit/plugin-paginate-rest.js",
"repository": "github:octokit/plugin-paginate-rest.js",
"dependencies": {
"@octokit/types": "^6.0.1"
"@octokit/types": "^6.40.0"
},
"peerDependencies": {
"@octokit/core": ">=2"
},
"devDependencies": {
"@octokit/core": "^3.0.0",
"@octokit/plugin-rest-endpoint-methods": "^4.0.0",
"@pika/pack": "^0.5.0",
"@octokit/core": "^4.0.0",
"@octokit/plugin-rest-endpoint-methods": "^6.0.0",
"@pika/pack": "^0.3.7",
"@pika/plugin-build-node": "^0.9.0",
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/fetch-mock": "^7.3.1",
"@types/jest": "^26.0.0",
"@types/node": "^14.0.4",
"@types/jest": "^28.0.0",
"@types/node": "^16.0.0",
"fetch-mock": "^9.0.0",
"jest": "^26.0.1",
"github-openapi-graphql-query": "^2.0.0",
"jest": "^28.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.4",
"semantic-release": "^17.0.0",
"prettier": "2.7.1",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^26.0.0",
"ts-jest": "^28.0.0",
"typescript": "^4.0.2"
},
"publishConfig": {
"access": "public"
},
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"main": "dist-node/index.js",
"module": "dist-web/index.js"
}
}

View File

@ -45,7 +45,7 @@ const MyOctokit = Octokit.plugin(restEndpointMethods);
const octokit = new MyOctokit({ auth: "secret123" });
// https://developer.github.com/v3/users/#get-the-authenticated-user
octokit.users.getAuthenticated();
octokit.rest.users.getAuthenticated();
```
There is one method for each REST API endpoint documented at [https://developer.github.com/v3](https://developer.github.com/v3). All endpoint methods are documented in the [docs/](docs/) folder, e.g. [docs/users/getAuthenticated.md](docs/users/getAuthenticated.md)
@ -63,6 +63,8 @@ type UpdateLabelParameters = RestEndpointMethodTypes["issues"]["updateLabel"]["p
type UpdateLabelResponse = RestEndpointMethodTypes["issues"]["updateLabel"]["response"];
```
In order to get types beyond parameters and responses, check out [`@octokit/openapi-types`](https://github.com/octokit/openapi-types.ts/#readme), which is a direct transpliation from GitHub's official OpenAPI specification.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)

View File

@ -2,10 +2,60 @@
Object.defineProperty(exports, '__esModule', { value: true });
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
const Endpoints = {
actions: {
addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
@ -14,6 +64,7 @@ const Endpoints = {
createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
@ -30,16 +81,20 @@ const Endpoints = {
getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"],
getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],
getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"],
getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"],
getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"],
getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, {
renamed: ["actions", "getGithubActionsPermissionsRepository"]
}],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],
getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
@ -47,6 +102,7 @@ const Endpoints = {
getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"],
listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
@ -62,6 +118,7 @@ const Endpoints = {
listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"],
setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],
setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"],
@ -137,6 +194,7 @@ const Endpoints = {
removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],
resetToken: ["PATCH /applications/{client_id}/token"],
revokeInstallationAccessToken: ["DELETE /installation/token"],
scopeToken: ["POST /applications/{client_id}/token/scoped"],
suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"],
updateWebhookConfigForApp: ["PATCH /app/hook/config"]
@ -163,12 +221,16 @@ const Endpoints = {
update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
},
codeScanning: {
deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],
getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, {
renamedParameters: {
alert_id: "alert_number"
}
}],
getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],
getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],
listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],
uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
@ -245,15 +307,24 @@ const Endpoints = {
getTemplate: ["GET /gitignore/templates/{name}"]
},
interactions: {
getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits"],
getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, {
renamed: ["interactions", "getRestrictionsForAuthenticatedUser"]
}],
removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"],
removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits"],
removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, {
renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"]
}],
setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits"]
setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, {
renamed: ["interactions", "setRestrictionsForAuthenticatedUser"]
}]
},
issues: {
addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
@ -393,6 +464,7 @@ const Endpoints = {
},
orgs: {
blockUser: ["PUT /orgs/{org}/blocks/{username}"],
cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
@ -408,6 +480,7 @@ const Endpoints = {
list: ["GET /organizations"],
listAppInstallations: ["GET /orgs/{org}/installations"],
listBlockedUsers: ["GET /orgs/{org}/blocks"],
listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
listForAuthenticatedUser: ["GET /user/orgs"],
listForUser: ["GET /users/{username}/orgs"],
listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
@ -430,6 +503,31 @@ const Endpoints = {
updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
},
packages: {
deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"],
deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],
deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"]
}],
getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]
}],
getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"],
getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"],
getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"],
getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"],
getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]
},
projects: {
addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", {
mediaType: {
@ -659,7 +757,7 @@ const Endpoints = {
previews: ["squirrel-girl"]
}
}, {
deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://docs.github.com/v3/reactions/#delete-a-reaction-legacy"
deprecated: "octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy"
}],
listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", {
mediaType: {
@ -728,6 +826,7 @@ const Endpoints = {
createForAuthenticatedUser: ["POST /user/repos"],
createFork: ["POST /repos/{owner}/{repo}/forks"],
createInOrg: ["POST /orgs/{org}/repos"],
createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"],
createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
createPagesSite: ["POST /repos/{owner}/{repo}/pages", {
mediaType: {
@ -745,6 +844,7 @@ const Endpoints = {
delete: ["DELETE /repos/{owner}/{repo}"],
deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],
deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
@ -793,6 +893,7 @@ const Endpoints = {
get: ["GET /repos/{owner}/{repo}"],
getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
getAllTopics: ["GET /repos/{owner}/{repo}/topics", {
mediaType: {
@ -820,6 +921,7 @@ const Endpoints = {
getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"],
getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
getPages: ["GET /repos/{owner}/{repo}/pages"],
@ -828,6 +930,7 @@ const Endpoints = {
getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
getReadme: ["GET /repos/{owner}/{repo}/readme"],
getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
@ -889,6 +992,7 @@ const Endpoints = {
removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", {
mediaType: {
previews: ["mercy"]
@ -1030,7 +1134,7 @@ const Endpoints = {
}
};
const VERSION = "4.4.1";
const VERSION = "4.15.1";
function endpointsToMethods(octokit, endpointsMap) {
const newMethods = {};
@ -1113,19 +1217,11 @@ function decorate(octokit, scope, methodName, defaults, decorations) {
return Object.assign(withDecorations, requestWithDefaults);
}
/**
* This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary
* goal is to rebuild @octokit/rest on top of @octokit/core. Once that is
* done, we will remove the registerEndpoints methods and return the methods
* directly as with the other plugins. At that point we will also remove the
* legacy workarounds and deprecations.
*
* See the plan at
* https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1
*/
function restEndpointMethods(octokit) {
return endpointsToMethods(octokit, Endpoints);
const api = endpointsToMethods(octokit, Endpoints);
return _objectSpread2(_objectSpread2({}, api), {}, {
rest: api
});
}
restEndpointMethods.VERSION = VERSION;

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More