### Set up Repository Locally Source: https://github.com/octokit/octokit.js/blob/main/CONTRIBUTING.md Clone the repository, navigate to the directory, and install dependencies. This is the initial setup for local development. ```shell git clone https://github.com//.git cd npm install ``` -------------------------------- ### Octokit API Client Example Source: https://github.com/octokit/octokit.js/blob/main/README.md Demonstrates how to instantiate the Octokit client and make a request to the REST API to get the authenticated user's information. ```APIDOC ## Octokit API Client **Example**: Get the username for the authenticated user. ```js // Create a personal access token at https://github.com/settings/tokens/new?scopes=repo const octokit = new Octokit({ auth: `personal-access-token123` }); // Compare: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user const { data: { login }, } = await octokit.rest.users.getAuthenticated(); console.log("Hello, %s", login); ``` ``` -------------------------------- ### Get Installation Octokit Client Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Use `getInstallationOctokit` to obtain an Octokit instance authenticated for a specific app installation. This is useful for making API requests on behalf of that installation. Ensure the App is initialized with your `appId` and `privateKey`. ```javascript const app = new App({ appId, privateKey }); // Get authenticated client for a specific installation const octokit = await app.getInstallationOctokit(12345); // Make authenticated requests as the app installation const { data } = await octokit.rest.repos.listForAuthenticatedUser(); // Create an issue in any repo the app is installed on await octokit.rest.issues.create({ owner: 'myorg', repo: 'myrepo', title: 'Issue from GitHub App', body: 'Created by the app' }); ``` -------------------------------- ### Dispatch Repository Event with App Client Source: https://github.com/octokit/octokit.js/blob/main/README.md Use the `App` client to dispatch repository events. This example iterates through all repositories the app is installed on and dispatches a custom event. ```javascript import { App } from "octokit"; const app = new App({ appId, privateKey }); for await (const { octokit, repository } of app.eachRepository.iterator()) { // https://docs.github.com/en/rest/reference/repos#create-a-repository-dispatch-event await octokit.rest.repos.createDispatchEvent({ owner: repository.owner.login, repo: repository.name, event_type: "my_event", client_payload: { foo: "bar", }, }); console.log("Event dispatched for %s", repository.full_name); } ``` -------------------------------- ### Get Installation Authenticated Octokit Instance Source: https://github.com/octokit/octokit.js/blob/main/README.md Obtain an `octokit` instance authenticated as a specific installation using the `App` client. Replace `123` with the actual installation ID. ```javascript const octokit = await app.getInstallationOctokit(123); ``` -------------------------------- ### App Instance Usage Example Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to use the App instance type in a function. Ensures type safety when passing an App client. ```typescript function registerWebhooks(app: App) { app.webhooks.on('issues.opened', ({ octokit, payload }) => { console.log(`Issue #${payload.issue.number} opened`); }); } const app = new App({ appId, privateKey }); registerWebhooks(app); ``` -------------------------------- ### Authenticate as GitHub App Installation Source: https://github.com/octokit/octokit.js/blob/main/README.md Use `createAppAuth` to authenticate as a GitHub App installation. Provide your `appId`, `privateKey`, and `installationId` in the `auth` option. ```javascript import { createAppAuth } from "@octokit/auth-app"; const octokit = new Octokit({ authStrategy: createAppAuth, auth: { appId: 1, privateKey: "-----BEGIN PRIVATE KEY----- ...", installationId: 123, }, }); // authenticates as app based on request URLs const { data: { slug }, } = await octokit.rest.apps.getAuthenticated(); // creates an installation access token as needed // assumes that installationId 123 belongs to @octocat, otherwise the request will fail await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello world from " + slug, }); ``` -------------------------------- ### Iterate Over Repositories Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Use `eachRepository.iterator()` to create an async iterator that processes each repository the app is installed on. For each repository, you get an Octokit instance authenticated for that installation and the repository's metadata. This is useful for performing actions across multiple repositories. ```javascript const app = new App({ appId, privateKey }); // Process all repositories for await (const { octokit, repository } of app.eachRepository.iterator()) { console.log(`Processing ${repository.full_name}`); // Create a dispatch event in each repo await octokit.rest.repos.createDispatchEvent({ owner: repository.owner.login, repo: repository.name, event_type: 'my_event', client_payload: { foo: 'bar' } }); } ``` -------------------------------- ### Import Octokit for Node.js Source: https://github.com/octokit/octokit.js/blob/main/README.md Install octokit using npm/pnpm/yarn and import the Octokit and App clients for Node.js environments. ```javascript import { Octokit, App } from "octokit"; ``` -------------------------------- ### Create a Gist After Token Creation Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Example of handling the 'token.created' event to perform an action as the authenticated user, such as creating a gist. ```javascript app.oauth.on('token.created', async ({ token, octokit }) => { // Create a gist as the user await octokit.rest.gists.create({ description: 'Created via OAuthApp', public: true, files: { 'example.js': { content: '// Hello from OAuthApp' } } }); }); ``` -------------------------------- ### Initialize App with Webhook Configuration Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Example of initializing a new Octokit App with webhook configuration, including the app ID, private key, and webhook secret. ```javascript const app = new App({ appId: 12345, privateKey: process.env.PRIVATE_KEY, webhooks: { secret: process.env.WEBHOOK_SECRET } }); ``` -------------------------------- ### Run Tests Locally Source: https://github.com/octokit/octokit.js/blob/main/CONTRIBUTING.md Execute the test suite to ensure the local setup is functioning correctly before making changes. ```shell npm test ``` -------------------------------- ### Create OAuth App Server with Default Scopes Source: https://github.com/octokit/octokit.js/blob/main/README.md Set up an OAuth App server with default scopes. This example demonstrates creating a gist after a user token is obtained. Requires client ID and secret. ```javascript import { createServer } from "node:http"; import { OAuthApp, createNodeMiddleware } from "octokit"; const app = new OAuthApp({ clientId, clientSecret, defaultScopes: ["repo", "gist"], }); app.oauth.on("token", async ({ token, octokit }) => { await octokit.rest.gists.create({ description: "I created this gist using Octokit!", public: true, files: { "example.js": `/* some code here */`, }, }); }); // Your app can receive the OAuth redirect at /api/github/oauth/callback // Users can initiate the OAuth web flow by opening /api/oauth/login createServer(createNodeMiddleware(app)).listen(3000); ``` -------------------------------- ### Octokit Instance Usage Example Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to use the Octokit instance type in a function. Ensures type safety when passing an Octokit client. ```typescript function processRepository(octokit: Octokit) { return octokit.rest.repos.get({ owner: 'octokit', repo: 'octokit.js' }); } const octokit = new Octokit({ auth: 'token' }); processRepository(octokit); ``` -------------------------------- ### getInstallationOctokit(installationId) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Retrieves an Octokit instance authenticated for a specific app installation, allowing for app-level API requests. ```APIDOC ## getInstallationOctokit(installationId) ### Description Get an Octokit instance authenticated for a specific app installation. ### Method Signature ```typescript getInstallationOctokit(installationId: number): Promise ``` ### Parameters #### Path Parameters - **installationId** (number) - Required - The installation ID of the target app installation. ### Returns Promise resolving to an Octokit instance authenticated with an installation access token valid for that installation's repositories. ### Throws Rejects if the installation ID is invalid or the app is not installed on that installation. ### Example ```javascript const app = new App({ appId, privateKey }); // Get authenticated client for a specific installation const octokit = await app.getInstallationOctokit(12345); // Make authenticated requests as the app installation const { data } = await octokit.rest.repos.listForAuthenticatedUser(); // Create an issue in any repo the app is installed on await octokit.rest.issues.create({ owner: 'myorg', repo: 'myrepo', title: 'Issue from GitHub App', body: 'Created by the app' }); ``` ``` -------------------------------- ### Handle Device Flow Verification Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Example of using the `createToken` method for the device flow, providing an `onVerification` callback to display instructions to the user. ```javascript const { token, octokit } = await app.oauth.createToken({ async onVerification(verification) { console.log( `Open ${verification.verification_uri}`, `and enter code: ${verification.user_code}` ); } }); console.log(`Device authenticated!`); ``` -------------------------------- ### Authenticate using App SDK Source: https://github.com/octokit/octokit.js/blob/main/README.md Use the `App` SDK for authentication. Obtain an authenticated `octokit` instance for a specific installation. ```javascript const app = new App({ appId, privateKey }); const { data: slug } = await app.octokit.rest.apps.getAuthenticated(); const octokit = await app.getInstallationOctokit(123); await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello world from " + slug, }); ``` -------------------------------- ### Example JSON response for validating OAuth token (200 OK) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Successful response when checking the validity of an access token via the `/api/github/oauth/token` GET endpoint. ```json { "access_token": "ghu_xxx...", "expires_at": "2024-07-06T12:00:00Z", "refresh_token": "ghr_xxx...", "token_type": "bearer", "scope": "repo,user:email" } ``` -------------------------------- ### OAuthApp Instance Usage Example Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to use the OAuthApp instance type in a function. Ensures type safety when passing an OAuth App client. ```typescript function startOAuthFlow(app: OAuthApp): string { return app.oauth.oauthLoginUrl({ state: randomState(), scopes: ['repo'] }); } const oauthApp = new OAuthApp({ clientId, clientSecret }); const loginUrl = startOAuthFlow(oauthApp); ``` -------------------------------- ### Basic REST API Usage with Octokit.js Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/INDEX.md Demonstrates how to authenticate with a token and make basic REST API calls to get the authenticated user and create an issue. ```javascript import { Octokit } from 'octokit'; const octokit = new Octokit({ auth: 'token123' }); // Get authenticated user const { data: user } = await octokit.rest.users.getAuthenticated(); console.log(`Logged in as ${user.login}`); // Create an issue await octokit.rest.issues.create({ owner: 'octokit', repo: 'octokit.js', title: 'Hello, world!', body: 'Created with octokit' }); ``` -------------------------------- ### Initialize App with OAuth Configuration Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Example of initializing a new Octokit App with OAuth configuration, including app ID, private key, OAuth client ID, client secret, scopes, and signup allowance. ```javascript const app = new App({ appId: 12345, privateKey: process.env.PRIVATE_KEY, oauth: { clientId: process.env.OAUTH_CLIENT_ID, clientSecret: process.env.OAUTH_CLIENT_SECRET, scopes: ['repo', 'gist'], allowSignup: true } }); ``` -------------------------------- ### Get Authenticated User Login with GraphQL Source: https://github.com/octokit/octokit.js/blob/main/README.md Use `octokit.graphql` to query the GraphQL API. This example retrieves the login of the currently authenticated user. ```javascript const { viewer: { login } } = await octokit.graphql(`{ viewer { login } }`); ``` -------------------------------- ### Install Pull Request Locally Source: https://github.com/octokit/octokit.js/blob/main/CONTRIBUTING.md Install a specific pull request from a GitHub repository to test changes locally. Replace `[PULL REQUEST NUMBER]` with the actual pull request number. ```shell npm install https://github.pika.dev/octokit//pr/[PULL REQUEST NUMBER] ``` -------------------------------- ### Initialize Octokit and Get Authenticated User Source: https://github.com/octokit/octokit.js/blob/main/README.md Create an Octokit client instance with a personal access token and use it to fetch the authenticated user's login. Ensure your token has the necessary scopes. ```javascript // Create a personal access token at https://github.com/settings/tokens/new?scopes=repo const octokit = new Octokit({ auth: `personal-access-token123` }); // Compare: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user const { data: { login }, } = await octokit.rest.users.getAuthenticated(); console.log("Hello, %s", login); ``` -------------------------------- ### eachRepository.iterator() Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Creates an async iterator to process each repository the app is installed on, providing an authenticated Octokit instance and repository metadata for each. ```APIDOC ## eachRepository.iterator() ### Description Create an async iterator to process each repository the app is installed on. ### Method Signature ```typescript eachRepository.iterator(): AsyncIterator<{octokit: Octokit, repository: Repository}> ``` ### Returns Async iterator yielding objects with: - `octokit` — Octokit instance authenticated for that installation - `repository` — Repository metadata object with `owner`, `name`, `full_name`, etc. ### Example ```javascript const app = new App({ appId, privateKey }); // Process all repositories for await (const { octokit, repository } of app.eachRepository.iterator()) { console.log(`Processing ${repository.full_name}`); // Create a dispatch event in each repo await octokit.rest.repos.createDispatchEvent({ owner: repository.owner.login, repo: repository.name, event_type: 'my_event', client_payload: { foo: 'bar' } }); } ``` ``` -------------------------------- ### Register a Push Webhook Handler Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Register a handler for the 'push' event. This example logs the ref that was pushed to. ```javascript app.webhooks.on('push', async ({ payload }) => { console.log(`Pushed to ${payload.ref}`); }); ``` -------------------------------- ### Browser example for exchanging OAuth code for token Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md This JavaScript code demonstrates how a browser client can fetch an access token by sending the authorization code and state received from GitHub. ```javascript const code = new URL(location.href).searchParams.get('code'); const state = new URL(location.href).searchParams.get('state'); const response = await fetch('/api/github/oauth/token', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, state }) }); const { access_token } = await response.json(); // Use token for authenticated requests ``` -------------------------------- ### Custom Throttle Handlers Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Example of implementing custom functions for `onRateLimit` and `onSecondaryRateLimit` to control retry behavior. ```javascript const octokit = new Octokit({ auth: 'token', throttle: { onRateLimit: (retryAfter, options, octokit) => { console.error( `Rate limit exceeded for ${options.method} ${options.url}. ` + `Retry after ${retryAfter} seconds.` ); // Don't retry automatically return false; }, onSecondaryRateLimit: (retryAfter, options, octokit) => { // Always retry on secondary rate limit console.log(`Secondary rate limit hit. Waiting ${retryAfter} seconds.`); return true; } } }); ``` -------------------------------- ### Create Label with Schema Preview Source: https://github.com/octokit/octokit.js/blob/main/README.md Enable schema previews using the `mediaType` option in `octokit.graphql`. This example demonstrates creating a label with the 'bane' preview enabled. ```javascript await octokit.graphql( `mutation createLabel($repositoryId:ID!,name:String!,color:String!) { createLabel(input:{repositoryId:$repositoryId,name:$name}) { label: { id } } }`, { repositoryId: 1, name: "important", color: "cc0000", mediaType: { previews: ["bane"], }, }, ); ``` -------------------------------- ### Handle OAuth Token Creation Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Example of how to register a listener for the 'token' event to persist or process newly created tokens. It logs the user's login name. ```javascript const app = new OAuthApp({ clientId, clientSecret, defaultScopes: ['repo', 'gist'] }); app.oauth.on('token', async ({ token, octokit }) => { // Token created - persist or process it console.log(`Token created for ${octokit.auth.login}`); }); ``` -------------------------------- ### Configure App Authentication Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Authenticate Octokit.js using app authentication with `@octokit/auth-app`. Provide app ID, private key, and installation ID. ```javascript import { createAppAuth } from '@octokit/auth-app'; const octokit = new Octokit({ authStrategy: createAppAuth, auth: { appId: 12345, privateKey: '-----BEGIN PRIVATE KEY-----\n...', installationId: 56789 } }); ``` -------------------------------- ### Example JSON response for OAuth token creation (400/401) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Error response when token exchange fails due to bad credentials or an invalid code. ```json { "message": "Bad credentials or invalid code" } ``` -------------------------------- ### Octokit REST API - Issues Create Source: https://github.com/octokit/octokit.js/blob/main/README.md Example of creating an issue in a GitHub repository using the octokit.rest.issues.create method. ```APIDOC ## octokit.rest.issues.create ### Description Creates an issue in a GitHub repository. ### Method POST ### Endpoint /repos/{owner}/{repo}/issues ### Parameters #### Path Parameters - **owner** (string) - Required - The account owner of the repository. The name is not case sensitive. - **repo** (string) - Required - The name of the repository. The name is not case sensitive. #### Request Body - **title** (string) - Required - The title of the issue. - **body** (string) - Optional - The contents of the issue. ### Request Example ```json { "owner": "octocat", "repo": "hello-world", "title": "Hello, world!", "body": "I created this issue using Octokit!" } ``` ### Response #### Success Response (201) - **url** (string) - The URL of the issue. - **html_url** (string) - The HTML URL of the issue. - **number** (integer) - The issue number. - **title** (string) - The title of the issue. - **body** (string) - The body of the issue. #### Response Example ```json { "url": "https://api.github.com/repos/octocat/hello-world/issues/1", "html_url": "https://github.com/octocat/hello-world/issues/1", "number": 1, "title": "Hello, world!", "body": "I created this issue using Octokit!" } ``` ``` -------------------------------- ### Example JSON response for OAuth token creation (200 OK) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Successful response when exchanging an authorization code for an access token, containing the access token and related details. ```json { "access_token": "ghu_xxx...", "expires_at": "2024-07-06T12:00:00Z", "refresh_token": "ghr_xxx...", "refresh_token_expires_at": "2024-08-05T12:00:00Z", "token_type": "bearer", "scope": "repo,user:email" } ``` -------------------------------- ### OAuth App Authentication Flow Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/INDEX.md Demonstrates the setup for an OAuth App, including generating a login URL and exchanging an authorization code for an access token. ```javascript import { OAuthApp } from 'octokit'; const app = new OAuthApp({ clientId: 'lv1.1234567890abcdef', clientSecret: 'secret', defaultScopes: ['repo'] }); app.oauth.on('token.created', async ({ token, octokit }) => { console.log(`User authenticated`); }); // Generate login URL const loginUrl = app.oauth.oauthLoginUrl({ state: randomString() }); // Exchange code for token const { token, octokit } = await app.oauth.createToken({ code: authCode }); ``` -------------------------------- ### Enable Credential Caching for App Instance Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Configure an App instance to cache installation credentials by default. This can be further customized with a specific credential cache implementation. ```javascript const app = new App({ appId: 12345, privateKey: 'key', cacheCredentialsByLogin: true, // Enable caching (default) credentialCache: customCacheInstance // Optional custom cache }); ``` -------------------------------- ### GraphQL Query with PageInfoBackward Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to include the `pageInfo` field with `hasPreviousPage` and `startCursor` in a GraphQL query for backward pagination using `octokit.graphql.paginate()`. ```javascript const { repository } = await octokit.graphql.paginate(` query($owner: String!, $repo: String!, $cursor: String) { repository(owner: $owner, name: $repo) { issues(last: 100, before: $cursor) { nodes { ... } pageInfo { hasPreviousPage startCursor } } } } `); ``` -------------------------------- ### Example curl for GitHub Webhooks Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Use this curl command to test your webhook endpoint by sending a POST request with necessary headers and a sample JSON payload. ```bash curl -X POST http://localhost:3000/api/github/webhooks \ -H "Content-Type: application/json" \ -H "X-GitHub-Event: issues" \ -H "X-GitHub-Delivery: 12345-67890" \ -H "X-Hub-Signature-256: sha256=abc123..." \ -d '{"action":"opened","issue":{"number":1},...}' ``` -------------------------------- ### GraphQL Query with PageInfoForward Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to include the `pageInfo` field with `hasNextPage` and `endCursor` in a GraphQL query for forward pagination using `octokit.graphql.paginate()`. ```javascript const { repository } = await octokit.graphql.paginate(` query($owner: String!, $repo: String!, $cursor: String) { repository(owner: $owner, name: $repo) { issues(first: 100, after: $cursor) { nodes { ... } pageInfo { hasNextPage endCursor } } } } `); ``` -------------------------------- ### Example JSON response for refreshing OAuth token (200 OK) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Successful response when refreshing an access token, providing a new access token and potentially a new refresh token. ```json { "access_token": "ghu_new...", "expires_at": "2024-08-06T12:00:00Z", "refresh_token": "ghr_new...", "refresh_token_expires_at": "2024-09-05T12:00:00Z", "token_type": "bearer", "scope": "repo" } ``` -------------------------------- ### Octokit Configuration with Custom Fetch (Proxy Support) Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Configure Octokit to use a custom fetch implementation, such as one that supports proxy agents. This example uses `undici` for proxy support. ```javascript import { fetch as undiciFetch, ProxyAgent } from 'undici'; const myFetch = (url, options) => { return undiciFetch(url, { ...options, dispatcher: new ProxyAgent('http://proxy.example.com:8080') }); }; const octokit = new Octokit({ auth: 'token', request: { fetch: myFetch } }); ``` -------------------------------- ### Octokit Configuration with Abort Signal Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/configuration.md Configure Octokit to use an AbortController signal for canceling requests. The example demonstrates aborting a request after a delay. ```javascript const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); const octokit = new Octokit({ auth: 'token', request: { signal: controller.signal } }); try { await octokit.request('GET /user'); } catch (error) { if (error.name === 'AbortError') { console.log('Request aborted'); } } ``` -------------------------------- ### Initiate GitHub OAuth Login Source: https://github.com/octokit/octokit.js/blob/main/README.md Redirects the user to GitHub's authorization endpoint to start the OAuth flow. Supports optional state and scopes. ```APIDOC ## GET /api/github/oauth/login ### Description Redirects to GitHub's authorization endpoint. Accepts optional `?state` and `?scopes` query parameters. `?scopes` is a comma-separated list of supported OAuth scope names. ### Method GET ### Endpoint /api/github/oauth/login ### Query Parameters - **state** (string) - Optional - The state parameter for the OAuth flow. - **scopes** (string) - Optional - A comma-separated list of supported OAuth scope names. ``` -------------------------------- ### Provide Custom Fetch Implementation for Proxy Support Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/octokit-class.md Supply a custom fetch function to Octokit's constructor via `request.fetch` to enable advanced networking scenarios like proxy support. This example uses `undici` and `ProxyAgent` for proxy configuration. ```javascript import { fetch as undiciFetch, ProxyAgent } from 'undici'; const myFetch = (url, options) => { return undiciFetch(url, { ...options, dispatcher: new ProxyAgent('http://proxy.example.com:8080') }); }; const octokit = new Octokit({ auth: 'token123', request: { fetch: myFetch } }); ``` -------------------------------- ### Instantiate OAuthApp Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Create a new OAuthApp instance using your application's client ID, client secret, and optionally default scopes or redirect URL. This setup is for traditional OAuth applications. ```javascript import { OAuthApp } from 'octokit'; const app = new OAuthApp({ clientId: 'lv1.1234567890abcdef', clientSecret: 'secret-from-github-settings', defaultScopes: ['repo', 'gist'] }); ``` -------------------------------- ### Handle 'token.created' OAuth Event Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Example of registering a handler for the 'token.created' event to log the new token and perform actions as the authenticated user. Ensure the 'token' and 'octokit' objects are correctly destructured. ```javascript app.oauth.on('token.created', async ({ token, octokit }) => { console.log(`User token created: ${token.access_token}`); // Watch the repo as the authenticated user await octokit.rest.activity.setRepoSubscription({ owner: 'octokit', repo: 'octokit.js', subscribed: true }); }); ``` -------------------------------- ### Octokit REST API - Apps Get Authenticated Source: https://github.com/octokit/octokit.js/blob/main/README.md Example of getting authenticated user information using octokit.rest.apps.getAuthenticated. ```APIDOC ## octokit.rest.apps.getAuthenticated ### Description Gets the authenticated GitHub App. ### Method GET ### Endpoint /app ### Parameters No parameters required. ### Response #### Success Response (200) - **slug** (string) - The slug of the GitHub App. #### Response Example ```json { "slug": "my-github-app" } ``` ``` -------------------------------- ### Configure Base URL for GitHub Enterprise Server Source: https://github.com/octokit/octokit.js/blob/main/README.md When using with GitHub Enterprise Server, set `options.baseUrl` to the root URL of the API. This example shows how to configure it for an Acme Inc. instance. ```javascript const octokit = new Octokit({ baseUrl: "https://github.acme-inc.com/api/v3", }); ``` -------------------------------- ### Node.js http.createServer() with Octokit Middleware Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Use Octokit.js middleware with Node.js's built-in http.createServer() to handle GitHub webhooks. This approach is suitable for simpler server setups without external frameworks. ```javascript import { createServer } from 'http'; import { App, createNodeMiddleware } from 'octokit'; const octokitApp = new App({ appId: 12345, privateKey: 'private-key-here', webhooks: { secret: 'webhook-secret' }, oauth: { clientId: 'lv1.1234567890abcdef', clientSecret: 'oauth-secret' } }); octokitApp.webhooks.on('push', async ({ octokit, payload }) => { console.log(`Pushed to ${payload.ref}`); }); const middleware = createNodeMiddleware(octokitApp); const server = createServer(middleware); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); }); ``` -------------------------------- ### Instantiate App Class Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Creates a new App instance with GitHub App credentials and optional webhook/OAuth configuration. Ensure your private key is in PEM format. ```javascript import { App } from 'octokit'; const app = new App({ appId: 12345, privateKey: `-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----`, webhooks: { secret: 'your-webhook-secret' }, oauth: { clientId: 'lv1.1234567890abcdef', clientSecret: 'client-secret-here' } }); ``` -------------------------------- ### Create GitHub App Server with Express Source: https://github.com/octokit/octokit.js/blob/main/README.md Use this snippet to initialize an Express server and Octokit App. Ensure you have your `appId`, `privateKey`, `secret`, `clientId`, and `clientSecret` configured. ```javascript import express from "express"; import { App, createNodeMiddleware } from "octokit"; const expressApp = express(); const octokitApp = new App({ appId, privateKey, webhooks: { secret }, oauth: { clientId, clientSecret }, }); expressApp.use(createNodeMiddleware(app)); expressApp.listen(3000, () => { console.log(`Example app listening at http://localhost:3000`); }); ``` -------------------------------- ### Pagination with Octokit.js Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/INDEX.md Illustrates how to fetch all issues for a repository using `octokit.paginate` and how to use an async iterator for memory-efficient pagination. ```javascript // Fetch all issues const allIssues = await octokit.paginate( octokit.rest.issues.listForRepo, { owner: 'octokit', repo: 'octokit.js', per_page: 100 } ); // Or use async iterator for memory efficiency const iterator = octokit.paginate.iterator( octokit.rest.issues.listForRepo, { owner: 'octokit', repo: 'octokit.js' } ); for await (const { data: issues } of iterator) { console.log(issues); } ``` -------------------------------- ### RequestError Usage Example Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/types.md Example of how to catch and handle a RequestError. Checks if an error is an instance of RequestError to access its properties. ```typescript import { RequestError } from 'octokit'; try { await octokit.request('GET /user'); } catch (error) { if (error instanceof RequestError) { console.log(error.status); } } ``` -------------------------------- ### Import Octokit for Browsers Source: https://github.com/octokit/octokit.js/blob/main/README.md Load the Octokit client directly from esm.sh for browser environments. ```html ``` -------------------------------- ### Revert to Default Module Source: https://github.com/octokit/octokit.js/blob/main/CONTRIBUTING.md After testing a pull request, revert to the default module installed from npm. ```shell npm install @octokit/ ``` -------------------------------- ### GET /api/github/oauth/token Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Checks the validity of an access token. Requires authentication via the Authorization header. ```APIDOC ## GET /api/github/oauth/token ### Description Check if an access token is valid. Requires authentication. ### Method GET ### Endpoint /api/github/oauth/token ### Headers - **Authorization** (string) - Required - `token ` ### Response #### Success Response (200 OK) - **access_token** (string) - The access token - **expires_at** (string) - The expiration time of the access token - **refresh_token** (string) - The refresh token - **token_type** (string) - The type of the token (e.g., 'bearer') - **scope** (string) - The granted scopes #### Response Example (200 OK) ```json { "access_token": "ghu_xxx...", "expires_at": "2024-07-06T12:00:00Z", "refresh_token": "ghr_xxx...", "token_type": "bearer", "scope": "repo,user:email" } ``` #### Error Response (401) Indicates that the token is invalid or expired. ``` -------------------------------- ### App Constructor Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Creates a new App instance with GitHub App credentials and optional webhook/OAuth configuration. The App instance provides methods for authenticated API requests, webhook event handling, and OAuth flows. ```APIDOC ## Constructor ```typescript new App(options: AppOptions) ``` ### Description Creates a new App instance with GitHub App credentials and optional webhook/OAuth configuration. The App instance provides methods for authenticated API requests, webhook event handling, and OAuth flows. ### Constructor Options #### Parameters - **appId** (number) - Required - The numeric GitHub App ID from the app's settings page. - **privateKey** (string) - Required - The private key (PEM format) for signing JWTs and requests. Must start with `-----BEGIN PRIVATE KEY-----` or `-----BEGIN RSA PRIVATE KEY-----`. - **oauth** (object) - Optional - OAuth configuration for user authentication flows. Requires `clientId` and `clientSecret` properties. - **webhooks** (object) - Optional - Webhook configuration. Requires `secret` property (webhook secret from app settings). - **Octokit** (class) - Optional - Custom Octokit class to use for API requests. Defaults to the full-featured Octokit with all plugins. - **baseUrl** (string) - Optional - API base URL for GitHub Enterprise Server (e.g., `https://github.acme-inc.com/api/v3`). - **log** (object) - Optional - Logger instance with `warn` and `info` methods. Defaults to console. ### Example ```javascript import { App } from 'octokit'; const app = new App({ appId: 12345, privateKey: `-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----`, webhooks: { secret: 'your-webhook-secret' }, oauth: { clientId: 'lv1.1234567890abcdef', clientSecret: 'client-secret-here' } }); ``` ``` -------------------------------- ### GraphQL Query with Octokit.js Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/INDEX.md Shows how to execute a GraphQL query to fetch the authenticated user's login and their first 10 repositories with stargazer counts. ```javascript const octokit = new Octokit({ auth: 'token123' }); const { viewer } = await octokit.graphql(`{ viewer { login repositories(first: 10) { nodes { name stargazerCount } } } }`); ``` -------------------------------- ### GET /api/github/oauth/login Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/create-node-middleware.md Redirects users to GitHub's OAuth authorization endpoint to initiate the OAuth web flow. ```APIDOC ## GET /api/github/oauth/login ### Description Redirect users to GitHub's OAuth authorization endpoint to start the OAuth web flow. ### Method GET ### Endpoint /api/github/oauth/login ### Parameters #### Query Parameters - **state** (string) - Optional - CSRF protection value to verify on callback - **scopes** (string) - Optional - Comma-separated list of OAuth scopes to request ### Response #### Success Response HTTP 302 redirect to GitHub OAuth authorization URL. ### Example ```html Login with GitHub ``` ``` -------------------------------- ### Octokit.js GraphQL Access Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/README.md Usage details for the GraphQL API, including the `octokit.graphql()` method, pagination, and query examples. ```APIDOC ## GraphQL - `octokit.graphql(query, variables)` usage is documented. - Pagination with `octokit.graphql.paginate()` is supported. - Query examples with variables are provided. - Response type handling is detailed. ``` -------------------------------- ### Complete OAuth Flow with HTTP Server Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Sets up an HTTP server to handle the OAuth login and callback. Redirects users to GitHub for authentication and exchanges the authorization code for an access token upon callback. Requires 'crypto' for state generation. ```javascript import { OAuthApp } from 'octokit'; import { createServer } from 'http'; const app = new OAuthApp({ clientId: 'lv1.your-client-id', clientSecret: 'your-client-secret', defaultScopes: ['repo', 'user:email'] }); // Handle token created event app.oauth.on('token.created', async ({ token, octokit }) => { const { data: user } = await octokit.rest.users.getAuthenticated(); console.log(`${user.login} authenticated successfully`); }); // Create a simple HTTP server const server = createServer(async (req, res) => { if (req.url === '/login') { // Redirect to GitHub OAuth const loginUrl = app.oauth.oauthLoginUrl({ state: require('crypto').randomBytes(16).toString('hex'), scopes: ['repo'] }); res.writeHead(302, { Location: loginUrl }); res.end(); } else if (req.url.startsWith('/callback')) { // Handle OAuth callback const url = new URL(`http://localhost${req.url}`); const code = url.searchParams.get('code'); const state = url.searchParams.get('state'); try { const { token, octokit } = await app.oauth.createToken({ code, state }); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(`Authenticated! Token: ${token.access_token}`); } catch (error) { res.writeHead(401); res.end(`Authentication failed: ${error.message}`); } } else { res.writeHead(404); res.end('Not Found'); } }); server.listen(3000, () => { console.log('OAuth server listening at http://localhost:3000'); console.log('Visit http://localhost:3000/login to authenticate'); }); ``` -------------------------------- ### OAuthApp Constructor Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/oauthapp-class.md Creates a new OAuthApp instance with OAuth application credentials. This is the primary way to initialize the OAuthApp client. ```APIDOC ## Constructor OAuthApp ### Description Creates a new OAuthApp instance with OAuth application credentials. ### Signature ```typescript new OAuthApp(options: OAuthAppOptions) ``` ### Parameters #### Constructor Options - **clientId** (`string`) - Required - The OAuth application's client ID from GitHub Developer Settings. Format: `lv1.xxxxxxxxxxxxxxxx`. - **clientSecret** (`string`) - Required - The OAuth application's client secret from GitHub Developer Settings. - **defaultScopes** (`string[]`) - Optional - Default OAuth scopes to request if not specified in `oauthLoginUrl()`. Example: `['repo', 'gist']`. - **redirectUrl** (`string`) - Optional - Default redirect URL. Must match one of the registered URLs in application settings. - **Octokit** (`class`) - Optional - Custom Octokit class for API requests. Defaults to the full-featured Octokit. - **baseUrl** (`string`) - Optional - API base URL for GitHub Enterprise Server. - **log** (`object`) - Optional - Logger instance with `warn` and `info` methods. ### Example ```javascript import { OAuthApp } from 'octokit'; const app = new OAuthApp({ clientId: 'lv1.1234567890abcdef', clientSecret: 'secret-from-github-settings', defaultScopes: ['repo', 'gist'] }); ``` ``` -------------------------------- ### Octokit Request - Generic POST Request Source: https://github.com/octokit/octokit.js/blob/main/README.md Example of sending a generic POST request to the GitHub API using octokit.request. ```APIDOC ## octokit.request ### Description Sends a generic HTTP request to the GitHub API. Can be used for endpoints not directly exposed by `octokit.rest` or for other domains. ### Method POST ### Endpoint /repos/{owner}/{repo}/issues ### Parameters #### Path Parameters - **owner** (string) - Required - The account owner of the repository. The name is not case sensitive. - **repo** (string) - Required - The name of the repository. The name is not case sensitive. #### Request Body - **title** (string) - Required - The title of the issue. - **body** (string) - Optional - The contents of the issue. ### Request Example ```json { "owner": "octocat", "repo": "hello-world", "title": "Hello, world!", "body": "I created this issue using Octokit!" } ``` ### Response #### Success Response (201) - **url** (string) - The URL of the issue. - **html_url** (string) - The HTML URL of the issue. - **number** (integer) - The issue number. - **title** (string) - The title of the issue. - **body** (string) - The body of the issue. #### Response Example ```json { "url": "https://api.github.com/repos/octocat/hello-world/issues/1", "html_url": "https://github.com/octocat/hello-world/issues/1", "number": 1, "title": "Hello, world!", "body": "I created this issue using Octokit!" } ``` ``` -------------------------------- ### App Client Source: https://github.com/octokit/octokit.js/blob/main/README.md Combines features for GitHub Apps, Webhooks, and OAuth. Provides methods for authenticating as a GitHub App and managing installations. ```APIDOC ## App client The `App` client combines features for GitHub Apps, Webhooks, and OAuth ### GitHub App **Standalone module**: [`@octokit/app`](https://github.com/octokit/app.js/#readme) For integrators, GitHub Apps are a means of authentication and authorization. A GitHub app can be registered on a GitHub user or organization account. A GitHub App registration defines a set of permissions and webhooks events it wants to receive and provides a set of credentials in return. Users can grant access to repositories by installing them. Some API endpoints require the GitHub app to authenticate as itself using a JSON Web Token (JWT). For requests affecting an installation, an installation access token has to be created using the app's credentials and the installation ID. The `App` client takes care of all that for you. Example: Dispatch a repository event in every repository the app is installed on ```js import { App } from "octokit"; const app = new App({ appId, privateKey }); for await (const { octokit, repository } of app.eachRepository.iterator()) { // https://docs.github.com/en/rest/reference/repos#create-a-repository-dispatch-event await octokit.rest.repos.createDispatchEvent({ owner: repository.owner.login, repo: repository.name, event_type: "my_event", client_payload: { foo: "bar", }, }); console.log("Event dispatched for %s", repository.full_name); } ``` Example: Get an `octokit` instance authenticated as an installation ```js const octokit = await app.getInstallationOctokit(123); ``` ``` -------------------------------- ### Octokit.js Configuration Options Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/README.md Reference for all configuration options available for Octokit, App, and OAuthApp constructors, including request options and authentication. ```APIDOC ## Configuration - Octokit options reference table. - App options reference table. - OAuthApp options reference table. - Request timeout configuration. - Throttle/retry customization. - Logger and cache customization. ``` -------------------------------- ### Authentication Strategies Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/octokit-class.md Octokit supports various authentication strategies, including token-based, App authentication, OAuth, and Installation Tokens. The default is `@octokit/auth-token`. ```APIDOC ## Authentication Strategies By default, Octokit uses `@octokit/auth-token` for simple token-based authentication. Other strategies available include: - **App Authentication** — Use `@octokit/auth-app` to authenticate as a GitHub App or App Installation - **OAuth** — Use `@octokit/auth-oauth-user` for user authentication via OAuth - **Installation Tokens** — Request installation-specific access tokens **Example with App Authentication:** ```javascript import { createAppAuth } from '@octokit/auth-app'; const octokit = new Octokit({ authStrategy: createAppAuth, auth: { appId: 123, privateKey: '-----BEGIN PRIVATE KEY-----...', installationId: 456 } }); // Requests are now authenticated as the app installation ``` ``` -------------------------------- ### Import Octokit for Deno Source: https://github.com/octokit/octokit.js/blob/main/README.md Load the Octokit client directly from esm.sh for Deno environments. The `dts` query parameter ensures TypeScript definitions are included. ```typescript import { Octokit, App } from "https://esm.sh/octokit?dts"; ``` -------------------------------- ### Octokit.js Server Integration Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/README.md Guidance on integrating Octokit.js with server environments like Express.js and Node.js http.createServer(). ```APIDOC ## Server Integration - Express.js middleware setup. - Node.js http.createServer() compatibility. - Webhook endpoint routing. - OAuth endpoint documentation. - Custom path prefix support. ``` -------------------------------- ### Register a Pull Request Opened Webhook Handler Source: https://github.com/octokit/octokit.js/blob/main/_autodocs/app-class.md Register a handler for the 'pull_request.opened' event. This example demonstrates logging the pull request number. ```javascript app.webhooks.on('pull_request.opened', async ({ payload }) => { console.log(`New PR #${payload.pull_request.number}`); }); ```