### Get Installation Token Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/core/README.md Obtain an installation access token using the `auth()` method. This is typically used when authenticating as a GitHub App installation. ```javascript const { token } = await appOctokit.auth({ type: "installation", installationId: 123, }); ``` -------------------------------- ### Example 1 - Basic GET stream request Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/undici/docs/docs/api/Dispatcher.md A fundamental example demonstrating how to use `client.stream` to fetch data and write it to a Writable stream, utilizing the `opaque` option to pass data between the factory and the main scope. ```APIDOC #### Example 1 - Basic GET stream request ```js import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' import { Writable } from 'stream' const server = createServer((request, response) => { response.end('Hello, World!') }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) const bufs = [] try { await client.stream({ path: '/', method: 'GET', opaque: { bufs } }, ({ statusCode, headers, opaque: { bufs } }) => { console.log(`response received ${statusCode}`) console.log('headers', headers) return new Writable({ write (chunk, encoding, callback) { bufs.push(chunk) callback() } }) }) console.log(Buffer.concat(bufs).toString('utf-8')) client.close() server.close() } catch (error) { console.error(error) } ``` ``` -------------------------------- ### Build and Install Act from Source Source: https://github.com/nektos/act/blob/master/README.md Follow these steps to build and install Act manually from its source code. Ensure you have Go tools version 1.20 or later installed. ```bash git clone git@github.com:nektos/act.git make test make install ``` -------------------------------- ### Install Act using Bash Script Source: https://github.com/nektos/act/wiki/Installation Installs the latest released version of Act by downloading and executing an installation script from GitHub. ```shell curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash ``` -------------------------------- ### Node.js Server with Busboy Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/@fastify/busboy/README.md This example demonstrates how to set up a basic Node.js HTTP server using Busboy to parse incoming form data, including files and fields. It handles both GET and POST requests. ```javascript var http = require('http'); var fs = require('fs'); var inspect = require('util').inspect; var Busboy = require('../lib'); http.createServer(function(req, res) { if (req.method === 'POST') { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log('File [' + fieldname + '] got ' + file.length + ' bytes'); file.on('data', function(data) { console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); }); file.on('end', function() { console.log('File [' + fieldname + '] Finished'); }); }); busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { console.log('Field [' + fieldname + ']: value: ' + inspect(val)); }); busboy.on('finish', function() { console.log('Done parsing form!'); res.writeHead(303, { Connection: 'close', Location: '/' }); res.end(); }); req.pipe(busboy); } else if (req.method === 'GET') { res.writeHead(200, { Connection: 'close' }); res.end('\n' + '
\n' + '
\n' + '
\n' + 'Node.js rules!\n' + '\n' + '
\n' + ''); } }).listen(8000, function() { console.log('Listening for requests'); }); // Example output: // // Listening for requests // Field [textfield]: value: 'testing! :-)' // Field [selectfield]: value: '9001' // Field [checkfield]: value: 'on' // Done parsing form! ``` -------------------------------- ### Getting Authentication Token Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/core/README.md Demonstrates how to obtain an authentication token using the `.auth()` method, specifying the token type and installation ID. ```APIDOC ## Getting Authentication Token ### Description Retrieves an authentication token using the `.auth()` method, specifying the token type and installation ID. ### Method `auth(options: AuthOptions)` ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js const { token } = await appOctokit.auth({ type: "installation", installationId: 123, }); ``` ### Response #### Success Response (200) - **token** (string) - The obtained authentication token. ``` -------------------------------- ### Install @actions/http-client Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@actions/http-client/README.md Install the @actions/http-client package using npm. ```bash npm install @actions/http-client --save ``` -------------------------------- ### Install before-after-hook Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/before-after-hook/README.md Install the before-after-hook package using npm or download the minified version. ```bash npm install before-after-hook ``` -------------------------------- ### Install fast-content-type-parse Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/fast-content-type-parse/README.md Install the package using npm. ```sh $ npm install fast-content-type-parse ``` -------------------------------- ### Create token auth with Installation or Action token Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/auth-token/README.md Use createTokenAuth with an installation access token or a GitHub Actions token. The resulting authentication object will have 'tokenType' set to 'installation'. ```javascript createTokenAuth("ghs_InstallallationOrActionToken00000000"); // { // type: 'token', // token: 'ghs_InstallallationOrActionToken00000000', // tokenType: 'installation' // } ``` -------------------------------- ### Install and Load in Node.js Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/plugin-rest-endpoint-methods/README.md Install the necessary packages using npm and then require them for Node.js usage. ```javascript const { Octokit } = require("@octokit/core"); const { restEndpointMethods, } = require("@octokit/plugin-rest-endpoint-methods"); ``` -------------------------------- ### Dispatch GET Request with Undici Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/Dispatcher.md Demonstrates how to dispatch a GET request using the Undici Client and handle the response lifecycle with custom callbacks. This example sets up a basic HTTP server, creates an Undici client, and dispatches a request, logging connection, headers, data, and completion events. The client and server are closed upon completion. ```javascript 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() } }) ``` -------------------------------- ### NPM Installation and Usage Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/json-with-bigint/README.md Shows how to install the library using npm and import its functions for use in a Node.js or browser project with ES modules. ```bash npm i json-with-bigint ``` ```javascript import { JSONParse, JSONStringify } from 'json-with-bigint'; const userData = { someBigNumber: 9007199254740992n }; localStorage.setItem('userData', JSONStringify(userData)); const restoredUserData = JSONParse(localStorage.getItem('userData') || ''); ``` -------------------------------- ### Install Dependencies for Contributing Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@actions/http-client/README.md Install project dependencies locally when contributing to the @actions/http-client project. ```bash npm install ``` -------------------------------- ### Global Install Act with Nix Source: https://github.com/nektos/act/wiki/Installation Installs Act globally using the Nix package manager. ```shell nix-env -iA nixpkgs.act ``` -------------------------------- ### Install Act with Scoop Source: https://github.com/nektos/act/wiki/Installation Installs Act on Windows using the Scoop package manager. ```shell scoop install act ``` -------------------------------- ### Install and Import Octokit in Node.js Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/@octokit/core/README.md Install @octokit/core using npm and import it in your Node.js project. ```javascript import { Octokit } from "@octokit/core"; ``` -------------------------------- ### MockPool request example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/MockPool.md Shows how to use MockPool.request to intercept a specific GET request to '/foo' and reply with a 200 status and 'foo' as the body. It then demonstrates making the request and logging the response status and body. ```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 Undici Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/README.md Install the undici package using npm. ```bash npm i undici ``` -------------------------------- ### Example .env/.secrets File Structure Source: https://github.com/nektos/act/wiki/Beginner's-guide This example shows the structure of `.env` or `.secrets` files, using Ruby's `dotenv` gem format. It includes examples for environment variables, multi-line secrets, and JSON strings. ```shell export MY_ENV='value' PRIV_KEY="---\nrandom text\n...---" JSON="{ "name": "value" }" SOME_VAR=SOME_VALUE ``` -------------------------------- ### Install and Import in Node.js Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/before-after-hook/README.md Install the package using npm and import the Hook class for use in Node.js environments. ```js import Hook from "before-after-hook"; ``` -------------------------------- ### Basic Request Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/undici/README.md Make a basic HTTP request and process the response. This example shows how to retrieve status code, headers, trailers, and stream 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) ``` -------------------------------- ### Install ncc CLI Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@vercel/ncc/readme.md Install the ncc command-line interface globally using npm. ```bash npm i -g @vercel/ncc ``` -------------------------------- ### Install Act with Nix Shell Source: https://github.com/nektos/act/wiki/Installation Installs Act temporarily using nix-shell, making it available within the current shell session. ```shell nix-shell -p act ``` -------------------------------- ### GraphQL API Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/request/README.md Example of how to make a GraphQL API request using the request library. It shows how to structure the query and variables. ```APIDOC ## POST /graphql ### Description Sends a GraphQL query to the GitHub GraphQL endpoint. This example queries for the total count of private repositories for an organization. ### Method POST ### Endpoint /graphql ### Parameters #### Headers - **authorization** (string) - Required - Authentication token. #### Request Body - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables to be used in the GraphQL query. ### Request Example ```js const result = await request("POST /graphql", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, query: `query ($login: String!) { organization(login: $login) { repositories(privacy: PRIVATE) { totalCount } } }`, variables: { login: "octokit", }, }); ``` ### Response #### Success Response (200) - **data** (object) - The result of the GraphQL query. #### Response Example ```json { "data": { "organization": { "repositories": { "totalCount": 50 } } } } ``` ``` -------------------------------- ### Install Act with Chocolatey Source: https://github.com/nektos/act/wiki/Installation Installs the Act CLI on Windows using the Chocolatey package manager. ```shell choco install act-cli ``` -------------------------------- ### Install Act with Homebrew Source: https://github.com/nektos/act/wiki/Installation Installs the latest stable version of Act using the Homebrew package manager. ```shell brew install act ``` -------------------------------- ### Install @octokit/endpoint in Node.js Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/endpoint/README.md Install the library using npm for use in Node.js environments. You can also use ES module imports. ```javascript const { endpoint } = require("@octokit/endpoint"); // or: import { endpoint } from "@octokit/endpoint"; ``` -------------------------------- ### Install Act with AUR (yay) Source: https://github.com/nektos/act/wiki/Installation Installs Act from the Arch User Repository (AUR) using the yay helper. ```shell yay -S act ``` -------------------------------- ### Install and Import Octokit Core in Node.js Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/core/README.md Install @octokit/core using npm and import the Octokit class. Supports both CommonJS and ES Module syntax. ```javascript const { Octokit } = require("@octokit/core"); // or: import { Octokit } from "@octokit/core"; ``` -------------------------------- ### REST API Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/request/README.md Example of how to make a REST API request to list organization repositories. It demonstrates passing parameters and authentication headers. ```APIDOC ## GET /orgs/{org}/repos ### Description Lists repositories for an organization. This example shows how to specify the organization and filter by private repositories. ### Method GET ### Endpoint /orgs/{org}/repos ### Parameters #### Path Parameters - **org** (string) - Required - The organization name. #### Query Parameters - **type** (string) - Optional - Filter repositories by type (e.g., 'private'). #### Headers - **authorization** (string) - Required - Authentication token. ### Request Example ```js const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); ``` ### Response #### Success Response (200) - **data** (array) - An array of repository objects. #### Response Example ```json { "data": [ { "id": 12345, "name": "repo-name", "private": true // ... other repository fields } ] } ``` ``` -------------------------------- ### REST API Endpoint Mapping Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/request/README.md Demonstrates how to map GitHub API documentation directly to a request. This example adds labels to an issue. ```javascript request("POST /repos/{owner}/{repo}/issues/{number}/labels", { mediaType: { previews: ["symmetra"], }, owner: "octokit", repo: "request.js", number: 1, labels: ["🐛 bug"], }); ``` -------------------------------- ### Install Act from Homebrew HEAD Source: https://github.com/nektos/act/wiki/Installation Installs the latest version of Act directly from the Homebrew HEAD, which requires a compiler. ```shell brew install act --HEAD ``` -------------------------------- ### REST API Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/@octokit/request/README.md Example of making a REST API request to list organization repositories. It demonstrates how to pass headers, path parameters, and query parameters. ```APIDOC ## GET /orgs/{org}/repos ### Description Lists repositories for an organization. ### Method GET ### Endpoint /orgs/{org}/repos ### Parameters #### Path Parameters - **org** (string) - Required - The organization's login name. #### Query Parameters - **type** (string) - Optional - Specifies the type of repositories to retrieve (e.g., 'private', 'public', 'all'). #### Headers - **authorization** (string) - Required - GitHub token for authentication. ### Request Example ```javascript const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); ``` ### Response #### Success Response (200) - **data** (array) - An array of repository objects. #### Response Example ```json { "data": [ { "id": 123, "name": "repo-name", "full_name": "octokit/repo-name" // ... other repository details } ] } ``` ``` -------------------------------- ### Client Certificate Authentication Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/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. It shows how to access certificate authorization status on the server. ```javascript const { readFileSync } = require('fs') const { join } = require('path') const { createServer } = require('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) => {}) body.on('end', () => { client.close() server.close() }) }) }) ``` -------------------------------- ### REST API Example with Octokit Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/@octokit/core/README.md Example of making a REST API request to get private repositories for an organization using Octokit. Requires a personal access token. ```javascript const octokit = new Octokit({ auth: `personal-access-token123` }); const response = await octokit.request("GET /orgs/{org}/repos", { org: "octokit", type: "private", }); ``` -------------------------------- ### MockPool Request Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/undici/docs/docs/api/MockPool.md Intercepts a GET request to '/foo' and replies with a 200 status and 'foo' body. This example shows how to use `mockPool.request` to make a request and process the response. ```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 } ``` -------------------------------- ### Basic DNS Interceptor Setup Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/undici/docs/docs/api/Dispatcher.md Demonstrates how to set up and use the DNS interceptor with a new Undici client. Replace `...opts` with your desired DNS interceptor configuration. ```javascript const { Client, interceptors } = require("undici"); const { dns } = interceptors; const client = new Agent().compose([ dns({ ...opts }) ]) const response = await client.request({ origin: `http://localhost:3030`, ...requestOpts }) ``` -------------------------------- ### Client Certificate Authentication Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/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. ```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) => {}) body.on('end', () => { client.close() server.close() }) }) }) ``` -------------------------------- ### REST API Request Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/request/README.md Send a GET request to list private repositories for an organization. Requires an authorization token. ```javascript const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); console.log(`${result.data.length} repos found.`); ``` -------------------------------- ### Type Webhook Payloads with TypeScript Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@actions/github/README.md Install '@octokit/webhooks-definitions' to get type definitions for webhook payloads. Cast the payload to the appropriate event type for better type safety. ```typescript import * as core from '@actions/core' import * as github from '@actions/github' import {PushEvent} from '@octokit/webhooks-definitions/schema' if (github.context.eventName === 'push') { const pushPayload = github.context.payload as PushEvent core.info(`The head commit is: ${pushPayload.head_commit}`) } ``` -------------------------------- ### Usage Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/@octokit/plugin-rest-endpoint-methods/README.md Demonstrates how to load the plugin and use one of the generated REST API methods, specifically fetching the authenticated user's information. ```APIDOC ## GET /user ### Description Retrieves the authenticated user's information. ### Method GET ### Endpoint /user ### Parameters This endpoint does not require any path or query parameters. ### Request Example ```javascript const MyOctokit = Octokit.plugin(restEndpointMethods); const octokit = new MyOctokit({ auth: "secret123" }); octokit.rest.users.getAuthenticated(); ``` ### Response #### Success Response (200) - **id** (integer) - The user's unique ID. - **login** (string) - The user's login name. - **name** (string) - The user's display name. #### Response Example ```json { "id": 1, "login": "octocat", "name": "The Octocat" } ``` ``` -------------------------------- ### Merging Endpoint Options with endpoint.merge() Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/@octokit/endpoint/README.md Get defaulted endpoint options without parsing them into request options. This example merges route and options, including custom headers and parameters. ```javascript const myProjectEndpoint = endpoint.defaults({ baseUrl: "https://github-enterprise.acme-inc.com/api/v3", headers: { "user-agent": "myApp/1.2.3", }, org: "my-project", }); myProjectEndpoint.merge("GET /orgs/{org}/repos", { headers: { authorization: `token 0000000000000000000000000000000000000001`, }, org: "my-secret-project", type: "private", }); ``` -------------------------------- ### Mocking Requests with Automatic Content-Length Calculation Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/MockPool.md Shows how to automatically calculate and set the 'Content-Length' header for a mocked response. This example mocks a GET request to '/foo' with a string body. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo', method: 'GET' }).replyContentLength().reply(200, 'foo') const { headers } = await request('http://localhost:3000/foo') console.log('headers', headers) // headers { 'content-length': '3' } ``` -------------------------------- ### Basic Pagination Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/plugin-paginate-rest/README.md Instantiate Octokit with the paginateRest plugin and use `octokit.paginate()` to fetch paginated issues. ```javascript const MyOctokit = Octokit.plugin(paginateRest); const octokit = new MyOctokit({ auth: "secret123" }); // See https://developer.github.com/v3/issues/#list-issues-for-a-repository const issues = await octokit.paginate("GET /repos/{owner}/{repo}/issues", { owner: "octocat", repo: "hello-world", since: "2010-10-01", per_page: 100, }); ``` -------------------------------- ### Retrieve repository permissions Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/@octokit/auth-token/README.md Fetch the permissions for a specific repository by making a GET request to the repository endpoint. Note that the 'permissions' key is not available 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 // } ``` -------------------------------- ### Connect request with echo Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/Dispatcher.md This example demonstrates establishing a connection using HTTP CONNECT and echoing data back to the client. It sets up a server that handles the CONNECT request and then uses the Undici client to connect and send data. ```javascript import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' const server = createServer((request, response) => { throw Error('should never get here') }).listen() server.on('connect', (req, socket, head) => { socket.write('HTTP/1.1 200 Connection established\r\n\r\n') let data = head.toString() socket.on('data', (buf) => { data += buf.toString() }) socket.on('end', () => { socket.end(data) }) }) await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { socket } = await client.connect({ path: '/' }) const wanted = 'Body' let data = '' socket.on('data', d => { data += d }) socket.on('end', () => { console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) client.close() server.close() }) socket.write(wanted) socket.end() } catch (error) { } ``` -------------------------------- ### Basic HTTP Request with Undici Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/undici/README.md Make a basic HTTP GET request to a specified URL and process the response. This example shows how to retrieve status code, 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) ``` -------------------------------- ### Client Constructor Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/Client.md Initializes a new Client instance. The constructor takes a URL and optional options to configure the client's behavior. ```APIDOC ## new Client(url[, options]) ### Description Initializes a new Client instance. ### Parameters * **url** `URL | string` - Should only include the **protocol, hostname, and port**. * **options** `ClientOptions` (optional) ### Returns `Client` ### ClientOptions > ⚠️ Warning: The `H2` support is experimental. * **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. * **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. * **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. * **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. * **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second. * **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. * **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. * **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. * **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. * **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. * **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. * **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. * **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. * **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. * **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. ``` -------------------------------- ### MockClient Request Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/MockClient.md Demonstrates how to use MockClient to intercept a GET request to '/foo' and reply with a 200 status and 'foo' body. The response is then processed to log the status code and body content. ```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 } ``` -------------------------------- ### Install uuid Package Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/uuid/README.md Install the uuid package using npm. ```shell npm install uuid ``` -------------------------------- ### Clone Demo Repository Source: https://github.com/nektos/act/wiki/quickstart/script.txt Clone a sample repository to experiment with GitHub Actions locally. ```bash git clone https://github.com/cplee/github-actions-demo ``` -------------------------------- ### List All Files and Directories Source: https://github.com/nektos/act/wiki/quickstart/script.txt Display all files and directories, ignoring the .git directory. ```bash tree -aI .git ``` -------------------------------- ### List Available Actions Source: https://github.com/nektos/act/wiki/quickstart/script.txt List all available actions within the repository. ```bash act -l ``` -------------------------------- ### Install Act with MacPorts Source: https://github.com/nektos/act/wiki/Installation Installs Act using the MacPorts package manager on macOS. ```shell sudo port install act ``` -------------------------------- ### Client Instantiation Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/Client.md Demonstrates how to instantiate the undici Client. The client will not connect to the origin until a request is queued or `client.connect` is explicitly called. ```APIDOC ## Client Constructor ### Description Instantiates a new `Client` object. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Example - Basic Client instantiation ```javascript 'use strict' import { Client } from 'undici' const client = new Client('http://localhost:3000') ``` ### Example - Custom connector ```javascript 'use strict' import { Client, buildConnector } from 'undici' const connector = buildConnector({ rejectUnauthorized: false }) const client = new Client('https://localhost:3000', { connect (opts, cb) { connector(opts, (err, socket) => { if (err) { cb(err) } else if (/* assertion */) { socket.destroy() cb(new Error('kaboom')) } else { cb(null, socket) } }) } }) ``` ``` -------------------------------- ### Build Act from Source Source: https://github.com/nektos/act/wiki/Installation Compiles Act from its source code using Make. Requires Go toolchain 1.16+. ```shell git clone https://github.com/nektos/act.git cd act/ make build ``` -------------------------------- ### Instantiating EventSource Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/undici/docs/docs/api/EventSource.md Demonstrates how to instantiate the EventSource class and set up an event listener for incoming messages. ```APIDOC ## Instantiating EventSource Undici exports a EventSource class. You can instantiate the EventSource as follows: ### Method ```javascript import { EventSource } from 'undici' const eventSource = new EventSource('http://localhost:3000') eventSource.onmessage = (event) => { console.log(event.data) } ``` ``` -------------------------------- ### Pipeline Echo Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/undici/docs/api/Dispatcher.md Demonstrates using `stream.pipeline` with Undici's dispatcher to pipe data from a Readable stream to a server and back to a Writable stream. ```javascript import { Readable, Writable, PassThrough, pipeline } from 'stream' import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' const server = createServer((request, response) => { request.pipe(response) }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) let res = '' pipeline( new Readable({ read () { this.push(Buffer.from('undici')) this.push(null) } }), client.pipeline({ path: '/', method: 'GET' }, ({ statusCode, headers, body }) => { console.log(`response received ${statusCode}`) console.log('headers', headers) return pipeline(body, new PassThrough(), () => {}) // PassThrough is used here to consume the body stream }), new Writable({ write (chunk, _, callback) { res += chunk.toString() callback() }, final (callback) { console.log(`Response pipelined to writable: ${res}`) callback() } }), error => { if (error) { console.error(error) } client.close() server.close() } ) ``` -------------------------------- ### Undici Headers Object Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/Dispatcher.md An example of how to specify headers as a JavaScript object for an Undici request. ```javascript { 'content-length': '123', 'content-type': 'text/plain', connection: 'keep-alive', host: 'mysite.com', accept: '*/*' } ``` -------------------------------- ### Example - MockClient request Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/undici/docs/api/MockClient.md Shows how to use MockClient to intercept a request and process its response. ```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 } ``` -------------------------------- ### JSONParse Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node20/node_modules/json-with-bigint/README.md Shows a basic example of using JSONParse to deserialize a string containing a BigInt value. ```javascript JSONParse('{"someBigNumber":9007199254740992}') ``` -------------------------------- ### MockClient Request Example Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node12/node_modules/undici/docs/api/MockClient.md An example demonstrating how to use MockClient.request to make a mocked request and process the response. ```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 } ``` -------------------------------- ### Basic Mocked Request with Undici Source: https://github.com/nektos/act/blob/master/pkg/runner/testdata/actions/node16/node_modules/undici/docs/api/MockPool.md Demonstrates how to set up a mock agent and intercept a basic GET request to '/foo' and receive a 200 OK response with a 'foo' body. ```javascript 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 } ```