Extendable client for GitHub's REST & GraphQL APIs
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Octokit Core is an extendable TypeScript client library for GitHub's REST & GraphQL APIs. It provides a minimal foundation with a plugin architecture for building comprehensive GitHub API clients with customizable authentication strategies, lifecycle hooks, and extensible functionality.
npm install @octokit/coreimport { Octokit, type OctokitOptions } from "@octokit/core";For CommonJS:
const { Octokit } = require("@octokit/core");Types-only import:
import type { OctokitOptions, OctokitPlugin, Hooks } from "@octokit/core/types";Version import:
import { VERSION } from "@octokit/core";import { Octokit } from "@octokit/core";
// Basic GitHub API client
const octokit = new Octokit({
auth: "github_pat_11ABCDEFG_...", // personal access token
});
// Make REST API requests
const { data: user } = await octokit.request("GET /user");
console.log(`Hello ${user.login}`);
// Make GraphQL requests
const { viewer } = await octokit.graphql(`
query {
viewer {
login
name
}
}
`);
// Use authentication
const userAuth = await octokit.auth();
console.log("Token type:", userAuth.type);Octokit Core is built on several key architectural principles:
plugin() method for adding functionalityCreate Octokit clients with various configuration options.
/**
* Main Octokit client class
*/
class Octokit {
/**
* Create a new Octokit client instance
* @param options - Configuration options for the client
*/
constructor(options?: OctokitOptions);
}Access the package version string.
/**
* Version string of the @octokit/core package
*/
const VERSION: string;Configure and extend the Octokit class with plugins and defaults.
/**
* Version string of the @octokit/core package
*/
static VERSION: string;
/**
* Array of registered plugins
*/
static plugins: OctokitPlugin[];
/**
* Create a new Octokit class with preset default options
* @param defaults - Default options or a function returning default options
* @returns Extended Octokit class with preset defaults
*/
static defaults<S extends Constructor<any>>(
this: S,
defaults: OctokitOptions | Function
): typeof this;
/**
* Extend Octokit class with plugins
* @param newPlugins - One or more plugin functions to attach
* @returns Extended Octokit class with plugin functionality
*/
static plugin<S extends Constructor<any> & { plugins: any[] }, T extends OctokitPlugin[]>(
this: S,
...newPlugins: T
): typeof this & Constructor<UnionToIntersection<ReturnTypeOf<T>>>;Usage Examples:
// Create class with default options
const MyOctokit = Octokit.defaults({
baseUrl: "https://github.company.com/api/v3",
auth: "token",
});
// Create class with plugins
const ExtendedOctokit = Octokit.plugin(restPlugin, paginatePlugin);
const octokit = new ExtendedOctokit({ auth: "token" });Make HTTP requests to GitHub's REST API.
/**
* REST API client from @octokit/request
* Supports all GitHub REST API endpoints
*/
request: typeof request;Usage Examples:
// GET request
const { data: repos } = await octokit.request("GET /user/repos", {
sort: "updated",
per_page: 50,
});
// POST request
const { data: issue } = await octokit.request("POST /repos/{owner}/{repo}/issues", {
owner: "octokit",
repo: "core.js",
title: "New issue",
body: "Issue description",
});
// Request with custom headers
const response = await octokit.request("GET /user", {
headers: {
"X-GitHub-Media-Type": "github.v3+json",
},
});Execute GraphQL queries and mutations against GitHub's GraphQL API.
/**
* GraphQL API client from @octokit/graphql
* Supports GitHub's GraphQL API v4
*/
graphql: typeof graphql;Usage Examples:
// Simple query
const { repository } = await octokit.graphql(`
query($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
description
stargazerCount
}
}
`, {
owner: "octokit",
name: "core.js",
});
// Mutation
const { createIssue } = await octokit.graphql(`
mutation($repositoryId: ID!, $title: String!, $body: String!) {
createIssue(input: {
repositoryId: $repositoryId,
title: $title,
body: $body
}) {
issue {
number
url
}
}
}
`, {
repositoryId: "MDEwOlJlcG9zaXRvcnkxMzc4NDI1MjE=",
title: "New issue",
body: "Created via GraphQL",
});Authenticate requests using various GitHub authentication strategies.
/**
* Authentication method - returns authentication details
* The actual signature depends on the authentication strategy used
*/
auth: (...args: unknown[]) => Promise<unknown>;Usage Examples:
// Get current authentication details
const auth = await octokit.auth();
console.log(auth.type); // "token", "oauth-token", "installation", etc.
// Use with different auth strategies
const octokit = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: 123,
privateKey: "-----BEGIN PRIVATE KEY-----\n...",
installationId: 456,
},
});Configurable logging system for debugging and monitoring.
/**
* Logger instance with configurable methods
*/
log: {
/** Log debug information (no-op by default) */
debug: (message: string, additionalInfo?: object) => any;
/** Log informational messages (no-op by default) */
info: (message: string, additionalInfo?: object) => any;
/** Log warning messages (uses console.warn by default) */
warn: (message: string, additionalInfo?: object) => any;
/** Log error messages (uses console.error by default) */
error: (message: string, additionalInfo?: object) => any;
/** Additional custom log methods */
[key: string]: any;
};Usage Examples:
// Custom logger
const octokit = new Octokit({
log: {
debug: (msg, info) => console.debug(`DEBUG: ${msg}`, info),
info: (msg, info) => console.info(`INFO: ${msg}`, info),
warn: (msg, info) => console.warn(`WARN: ${msg}`, info),
error: (msg, info) => console.error(`ERROR: ${msg}`, info),
},
});
// Default logging
octokit.log.debug("Making request", { endpoint: "/user" });
octokit.log.error("Request failed", { error: "Not found" });Intercept and modify requests and responses using the hook system.
/**
* Hook collection for request lifecycle management
* Uses the before-after-hook library
*/
hook: HookCollection<Hooks>;Usage Examples:
// Add request interceptor
octokit.hook.before("request", async (options) => {
console.log(`Making request to ${options.url}`);
options.headers["x-custom-header"] = "custom-value";
});
// Add response interceptor
octokit.hook.after("request", async (response, options) => {
console.log(`Request completed with status ${response.status}`);
});
// Add error handler
octokit.hook.error("request", async (error, options) => {
console.error(`Request failed: ${error.message}`);
throw error;
});/**
* Configuration options for Octokit constructor
*/
interface OctokitOptions {
/** Authentication strategy constructor (defaults to token auth) */
authStrategy?: any;
/** Authentication configuration (token, app credentials, etc.) */
auth?: any;
/** Custom User-Agent string */
userAgent?: string;
/** GitHub API preview features to enable */
previews?: string[];
/** Base URL for GitHub API (for GitHub Enterprise) */
baseUrl?: string;
/** Custom logger configuration */
log?: {
debug: (message: string) => unknown;
info: (message: string) => unknown;
warn: (message: string) => unknown;
error: (message: string) => unknown;
};
/** Request-specific options */
request?: OctokitTypes.RequestRequestOptions;
/** Timezone header for API requests */
timeZone?: string;
/** Additional custom options */
[option: string]: any;
}/**
* Plugin function signature
* @param octokit - Octokit instance being extended
* @param options - Options passed to the constructor
* @returns Object with methods/properties to add to the instance, or void
*/
type OctokitPlugin = (
octokit: Octokit,
options: OctokitOptions
) => { [key: string]: any } | void;/**
* Hook system type definitions for request lifecycle
*/
type Hooks = {
request: {
Options: Required<OctokitTypes.EndpointDefaults>;
Result: OctokitTypes.OctokitResponse<any>;
Error: RequestError | Error;
};
[key: string]: {
Options: unknown;
Result: unknown;
Error: unknown;
};
};/**
* Constructor function type
*/
type Constructor<T> = new (...args: any[]) => T;
/**
* Any function type
*/
type AnyFunction = (...args: any) => any;
/**
* Extract return type from function or array of functions
*/
type ReturnTypeOf<T extends AnyFunction | AnyFunction[]> =
T extends AnyFunction
? ReturnType<T>
: T extends AnyFunction[]
? // exclude `void` from intersection, see octokit/octokit.js#2115
UnionToIntersection<Exclude<ReturnType<T[number]>, void>>
: never;
/**
* Convert union types to intersection types
*/
type UnionToIntersection<Union> = (
Union extends any ? (argument: Union) => void : never
) extends (argument: infer Intersection) => void
? Intersection
: never;
/**
* Strict version of TypeScript's Omit utility type
*/
type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
/**
* Request parameters type from @octokit/types
*/
type RequestParameters = OctokitTypes.RequestParameters;Octokit Core integrates with @octokit/request-error for consistent error handling:
try {
await octokit.request("GET /repos/nonexistent/repo");
} catch (error) {
if (error.status === 404) {
console.log("Repository not found");
}
console.error("Request failed:", error.message);
}Common error scenarios: