### Initialize Gin Web Server in Go Source: https://github.com/jfrog/frogbot/blob/main/testdata/indirect-projects/go/main.go.txt This snippet shows the basic setup for a Go web server using the Gin framework. Ensure Gin is installed in your Go environment. ```go package main import ( "github.com/gin-gonic/gin" ) func main() { print("test") _ = gin.Default() } ``` -------------------------------- ### Use Token for Git Operations Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Demonstrates how to use both OAuth and installation access tokens for git operations, including prefixing installation tokens with 'x-access-token'. This example uses the 'execa' package. ```javascript const TOKEN = "ghp_PersonalAccessToken01245678900000000"; const auth = createTokenAuth(TOKEN); const { token, tokenType } = await auth(); const tokenWithPrefix = tokenType === "installation" ? `x-access-token:${token}` : token; const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`; const { stdout } = await execa("git", ["push", repositoryUrl]); console.log(stdout); ``` -------------------------------- ### Install @actions/http-client Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/http-client/README.md Install the package using npm. ```bash npm install @actions/http-client --save ``` -------------------------------- ### Check Go Installation Source: https://github.com/jfrog/frogbot/blob/main/CONTRIBUTING.md Verify that Go is installed on your system before proceeding with the build process. ```bash go version ``` -------------------------------- ### REST API Example with @octokit/request Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Demonstrates how to make a GET request to the GitHub REST API to fetch user information. Requires importing the request function. ```javascript import { request } from "@octokit/request"; const { data } = await request("GET /users/{username}", { username: "octokit" }); ``` -------------------------------- ### Install before-after-hook with npm Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/before-after-hook/README.md Install the before-after-hook package using npm. ```bash npm install before-after-hook ``` -------------------------------- ### Install and Import in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Install the @octokit/auth-token package using npm and import the createTokenAuth function. ```js const { createTokenAuth } = require("@octokit/auth-token"); // or: import { createTokenAuth } from "@octokit/auth-token"; ``` -------------------------------- ### Generate documentation Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/is-plain-object/README.md Install global dependencies and run the documentation generation command. ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` -------------------------------- ### GraphQL Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Example of how to make a request to the GitHub GraphQL API using the @octokit/request library. ```APIDOC ## GraphQL Example ### Description Send a POST request to the GraphQL endpoint to query for the authenticated user's login. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **query** (string) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables to use with the GraphQL query. ### Request Example ```javascript import { request } from "@octokit/request"; async function getLogin() { const response = await request("POST /graphql", { headers: { authorization: `token YOUR-GITHUB-TOKEN` }, body: { query: "query { viewer { login } }" } }); console.log(response.data.viewer.login); } getLogin(); ``` ### Response #### Success Response (200) - **data** (Object) - The result of the GraphQL query. #### Response Example ```json { "data": { "viewer": { "login": "octocat" } } } ``` ``` -------------------------------- ### MockAgent: Basic Mocked Request with Global Dispatcher Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockAgent.md This example shows how to set up a basic mocked request using MockAgent. It involves getting a mock pool for a specific origin, intercepting a path, and replying with a status code and body. The MockAgent is then set as the global dispatcher. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) 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 } ``` -------------------------------- ### Basic Pagination Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/plugin-paginate-rest/README.md Instantiate Octokit with the plugin and use the `paginate` method to fetch all issues for a repository. ```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, }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/http-client/README.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Create Token Auth with User-to-Server Installation Token Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Use createTokenAuth with a user authentication for installation token (user-to-server). ```js // Installation access token or GitHub Action token createTokenAuth("ghu_InstallationUserToServer000000000000"); // { // type: 'token', // token: 'ghu_InstallationUserToServer000000000000', // tokenType: 'user-to-server' // } ``` -------------------------------- ### TypeScript Usage Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/graphql/README.md Example of using @octokit/graphql with TypeScript. Ensure you have the necessary types installed. ```typescript import { graphql } from "@octokit/graphql"; async function run() { const query = ` { viewer { login } } `; const token = "YOUR_PERSONAL_ACCESS_TOKEN"; const { viewer } = await graphql<{ viewer: { login: string } }>(query, { headers: { authorization: `token ${token}` } }); console.log(`Hello, ${viewer.login}!`); } run(); ``` -------------------------------- ### Go Main Function Example Source: https://github.com/jfrog/frogbot/blob/main/testdata/projects/go/main.go.txt This is the entry point of a Go program. It includes imports for standard libraries and external packages. ```go package main import ( "fmt" "github.com/google/uuid" "github.com/sassoftware/go-rpmutils" ) func main() { fmt.Println("test") uuid.New() _, _ = rpmutils.ReadRpm(nil) } ``` -------------------------------- ### Run tests Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/is-plain-object/README.md Install dependencies and run the unit tests to verify the package's functionality. ```sh $ npm install && npm test ``` -------------------------------- ### Install and Import Octokit Core in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/core/README.md Install @octokit/core using npm and import the Octokit class for use in Node.js environments. ```javascript const { Octokit } = require("@octokit/core"); // or: import { Octokit } from "@octokit/core"; ``` -------------------------------- ### Usage Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/plugin-rest-endpoint-methods/README.md Demonstrates how to load the plugin and use one of the generated REST API methods. ```APIDOC ## GET /user ### Description Retrieves the authenticated user's information. ### Method GET ### Endpoint /user ### Parameters This endpoint does not require any parameters. ### Request Example ```javascript // Assuming octokit is an instance of Octokit with the restEndpointMethods plugin loaded 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" } ``` ``` -------------------------------- ### Dispatch GET Request with Undici Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Dispatcher.md This example demonstrates how to dispatch a GET request using the Undici Client. It includes setting custom headers and handling various events like connection, headers received, data chunks, and request completion. The server and client are closed upon successful 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() } }) ``` -------------------------------- ### Install debug.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/debug/README.md Install the debug.js package using npm. ```bash $ npm install debug ``` -------------------------------- ### Install node-fetch Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/node-fetch/README.md Install the current stable release (2.x) of node-fetch using npm. ```sh npm install node-fetch ``` -------------------------------- ### Create Token Auth with Installation or GitHub Action Token Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Use createTokenAuth with an installation access token or a GITHUB_TOKEN provided to GitHub Actions. ```js // Installation access token or GitHub Action token createTokenAuth("ghs_InstallallationOrActionToken00000000"); // { // type: 'token', // token: 'ghs_InstallallationOrActionToken00000000', // tokenType: 'installation' // } ``` -------------------------------- ### Example Review Content Source: https://github.com/jfrog/frogbot/blob/main/testdata/messages/reviewcomment/review_comment_fallback_standard.md This snippet shows sample review content that might be included in a comment. ```text some review content ``` -------------------------------- ### Install is-plain-object with npm Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/is-plain-object/README.md Install the package using npm for use in your project. ```sh $ npm install --save is-plain-object ``` -------------------------------- ### MockClient Request Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockClient.md Shows how to use MockClient to intercept a request and receive a mocked response. The example registers a mock response for '/foo' and then makes a request to that path, logging the status code and response body. ```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 semver with npm Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/semver/README.md Install the semver package using npm. This is the first step to using it in your Node.js project. ```bash npm install semver ``` -------------------------------- ### Starting the Node.js HTTP Server Source: https://github.com/jfrog/frogbot/blob/main/testdata/scanpullrequest/expected_response_multi_dir.md Command to start the Node.js HTTP server defined in poc1-server.mjs. This is the first terminal command required to set up the demonstration. ```bash node poc1-server.mjs ``` -------------------------------- ### Node.js Usage with npm Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/plugin-paginate-rest/README.md Install and import the plugin and Octokit core using npm for Node.js environments. ```javascript const { Octokit } = require("@octokit/core"); const { paginateRest, composePaginateRest, } = require("@octokit/plugin-paginate-rest"); ``` -------------------------------- ### Installing and Importing @octokit/request in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Instructions for installing the @octokit/request package via npm and importing the request function in Node.js environments. ```javascript const { request } = require("@octokit/request"); // or: import { request } from "@octokit/request"; ``` -------------------------------- ### Install and Import @octokit/graphql in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/graphql/README.md Install the package using npm and import the graphql function. Supports both CommonJS and ES Module syntax. ```javascript const {graphql} = require("@octokit/graphql"); // or: import { graphql } from "@octokit/graphql"; ``` -------------------------------- ### MockAgent Request Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockAgent.md Shows how to use the MockAgent's `request` method directly to simulate an HTTP request and capture its response details. ```javascript import { MockAgent } from 'undici' const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo' }).reply(200, 'foo') const { statusCode, body } = await mockAgent.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 } ``` -------------------------------- ### GraphQL API Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/core/README.md Example of how to make a GraphQL API request using the octokit.graphql method. This method allows you to execute GraphQL queries. ```APIDOC ## octokit.graphql ### Description Make a request to the GitHub GraphQL API. ### Method `octokit.graphql(query, variables)` ### Parameters - **query** (string) - The GraphQL query string. - **variables** (object) - An object containing variables for the GraphQL query. - **login** (string) - Required - The organization login. ### Request Example ```javascript const octokit = new Octokit({ auth: `secret123` }); const response = await octokit.graphql( `query ($login: String!) { organization(login: $login) { repositories(privacy: PRIVATE) { totalCount } } }`, { login: "octokit" } ); ``` ### Response #### Success Response (200) - **data** (Object) - The result of the GraphQL query. #### Response Example ```json { "data": { "organization": { "repositories": { "totalCount": 100 } } } } ``` ``` -------------------------------- ### Type-Safe Webhook Payload Handling Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/github/README.md Provides an example of how to use TypeScript type definitions from '@octokit/webhooks-definitions' to safely access webhook payload data. Install the package first using 'npm install @octokit/webhooks-definitions'. ```ts 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}`) } ``` -------------------------------- ### Get OAuth Token Scopes Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Retrieve and display the scopes enabled for a given OAuth 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 /", { headers: authentication.headers, }); 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`); } ``` -------------------------------- ### Get Repository Permissions Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/auth-token/README.md Retrieve the permissions enabled for a specific repository. Note that the 'permissions' key is not available when using installation access tokens. ```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', headers: authentication.headers }); console.log(response.data.permissions) // { // admin: true, // push: true, // pull: true // } ``` -------------------------------- ### Load in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/plugin-rest-endpoint-methods/README.md Install the necessary packages using npm and require them for Node.js applications. You can optionally use a compatible module instead of @octokit/core. ```js const { Octokit } = require("@octokit/core"); const { restEndpointMethods, } = require("@octokit/plugin-rest-endpoint-methods"); ``` -------------------------------- ### Make a REST API Request with Octokit Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/core/README.md Example of creating an Octokit instance with authentication and making a GET request to retrieve private repositories for an organization. ```javascript // Create a personal access token at https://github.com/settings/tokens/new?scopes=repo const octokit = new Octokit({ auth: `personal-access-token123` }); const response = await octokit.request("GET /orgs/{org}/repos", { org: "octokit", type: "private", }); ``` -------------------------------- ### Basic Gradle Build Script Setup Source: https://github.com/jfrog/frogbot/blob/main/testdata/projects/gradle/fixedBuildGradleForCompare.txt Standard configuration for a Java application project in Gradle. Includes plugins, main class, group, version, and source compatibility. ```gradle plugins { id 'java' id 'application' } mainClassName = 'com.example.Main' group 'com.example' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 ``` -------------------------------- ### Client Certificate Authentication Example Source: https://github.com/jfrog/frogbot/blob/main/action/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 configure both server and client TLS options, including CA certificates, keys, and certs. The server checks the `authorized` and `authorizationError` properties of the client's certificate. ```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() }) }) }) ``` -------------------------------- ### MockPool request Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockPool.md This example demonstrates how to use `mockPool.request` to make a request to a mocked origin. It intercepts a GET request to '/foo' and replies with a 200 status and 'foo' as the body. The response is then processed to log 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 } ``` -------------------------------- ### Mocked Request with Reply Data Callback Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockPool.md This example shows how to use a callback function within `reply` to dynamically generate the response body based on the incoming request's headers. It intercepts a GET request to '/echo' and echoes a 'message' header from the request in the response. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/echo', method: 'GET', headers: { 'User-Agent': 'undici', Host: 'example.com' } }).reply(200, ({ headers }) => ({ message: headers.get('message') })) const { statusCode, body, headers } = await request('http://localhost:3000', { headers: { message: 'hello world!' } }) 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')) // { "message":"hello world!" } } ``` -------------------------------- ### Mocked request with path callback Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockPool.md This example demonstrates how to mock a GET request to 'http://localhost:3000/foo?foo=bar' using a callback function to match the request path and query parameters. The mock pool is configured to intercept requests that match the specified criteria and reply with a 200 status code and 'foo' as the response body. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' import querystring from 'querystring' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) const mockPool = mockAgent.get('http://localhost:3000') const matchPath = requestPath => { const [pathname, search] = requestPath.split('?') const requestQuery = querystring.parse(search) if (!pathname.startsWith('/foo')) { return false } if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { return false } return true } mockPool.intercept({ path: matchPath, method: 'GET' }).reply(200, 'foo') const result = await request('http://localhost:3000/foo?foo=bar') // Will match and return mocked data ``` -------------------------------- ### Basic HTTP Server with Busboy Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@fastify/busboy/README.md This example demonstrates a basic HTTP server that uses busboy to parse incoming form data, including files and fields. It handles both POST requests for form submission and GET requests to serve the HTML form. Ensure you handle the file stream, even if discarding its contents, to prevent the 'finish' event from being missed. ```javascript const http = require('node:http'); const { inspect } = require('node:util'); const Busboy = require('busboy'); http.createServer(function(req, res) { if (req.method === 'POST') { const busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log('File [' + fieldname + ']: filename: ' + filename); 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('\
\
\
\ Node.js rules!
\
\ '); } }).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! ``` -------------------------------- ### Initialize New Git Repository Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/simple-git/readme.md Initializes a new Git repository, adds all files, commits them, adds a remote origin, and pushes to the master branch. ```javascript simpleGit() .init() .add('./*') .commit('first commit!') .addRemote('origin', 'https://github.com/user/repo.git') .push('origin', 'master'); ``` -------------------------------- ### Install uuid Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/core/node_modules/uuid/README.md Install the uuid package using npm. ```shell npm install uuid ``` -------------------------------- ### Mocked Request with Query, Body, Headers, and Trailers Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockPool.md This comprehensive example demonstrates mocking a POST request with specific query parameters, request body, headers, and configuring a response with status code, JSON body, custom headers, and trailers. It verifies that all aspects of the request and response are correctly handled. ```javascript 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' } ``` -------------------------------- ### Building a Custom Octokit with Plugins and Defaults Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/core/README.md Shows how to create a custom Octokit class with multiple plugins, default options, and authentication strategies. This is useful for specific environments like GitHub Actions. ```javascript const { Octokit } = require("@octokit/core"); const MyActionOctokit = Octokit.plugin( require("@octokit/plugin-paginate-rest").paginateRest, require("@octokit/plugin-throttling").throttling, require("@octokit/plugin-retry").retry ).defaults({ throttle: { onAbuseLimit: (retryAfter, options) => { /* ... */ }, onRateLimit: (retryAfter, options) => { /* ... */ }, }, authStrategy: require("@octokit/auth-action").createActionAuth, userAgent: `my-octokit-action/v1.2.3`, }); const octokit = new MyActionOctokit(); const installations = await octokit.paginate("GET /app/installations"); ``` -------------------------------- ### Configure Simple Git Instance with Options Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/simple-git/readme.md Instantiate simple-git with a configuration object to set options like base directory, binary path, and concurrency. Supports backward compatibility by allowing base directory as the first argument. ```typescript import { simpleGit, SimpleGit, SimpleGitOptions } from 'simple-git'; const options: Partial = { baseDir: process.cwd(), binary: 'git', maxConcurrentProcesses: 6, trimmed: false, }; // when setting all options in a single object const git: SimpleGit = simpleGit(options); // or split out the baseDir, supported for backward compatibility const git: SimpleGit = simpleGit('/some/path', { binary: 'git' }); ``` -------------------------------- ### Client Constructor Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Client.md Instantiates a new Client object. The URL should only contain the protocol, hostname, and port. Options can be provided to configure the client. ```APIDOC ## new Client(url[, options]) ### Description Instantiates a new Client object. ### Parameters * **url** `URL | string` - Should only include the **protocol, hostname, and port**. * **options** `ClientOptions` (optional) ### Returns * `Client` - A new Client instance. ``` -------------------------------- ### Browser Installation for Octokit Endpoint Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/endpoint/README.md Install @octokit/endpoint directly from cdn.skypack.dev for browser usage. ```html ``` -------------------------------- ### Basic Usage in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/debug/README.md Initialize debug for a module and log messages. This example shows how to create a debug instance for 'http' and log application boot messages and server requests. ```javascript var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` -------------------------------- ### Client Connect Event Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Client.md Demonstrates how to listen for and handle the 'connect' event on an Undici Client. This event is emitted when a socket has been created and connected. ```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}`) client.on('connect', (origin) => { console.log(`Connected to ${origin}`) }) try { const { body } = await client.request({ path: '/', method: 'GET' }) body.setEncoding('utf-8') body.on('data', console.log) client.close() server.close() } catch (error) { console.error(error) client.close() server.close() } ``` -------------------------------- ### Install Undici using npm Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/README.md Install the undici package using npm. This is the primary method for adding undici to your Node.js project. ```bash npm i undici ``` -------------------------------- ### Build Project Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/http-client/README.md Build the project using the npm build script. ```bash npm run build ``` -------------------------------- ### Node.js Installation for Octokit Endpoint Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/endpoint/README.md Install @octokit/endpoint using npm for Node.js environments. Supports both CommonJS and ES module imports. ```javascript const { endpoint } = require("@octokit/endpoint"); // or: import { endpoint } from "@octokit/endpoint"; ``` -------------------------------- ### Release New Version with standard-version Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/core/node_modules/uuid/CONTRIBUTING.md Automate version bumping and changelog generation for releases. Use --dry-run to preview changes before a full release. ```shell npm run release -- --dry-run # verify output manually ``` ```shell npm run release # follow the instructions from the output of this command ``` -------------------------------- ### Instantiate MockClient with MockAgent Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/MockClient.md Demonstrates how to instantiate a MockClient using MockAgent. Ensure connections are set to 1 to obtain a MockClient instance. This client is ready to intercept requests once registered as the agent and mock requests are defined. ```javascript import { MockAgent } from 'undici' // Connections must be set to 1 to return a MockClient instance const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') ``` -------------------------------- ### Client.connect(options[, callback]) Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Client.md Connects the client to the origin. See `Dispatcher.connect` for details. ```APIDOC ## Client.connect(options[, callback]) ### Description Connects the client to the origin. See `Dispatcher.connect` for details. ### Method `connect(options[, callback])` ``` -------------------------------- ### Install and Import deprecation in Node.js Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/deprecation/README.md Install the deprecation module using npm and import the Deprecation class. It supports both CommonJS and ES module syntax. ```javascript const { Deprecation } = require("deprecation"); // or: import { Deprecation } from "deprecation"; ``` -------------------------------- ### Client.upgrade(options[, callback]) Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Client.md Initiates an upgrade request. See `Dispatcher.upgrade` for details. ```APIDOC ## Client.upgrade(options[, callback]) ### Description Initiates an upgrade request. See `Dispatcher.upgrade` for details. ### Method `upgrade(options[, callback])` ``` -------------------------------- ### Add labels to an issue example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Example of adding labels to a GitHub issue using the @octokit/request library. This demonstrates specifying media type previews. ```APIDOC ## POST /repos/{owner}/{repo}/issues/{number}/labels ### Description Adds labels to an issue. ### Method POST ### Endpoint /repos/{owner}/{repo}/issues/{number}/labels ### Parameters #### Path Parameters - **owner** (string) - Required - The account owner of the repository. - **repo** (string) - Required - The name of the repository. - **number** (integer) - Required - The number of the issue. #### Query Parameters None #### Request Body - **labels** (array of strings) - Required - An array of label names to add to the issue. ### Request Example ```js request("POST /repos/{owner}/{repo}/issues/{number}/labels", { mediaType: { previews: ["symmetra"], }, owner: "octokit", repo: "request.js", number: 1, labels: ["🐛 bug"], }); ``` ### Response #### Success Response (200 or 201) - **(No specific fields documented in source, typically returns the labels applied)** #### Response Example (Not provided in source) ``` -------------------------------- ### GraphQL API Request Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Example of making a GraphQL API request to count private repositories for an organization. It shows how to structure the query and variables. ```APIDOC ## POST /graphql ### Description Executes a GraphQL query against the GitHub API. ### Method POST ### Endpoint /graphql ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - A JSON object containing variables for the 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 } } } } ``` ``` -------------------------------- ### REST API Request Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Example of making a REST API request to list organization repositories. It demonstrates how to pass authentication headers and 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 kind of repositories to return. Possible values are `all`, `public`, `private`, `forks`, `sources`, `member`. #### Request Body None ### Request Example ```js const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); console.log(`${result.data.length} repos found.`); ``` ### Response #### Success Response (200) - **data** (array) - An array of repository objects. #### Response Example ```json { "data": [ { "id": 12345, "name": "repository-name", "full_name": "octokit/repository-name", "private": true // ... other repository fields } ] } ``` ``` -------------------------------- ### REST API Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/core/README.md Example of how to make a REST API request using the octokit.request method. This method allows you to call any GitHub REST API endpoint. ```APIDOC ## octokit.request ### Description Make a request to the GitHub REST API. ### Method `octokit.request(path, options)` ### Parameters - **path** (string) - The API endpoint path, e.g. "GET /orgs/{org}/repos". - **options** (object) - An object containing path parameters, query parameters, and request body. - **org** (string) - Required - The organization name. - **type** (string) - Optional - The type of repositories to retrieve (e.g., "private"). ### Request Example ```javascript const octokit = new Octokit({ auth: `personal-access-token123` }); const response = await octokit.request("GET /orgs/{org}/repos", { org: "octokit", type: "private", }); ``` ### Response #### Success Response (200) - **data** (Array) - A list of repositories. #### Response Example ```json { "data": [ { "id": 12345, "name": "repository-name", "private": true } ] } ``` ``` -------------------------------- ### Dynamically Generating Mock Responses Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/best-practices/mocking-request.md This example shows how to use a function with `reply` to dynamically generate a response based on the incoming request options. The `opts` object contains details about the request, allowing for conditional logic in your mock responses. ```javascript mockPool.intercept({ path: '/bank-transfer', method: 'POST', headers: { 'X-TOKEN-SECRET': 'SuperSecretToken', }, body: JSON.stringify({ recipient: '1234567890', amount: '100' }) }).reply(200, (opts) => { // do something with opts return { message: 'transaction processed' } }) ``` -------------------------------- ### Make GraphQL Request with Octokit Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@actions/github/README.md Demonstrates how to make a GraphQL request using the Octokit client. Requires an initialized Octokit instance. ```js const result = await octokit.graphql(query, variables); ``` -------------------------------- ### Example of Prototype Pollution in Minimist Source: https://github.com/jfrog/frogbot/blob/main/testdata/messages/integration/test_proj_with_vulnerability_standard.md This example demonstrates how prototype pollution can be triggered in the minimist package by parsing crafted arguments. It shows that the 'y' property can be assigned to the constructor's prototype. ```javascript var argv = parse(['--_.concat.constructor.prototype.y', '123']); t.equal((function(){}).foo, undefined); t.equal(argv.y, undefined); ``` -------------------------------- ### semver Command-Line Utility Help Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/semver/README.md Displays the help information for the semver command-line utility, outlining its usage, options for range matching, version incrementing, and loose parsing. ```bash $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] [ [...]] Prints valid versions sorted by SemVer precedence Options: -r --range Print versions that match the specified range. -i --increment [] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` -------------------------------- ### WebIDL Type Declaration Example Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/node-fetch/node_modules/webidl-conversions/README.md Illustrates the equivalent WebIDL operation declaration for the JavaScript function shown in the usage example. This highlights the direct mapping between JavaScript type conversions and WebIDL type specifications. ```webidl void doStuff(boolean x, unsigned long y); ``` -------------------------------- ### REST API Example: List Organization Repositories Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/@octokit/request/README.md Demonstrates how to fetch a list of private repositories for a given organization using the REST API. Ensure to replace the placeholder authorization token. ```javascript // Following GitHub docs formatting: // https://developer.github.com/v3/repos/#list-organization-repositories const result = await request("GET /orgs/{org}/repos", { headers: { authorization: "token 0000000000000000000000000000000000000001", }, org: "octokit", type: "private", }); console.log(`${result.data.length} repos found.`); ``` -------------------------------- ### Basic GET Request with Undici Client Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/undici/docs/api/Dispatcher.md Demonstrates how to perform a basic GET request using the Undici Client and handle the response, including status code, headers, body, and trailers. Ensure the server is listening before making the request. ```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}`) try { const { body, headers, statusCode, trailers } = await client.request({ path: '/', method: 'GET' }) console.log(`response received ${statusCode}`) console.log('headers', headers) body.setEncoding('utf8') body.on('data', console.log) body.on('end', () => { console.log('trailers', trailers) }) client.close() server.close() } catch (error) { console.error(error) } ``` -------------------------------- ### Update Repo and Restart App on Changes (Chained and Async) Source: https://github.com/jfrog/frogbot/blob/main/action/node_modules/simple-git/readme.md Demonstrates two ways to pull repository updates: using chained commands with exec callbacks and using async/await with optional chaining. Restarts the app if changes are detected. ```javascript // when using a chain simpleGit() .exec(() => console.log('Starting pull...')) .pull((err, update) => { if (update && update.summary.changes) { require('child_process').exec('npm restart'); } }) .exec(() => console.log('pull done.')); // when using async and optional chaining const git = simpleGit(); console.log('Starting pull...'); if ((await git.pull())?.summary.changes) { require('child_process').exec('npm restart'); } console.log('pull done.'); ```