### Installation
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/bottleneck/README.md
Instructions on how to install Bottleneck using npm, with examples for both ES modules and CommonJS.
```bash
npm install --save bottleneck
```
```javascript
import Bottleneck from "bottleneck";
// Note: To support older browsers and Node <6.0, you must import the ES5 bundle instead.
var Bottleneck = require("bottleneck/es5");
```
--------------------------------
### Full Example with CDN and Virtual Compiler Host
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@typescript/vfs/README.md
Demonstrates a comprehensive setup using `@typescript/vfs` to create a virtual file system from CDN, initialize a virtual compiler host, and emit compiled files. This example is derived from the TypeScript Sandbox codebase.
```typescript
import ts from "typescript"
import tsvfs from "@typescript/vfs"
import lzstring from "lz-string"
const fsMap = await tsvfs.createDefaultMapFromCDN(compilerOptions, ts.version, true, ts, lzstring)
fsMap.set("index.ts", "// main TypeScript file content")
const system = tsvfs.createSystem(fsMap)
const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts)
const program = ts.createProgram({
rootNames: [...fsMap.keys()],
options: compilerOptions,
host: host.compilerHost,
})
// This will update the fsMap with new files
// for the .d.ts and .js files
program.emit()
// Now I can look at the AST for the .ts file too
const index = program.getSourceFile("index.ts")
```
--------------------------------
### Install process-nextick-args
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/process-nextick-args/readme.md
Install the package using npm.
```bash
npm install --save process-nextick-args
```
--------------------------------
### Basic Mocked Request
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates how to set up a basic mock for a GET request to '/foo' and then make a request to that endpoint, verifying the mocked response.
```APIDOC
## MockPool.intercept()
### Description
Intercepts requests matching the specified criteria and allows defining a mocked response.
### Method
`MockPool.intercept(options)`
### Parameters
#### Path Parameters
- **options** (object) - Required - An object containing the criteria for matching requests.
- **path** (string) - Required - The path to match.
- **method** (string) - Optional - The HTTP method to match (e.g., 'GET', 'POST'). Defaults to 'GET'.
- **headers** (object) - Optional - An object containing headers to match.
- **body** (string | object | Buffer) - Optional - The request body to match.
### Return
`MockInterceptor` - An object that allows defining the mocked response using `reply()`.
#### Example - Basic Mocked Request
```js
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
// MockPool
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
```
--------------------------------
### Example 1 - Dispatch GET request
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/Dispatcher.md
Demonstrates how to dispatch a GET request using the Dispatcher API, including setting headers and handling response events.
```APIDOC
## Example 1 - Dispatch GET request
```js
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const data = []
client.dispatch({
path: '/',
method: 'GET',
headers: {
'x-foo': 'bar'
}
}, {
onConnect: () => {
console.log('Connected!')
},
onError: (error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Data: ${res}`)
client.close()
server.close()
}
})
```
```
--------------------------------
### Mocked Request with Query, Body, Headers, and Trailers
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates a comprehensive mock setup, including matching requests by path with query parameters, HTTP method, request body, and request headers, and defining a response with status code, body, headers, and trailers.
```APIDOC
## MockPool.intercept() with Advanced Options
### Description
Intercepts requests based on a detailed set of criteria including path with query parameters, method, request body, and request headers. It also allows defining a response with custom headers and trailers.
### Method
`MockPool.intercept(options).reply(statusCode, body, responseOptions)`
### Parameters
#### Path Parameters
- **options** (object) - Required - Criteria for matching the request.
- **path** (string) - Required - The full path including query parameters.
- **method** (string) - Required - The HTTP method.
- **body** (string | object | Buffer) - Required - The request body.
- **headers** (object) - Required - Request headers to match.
- **statusCode** (number) - Required - The HTTP status code for the response.
- **body** (string | object | Buffer) - Required - The response body.
- **responseOptions** (object) - Optional - Options for the response.
- **headers** (object) - Response headers.
- **trailers** (object) - Response trailers.
#### Example - Mocked request with query body, request headers and response headers and trailers
```js
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo?hello=there&see=ya',
method: 'POST',
body: 'form1=data1&form2=data2',
headers: {
'User-Agent': 'undici',
Host: 'example.com'
}
}).reply(200, { foo: 'bar' }, {
headers: { 'content-type': 'application/json' },
trailers: { 'Content-MD5': 'test' }
})
const {
statusCode,
headers,
trailers,
body
} = await request('http://localhost:3000/foo?hello=there&see=ya', {
method: 'POST',
body: 'form1=data1&form2=data2',
headers: {
foo: 'bar',
'User-Agent': 'undici',
Host: 'example.com'
}
})
console.log('response received', statusCode) // response received 200
console.log('headers', headers) // { 'content-type': 'application/json' }
for await (const data of body) {
console.log('data', data.toString('utf8')) // '{"foo":"bar"}'
}
console.log('trailers', trailers) // { 'content-md5': 'test' }
```
```
--------------------------------
### Install @bufbuild/protobuf
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@bufbuild/protobuf/README.md
Install the package using npm.
```bash
npm install @bufbuild/protobuf
```
--------------------------------
### Install path-key
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-key/readme.md
Install the package using npm.
```bash
$ npm install path-key
```
--------------------------------
### Install is-fullwidth-code-point
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/is-fullwidth-code-point/readme.md
Install the package using npm.
```bash
$ npm install is-fullwidth-code-point
```
--------------------------------
### Development Commands for Filesize.js
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/filesize/README.md
Install dependencies, start development mode with live reload, build distributions, or check and fix code style.
```bash
npm install # Install dependencies
npm run dev # Development mode with live reload
npm run build # Build distributions
npm run lint # Check code style
npm run lint:fix # Auto-fix linting issues
```
--------------------------------
### Install @azure/core-auth
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@azure/core-auth/README.md
Install the core authentication library using npm.
```bash
npm install @azure/core-auth
```
--------------------------------
### Installation with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/balanced-match/README.md
Install the balanced-match package using npm.
```bash
npm install balanced-match
```
--------------------------------
### Install path-expression-matcher
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-expression-matcher/README.md
Install the package using npm.
```bash
npm install path-expression-matcher
```
--------------------------------
### Install @azure/abort-controller
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@azure/abort-controller/README.md
Install the library using npm.
```bash
npm install @azure/abort-controller
```
--------------------------------
### Install Gulp and Dependencies
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/typescript/README.md
Install Gulp globally and then install project-specific development dependencies using npm ci.
```bash
npm install -g gulp
npm ci
```
--------------------------------
### Install @protobuf-ts/runtime with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@protobuf-ts/runtime/README.md
Use this command to install the runtime library using npm.
```shell
npm install @protobuf-ts/runtime
```
--------------------------------
### Install filesize.js
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/filesize/README.md
Install the filesize.js package using npm.
```bash
npm install filesize
```
--------------------------------
### Installing brace-expansion with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/brace-expansion/README.md
Instructions for installing the brace-expansion package using npm.
```bash
npm install brace-expansion
```
--------------------------------
### Install fast-content-type-parse
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/fast-content-type-parse/README.md
Install the package using npm.
```sh
$ npm install fast-content-type-parse
```
--------------------------------
### Quick Start: Create a ZIP Archive
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/archiver/README.md
This example demonstrates how to create a ZIP archive using Archiver. It includes appending files from streams, strings, buffers, and directories, as well as using glob patterns. Ensure to handle 'close', 'end', and 'error' events.
```javascript
const fs = require('fs');
const archiver = require('archiver');
const output = fs.createWriteStream(__dirname + '/example.zip');
const archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
});
output.on('close', function() {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
output.on('end', function() {
console.log('Data has been drained');
});
archive.on('warning', function(err) {
if (err.code === 'ENOENT') {
// log warning
} else {
// throw error
throw err;
}
});
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
const file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });
archive.append('string cheese!', { name: 'file2.txt' });
const buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });
archive.file('file1.txt', { name: 'file4.txt' });
archive.directory('subdir/', 'new-subdir');
archive.directory('subdir/', false);
archive.glob('file*.txt', {cwd:__dirname});
archive.finalize();
```
--------------------------------
### Install @protobuf-ts/runtime with yarn
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@protobuf-ts/runtime/README.md
Use this command to install the runtime library using yarn.
```shell
yarn add @protobuf-ts/runtime
```
--------------------------------
### Install @actions/http-client
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/core/node_modules/@actions/http-client/README.md
Install the @actions/http-client package using npm.
```bash
npm install @actions/http-client --save
```
--------------------------------
### Install isarray with component
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/isarray/README.md
Install the isarray package using the component package manager.
```bash
$ component install juliangruber/isarray
```
--------------------------------
### Install strip-ansi
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/strip-ansi/readme.md
Install the package using npm.
```bash
$ npm install strip-ansi
```
--------------------------------
### Install string-width
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/string-width/readme.md
Install the string-width package using npm.
```bash
$ npm install string-width
```
--------------------------------
### Install wrap-ansi
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/wrap-ansi/readme.md
Install the wrap-ansi package using npm.
```bash
$ npm install wrap-ansi
```
--------------------------------
### Create Token Auth with Installation or Action Token
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/auth-token/README.md
Use createTokenAuth with an installation access token or a GITHUB_TOKEN from GitHub Actions. The resulting object indicates 'installation' token type.
```javascript
// Installation access token or GitHub Action token
createTokenAuth("ghs_InstallallationOrActionToken00000000");
// {
// type: 'token',
// token: 'ghs_InstallallationOrActionToken00000000',
// tokenType: 'installation'
// }
```
--------------------------------
### Install fast-xml-builder
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/fast-xml-builder/README.md
Install the fast-xml-builder package using npm.
```bash
npm install fast-xml-builder
```
--------------------------------
### Install Binary Module
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/binary/README.markdown
Standard npm installation command for the binary module.
```bash
npm install binary
```
--------------------------------
### Install @nodable/entities
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@nodable/entities/README.md
Install the @nodable/entities package using npm.
```bash
npm install @nodable/entities
```
--------------------------------
### Build Documentation
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/normalize-path/README.md
Install global dependencies and run the 'verb' command to generate the README.md file from its template.
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
--------------------------------
### Get Installation Token with App Authentication
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/core/README.md
Access the `.auth()` method to retrieve an installation token when using app authentication.
```javascript
const { token } = await appOctokit.auth({
type: "installation",
installationId: 123,
});
```
--------------------------------
### Install Debug Utility
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/debug/README.md
Install the debug utility using npm.
```bash
npm install debug
```
--------------------------------
### Quick Start: Basic Path Matching
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-expression-matcher/README.md
Demonstrates creating an Expression and a Matcher to track and match a simple path. Shows how to push path segments and check for a match.
```javascript
import { Expression, Matcher } from 'path-expression-matcher';
// Create expression (parse once, reuse many times)
const expr = new Expression("root.users.user");
// Create matcher (tracks current path)
const matcher = new Matcher();
matcher.push("root");
matcher.push("users");
matcher.push("user", { id: "123" });
// Match current path against expression
if (matcher.matches(expr)) {
console.log("Match found!");
console.log("Current path:", matcher.toString()); // "root.users.user"
}
```
--------------------------------
### Basic Dispatcher Compose Example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/Dispatcher.md
Demonstrates how to compose a custom redirect interceptor with the Undici Client. This example shows a basic setup for handling redirects manually.
```javascript
const { Client, RedirectHandler } = require('undici')
const redirectInterceptor = dispatch => {
return (opts, handler) => {
const { maxRedirections } = opts
if (!maxRedirections) {
return dispatch(opts, handler)
}
const redirectHandler = new RedirectHandler(
dispatch,
maxRedirections,
opts,
handler
)
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
return dispatch(opts, redirectHandler)
}
}
const client = new Client('http://localhost:3000')
.compose(redirectInterceptor)
await client.request({ path: '/', method: 'GET' })
```
--------------------------------
### Install Chainsaw via npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/chainsaw/README.markdown
Install the chainsaw module using npm.
```bash
npm install chainsaw
```
--------------------------------
### Installation with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/event-target-shim/README.md
Install the event-target-shim library using npm. This is the recommended method for use with bundlers.
```bash
npm install event-target-shim
```
--------------------------------
### Install Dependencies
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/core/node_modules/@actions/http-client/README.md
Install project dependencies using npm.
```bash
npm install
```
--------------------------------
### Basic GET Request with Undici
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/README.md
Perform a GET request to a specified URL and process the response. This example demonstrates how to access status codes, headers, trailers, and the response body.
```javascript
import { request } from 'undici'
const {
statusCode,
headers,
trailers,
body
} = await request('http://localhost:3000/foo')
console.log('response received', statusCode)
console.log('headers', headers)
for await (const data of body) { console.log('data', data) }
console.log('trailers', trailers)
```
--------------------------------
### Quick Start: Namespace Support
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/path-expression-matcher/README.md
Illustrates how to use namespaces in path expressions and track them with the Matcher. Shows the resulting string representation with namespaces.
```javascript
// Namespace support
const nsExpr = new Expression("soap::Envelope.soap::Body..ns::UserId");
matcher.push("Envelope", null, "soap");
matcher.push("Body", null, "soap");
matcher.push("UserId", null, "ns");
console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:UserId"
```
--------------------------------
### Use fast-xml-parser as a CLI command
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/fast-xml-parser/README.md
Example of using the installed fast-xml-parser as a command-line interface tool.
```bash
$ fxparser some.xml
```
--------------------------------
### MockPool request example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates how to use `MockPool.request` to make a mocked HTTP request. It sets up a MockAgent and a MockPool, intercepts a GET request to '/foo' on 'http://localhost:3000', and configures it to reply with a 200 status and 'foo' as the body. The example then makes the request and logs the status code and the body content.
```javascript
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET',
}).reply(200, 'foo')
const {
statusCode,
body
} = await mockPool.request({
origin: 'http://localhost:3000',
path: '/foo',
method: 'GET'
})
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
--------------------------------
### Install Redis Client
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/bottleneck/README.md
Install either the `redis` or `ioredis` package to enable Bottleneck's clustering functionality.
```bash
# NodeRedis (https://github.com/NodeRedis/node_redis)
npm install --save redis
# or ioredis (https://github.com/luin/ioredis)
npm install --save ioredis
```
--------------------------------
### Get enabled scopes for OAuth tokens
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/auth-token/README.md
Retrieve the scopes enabled for a given token. This method does not work for installation tokens.
```javascript
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("HEAD /");
const scopes = response.headers["x-oauth-scopes"].split(/,\s+/);
if (scopes.length) {
console.log(
`"${TOKEN}" has ${scopes.length} scopes enabled: ${scopes.join(", ")}`,
);
} else {
console.log(`"${TOKEN}" has no scopes enabled`);
}
```
--------------------------------
### Initializing the Octokit Client
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/github/README.md
Demonstrates how to get an authenticated Octokit client using a GitHub token. It also shows how to pass additional options like a user agent.
```APIDOC
## Initializing the Octokit Client
### Description
Get an authenticated Octokit client to interact with the GitHub API. This client is pre-configured to follow proxy settings and GHES base URLs.
### Usage
```javascript
import * as github from '@actions/github';
import * as core from '@actions/core';
async function run() {
const myToken = core.getInput('myToken');
const octokit = github.getOctokit(myToken);
// You can also pass in additional options as a second parameter to getOctokit
// const octokit = github.getOctokit(myToken, {userAgent: "MyActionVersion1"});
// ... your code here using the octokit client
}
run();
```
### Parameters
- `token` (string) - A GitHub token with appropriate permissions.
- `options` (object, optional) - Additional configuration options for the Octokit client, such as `userAgent`.
```
--------------------------------
### Get repository permissions for a token
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/auth-token/README.md
Retrieve the permissions enabled for a specific repository using a token. Note that the 'permissions' key is not set when using an installation access token.
```javascript
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const authentication = await auth();
const response = await request("GET /repos/{owner}/{repo}", {
owner: "octocat",
repo: "hello-world",
});
console.log(response.data.permissions);
// {
// admin: true,
// push: true,
// pull: true
// }
```
--------------------------------
### Find and Load package.json in ESM
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/package-json-from-dist/README.md
Use `findPackageJson` to get the path and `loadPackageJson` to read the package.json content. This example assumes ESM module system and a standard 'dist' build output.
```typescript
import {
findPackageJson,
loadPackageJson,
} from 'package-json-from-dist'
const pj = findPackageJson(import.meta.url)
console.log(`package.json found at ${pj}`)
const pkg = loadPackageJson(import.meta.url)
console.log(`Hello from ${pkg.name}@${pkg.version}`)
```
--------------------------------
### List organization repositories (Alternative Options)
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/request/README.md
Demonstrates an alternative way to make the same request by passing 'method' and 'url' as part of the options object instead of as the first argument.
```javascript
const result = await request({
method: "GET",
url: "/orgs/{org}/repos",
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
});
```
--------------------------------
### Get Match Indices with balanced.range
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/minimatch/node_modules/balanced-match/README.md
The `balanced.range` function returns an array containing the start and end indices of the first non-nested matching pair of strings. If no match is found, it returns `undefined`.
```javascript
import { balanced } from 'balanced-match'
// Example usage for balanced.range (assuming it's imported or available)
// const r = balanced.range('a', 'b', 'preabpost')
// console.log(r) // Output: [3, 5]
```
--------------------------------
### Get Range of First Matching Pair
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/balanced-match/README.md
This function returns the start and end indices of the first non-nested matching pair of delimiters. It's useful when you only need the positions of the matched pair.
```javascript
var balanced = require('balanced-match');
console.log(balanced.range('{', '}', 'pre{in{nested}}post'));
console.log(balanced.range('', '', 'preboldpost'));
```
--------------------------------
### MockClient Request Example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/api/MockClient.md
Demonstrates how to use MockClient to intercept a GET request to '/foo', reply with a 200 status and 'foo' body, and then process the response. Ensure the MockClient is associated with the correct origin and path.
```javascript
import { MockAgent } from 'undici'
const mockAgent = new MockAgent({ connections: 1 })
const mockClient = mockAgent.get('http://localhost:3000')
mockClient.intercept({ path: '/foo' }).reply(200, 'foo')
const {
statusCode,
body
} = await mockClient.request({
origin: 'http://localhost:3000',
path: '/foo',
method: 'GET'
})
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
--------------------------------
### Getting OIDC Token
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@actions/core/README.md
Details how to obtain a JSON Web Token (JWT) ID token from the GitHub OIDC provider. This token can be used to authenticate with third-party cloud providers. It covers the `getIDToken()` method, its optional `audience` input, and provides an example of its usage.
```APIDOC
## 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 {
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'
uns:
using: 'node12'
main: 'dist/index.js'
```
```
--------------------------------
### Client Certificate Authentication Example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/docs/docs/best-practices/client-certificate.md
Demonstrates setting up an HTTPS server that requests client certificates and an Undici client that provides its own certificate for authentication. The server checks the validity of the client certificate and logs the result. The client connects using TLS options including CA, key, cert, and servername.
```javascript
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const { createServer } = require('node:https')
const { Client } = require('undici')
const serverOptions = {
ca: [
readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8')
],
key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'),
cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'),
requestCert: true,
rejectUnauthorized: false
}
const server = createServer(serverOptions, (req, res) => {
// true if client cert is valid
if(req.client.authorized === true) {
console.log('valid')
} else {
console.error(req.client.authorizationError)
}
res.end()
})
server.listen(0, function () {
const tls = {
ca: [
readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8')
],
key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'),
cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'),
rejectUnauthorized: false,
servername: 'agent1'
}
const client = new Client(`https://localhost:${server.address().port}`, {
connect: tls
})
client.request({
path: '/',
method: 'GET'
}, (err, { body }) => {
body.on('data', (buf) => {}) // eslint-disable-line no-unused-vars
body.on('end', () => {
client.close()
server.close()
})
})
})
```
--------------------------------
### Install zip-stream
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/zip-stream/README.md
Install the zip-stream module using npm. You can also install upcoming versions directly from the master branch.
```bash
npm install zip-stream --save
```
```bash
npm install https://github.com/archiverjs/node-zip-stream/archive/master.tar.gz
```
--------------------------------
### Install compress-commons
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/compress-commons/README.md
Install the compress-commons library using npm. You can also install directly from a tarball to test upcoming versions.
```bash
npm install compress-commons --save
```
```bash
npm install https://github.com/archiverjs/node-compress-commons/archive/master.tar.gz
```
--------------------------------
### Install crc-32 using npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/crc-32/README.md
Install the crc-32 package using npm. This command installs the library for use in your project.
```bash
npm install crc-32
```
--------------------------------
### Install color-convert using npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/color-convert/README.md
Shows the command to install the color-convert library using npm.
```bash
$ npm install color-convert
```
--------------------------------
### Install shebang-regex
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/shebang-regex/readme.md
Install the package using npm.
```bash
$ npm install shebang-regex
```
--------------------------------
### REST API Example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/core/README.md
Example of how to instantiate Octokit and make a REST API request.
```APIDOC
## REST API Example
### Description
Example of how to instantiate Octokit and make a REST API request.
### Method
```javascript
const octokit = new Octokit({ auth: `personal-access-token123` });
const response = await octokit.request("GET /orgs/{org}/repos", {
org: "octokit",
type: "private",
});
```
### Notes
See [`@octokit/request`](https://github.com/octokit/request.js) for full documentation of the `.request` method.
```
--------------------------------
### GraphQL API Example
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@octokit/core/README.md
Example of how to instantiate Octokit and make a GraphQL API request.
```APIDOC
## GraphQL API Example
### Description
Example of how to instantiate Octokit and make a GraphQL API request.
### Method
```javascript
const octokit = new Octokit({ auth: `secret123` });
const response = await octokit.graphql(
`query ($login: String!) {
organization(login: $login) {
repositories(privacy: PRIVATE) {
totalCount
}
}
}`,
{ login: "octokit" },
);
```
### Notes
See [`@octokit/graphql`](https://github.com/octokit/graphql.js) for full documentation of the `.graphql` method.
```
--------------------------------
### Basic CLI Layout with cliui
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@isaacs/cliui/README.md
Demonstrates how to create a basic command-line interface layout using cliui, including text, options, and descriptions with wrapping and alignment.
```javascript
const ui = require('cliui')()
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div(
{
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
},
{
text: "the file to load." +
chalk.green("(if this description is long it wraps).")
,
width: 20
},
{
text: chalk.red("[required]"),
align: 'right'
}
)
console.log(ui.toString())
```
--------------------------------
### Install East Asian Width Module
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/eastasianwidth/README.md
Install the module using npm. This is the first step before using its functionalities.
```bash
$ npm install eastasianwidth
```
--------------------------------
### Example Usage: Negated Options and Last Value Wins
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@pkgjs/parseargs/README.md
Demonstrates the output of the `parseArgs` example with various command-line arguments, including negated options and cases where an option is used multiple times.
```console
$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
```
--------------------------------
### Install ansi-styles
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/wrap-ansi-cjs/node_modules/ansi-styles/readme.md
Install the ansi-styles module using npm.
```bash
$ npm install ansi-styles
```
--------------------------------
### Install @protobuf-ts/runtime-rpc with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@protobuf-ts/runtime-rpc/README.md
Use this command to install the package using npm. This is the first step if you plan to create your own RPC transport.
```shell
npm install @protobuf-ts/runtime-rpc
```
--------------------------------
### Install unzip-stream
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/unzip-stream/README.md
Install the unzip-stream package using npm.
```bash
$ npm install unzip-stream
```
--------------------------------
### Install Undici
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/undici/README.md
Install the undici package using npm.
```bash
npm i undici
```
--------------------------------
### Importing the brace-expansion library
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/brace-expansion/README.md
Shows how to import the brace-expansion module using require.
```javascript
var expand = require('brace-expansion');
```
--------------------------------
### Install text-decoder
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/text-decoder/README.md
Install the text-decoder package using npm.
```bash
npm i text-decoder
```
--------------------------------
### Install tar-stream
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/tar-stream/README.md
Install the tar-stream module using npm.
```bash
npm install tar-stream
```
--------------------------------
### Import and Initialize LRUCache
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/lru-cache/README.md
Demonstrates how to import the LRUCache class and initialize it with various options. Ensure at least one of 'max', 'ttl', or 'maxSize' is specified to prevent unbounded storage.
```javascript
// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'
// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does. Most of them can be
// overridden for specific items in get()/set()
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// for use when you need to clean up something when objects
// are evicted from the cache
dispose: (value, key) => {
freeFromMemoryOrWhatever(value)
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
// async method to use for cache.fetch(), for
// stale-while-revalidate type of behavior
fetchMethod: async (
key,
staleValue,
{ options, signal, context }
) => {},
}
const cache = new LRUCache(options)
cache.set('key', 'value')
cache.get('key') // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.clear() // empty the cache
```
--------------------------------
### Install ansi-regex
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/string-width-cjs/node_modules/ansi-regex/readme.md
Install the ansi-regex package using npm.
```bash
$ npm install ansi-regex
```
--------------------------------
### Install fast-xml-parser as a global command-line tool
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/fast-xml-parser/README.md
Install fast-xml-parser globally to use it as a system command.
```bash
$ npm install fast-xml-parser -g
```
--------------------------------
### Basic Brace Expansion Examples
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/brace-expansion/README.md
Demonstrates various ways to use the expand function for different brace expansion patterns.
```javascript
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
```
```javascript
expand('-v{,,}')
// => ['-v', '-v', '-v']
```
```javascript
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
```
```javascript
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
```
```javascript
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
```
```javascript
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
```
```javascript
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
```
```javascript
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
```
```javascript
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
```
```javascript
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
--------------------------------
### Install @protobuf-ts/runtime-rpc with yarn
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/@protobuf-ts/runtime-rpc/README.md
Use this command to install the package using yarn. This is the first step if you plan to create your own RPC transport.
```shell
yarn add @protobuf-ts/runtime-rpc
```
--------------------------------
### Install streamx
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/streamx/README.md
Install the streamx package using npm.
```bash
npm install streamx
```
--------------------------------
### Install shebang-command with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/shebang-command/readme.md
Install the package using npm.
```bash
$ npm install shebang-command
```
--------------------------------
### Install isarray with npm
Source: https://github.com/dawidd6/action-download-artifact/blob/master/node_modules/isarray/README.md
Install the isarray package using npm for use in Node.js projects or for bundling with tools like browserify.
```bash
$ npm install isarray
```