Comprehensive tooling for working with OpenAPI definitions
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for loading, parsing, and accessing OpenAPI definitions with full OpenAPI 3.0/3.1 support.
Initialize an Oas instance with an OpenAPI definition and optional user context.
/**
* Create a new Oas instance
* @param oas - OpenAPI definition as object or JSON string
* @param user - Optional user information for auth token extraction
*/
constructor(oas: OASDocument | string, user?: User);Usage Examples:
import Oas from "oas";
// From object
const oas = new Oas({
openapi: "3.1.0",
info: { title: "My API", version: "1.0.0" },
paths: {}
});
// From JSON string
const oasFromString = new Oas('{"openapi":"3.1.0","info":{"title":"API","version":"1.0.0"},"paths":{}}');
// With user context
const oasWithUser = new Oas(definition, {
apiKey: "secret-key",
keys: [{ name: "my-app", user: "user123", pass: "pass456" }]
});Force-type a JSON object to an OpenAPI definition for TypeScript compatibility.
/**
* Initialize a new Oas instance with type forcing
* @param oas - OpenAPI definition or untyped JSON object
* @param user - Optional user information for auth token extraction
* @returns New Oas instance
*/
static init(oas: OASDocument | Record<string, unknown>, user?: User): Oas;Usage Examples:
// Type-force an untyped object
const untypedApi = JSON.parse(apiJsonString);
const oas = Oas.init(untypedApi);
// With user context
const oasWithUser = Oas.init(untypedApi, { apiKey: "secret" });Retrieve the OpenAPI specification version of the current definition.
/**
* Get the OpenAPI version string from the definition
* @returns OpenAPI version (e.g., "3.0.3", "3.1.0")
* @throws Error if version cannot be determined
*/
getVersion(): string;Usage Examples:
const version = oas.getVersion(); // "3.1.0"
// Handle version-specific logic
if (version.startsWith("3.1")) {
// OpenAPI 3.1 specific features
console.log("Supports webhooks and JSON Schema draft 2020-12");
}Statically check if an operation object has an operationId defined.
/**
* Check if an operation object has an operationId
* @param schema - Operation object to check
* @returns True if operationId is defined and non-empty
*/
static hasOperationId(schema: OperationObject): boolean;Usage Examples:
const operationSchema = {
summary: "Get user",
operationId: "getUser",
responses: { "200": { description: "Success" } }
};
const hasId = Oas.hasOperationId(operationSchema); // true
const operationWithoutId = {
summary: "List users",
responses: { "200": { description: "Success" } }
};
const hasId2 = Oas.hasOperationId(operationWithoutId); // falseStatically generate an operationId for an operation based on path and method.
/**
* Generate an operationId for an operation
* @param path - API path (e.g., "/users/{id}")
* @param method - HTTP method
* @param schema - Operation object
* @param opts - Generation options
* @returns Generated operationId string
*/
static getOperationId(
path: string,
method: string,
schema: OperationObject,
opts?: OperationIDGeneratorOptions
): string;Usage Examples:
const operationSchema = {
summary: "Get user by ID",
responses: { "200": { description: "User found" } }
};
// Generate camelCase operationId
const operationId = Oas.getOperationId("/users/{id}", "get", operationSchema, {
camelCase: true
}); // "getUsersById"
// Use existing operationId if present
const schemaWithId = {
operationId: "fetchUser",
responses: { "200": { description: "Success" } }
};
const existingId = Oas.getOperationId("/users/{id}", "get", schemaWithId, {
onlyUseExistingOperationIds: true
}); // "fetchUser"Retrieve the complete OpenAPI definition object.
/**
* Get the current OpenAPI definition
* @returns Complete OpenAPI definition object
*/
getDefinition(): OASDocument;Usage Examples:
const definition = oas.getDefinition();
// Access definition properties
console.log(definition.info.title);
console.log(definition.servers?.[0]?.url);
console.log(Object.keys(definition.paths));
// Serialize back to JSON
const jsonString = JSON.stringify(definition, null, 2);Get all paths in the API definition as Operation instances for easy manipulation.
/**
* Get all paths with their operations as Operation instances
* @returns Record of paths to HTTP methods to Operation instances
*/
getPaths(): Record<string, Record<HttpMethods, Operation | Webhook>>;Usage Examples:
const paths = oas.getPaths();
// Iterate through all operations
Object.entries(paths).forEach(([path, operations]) => {
Object.entries(operations).forEach(([method, operation]) => {
console.log(`${method.toUpperCase()} ${path}: ${operation.getSummary()}`);
});
});
// Find all GET operations
const getOperations = Object.entries(paths)
.flatMap(([path, ops]) =>
Object.entries(ops)
.filter(([method]) => method === "get")
.map(([, operation]) => ({ path, operation }))
);Get all webhooks (OpenAPI 3.1 only) as Webhook instances.
/**
* Get all webhooks as Webhook instances (OpenAPI 3.1 only)
* @returns Record of webhook IDs to HTTP methods to Webhook instances
*/
getWebhooks(): Record<string, Record<HttpMethods, Webhook>>;Usage Examples:
const webhooks = oas.getWebhooks();
// Process all webhooks
Object.entries(webhooks).forEach(([webhookId, methods]) => {
Object.entries(methods).forEach(([method, webhook]) => {
console.log(`Webhook ${webhookId} ${method}: ${webhook.getSummary()}`);
});
});Get all tag names from the API definition with optional path fallback.
/**
* Get all tag names that exist in the API definition
* @param setIfMissing - If true, adds path names for operations without tags
* @returns Array of tag names, sorted by definition order
*/
getTags(setIfMissing?: boolean): string[];Usage Examples:
// Get defined tags only
const tags = oas.getTags(); // ["users", "orders", "products"]
// Include paths for untagged operations
const allTags = oas.getTags(true); // ["users", "orders", "/health", "/metrics"]
// Group operations by tag
const operationsByTag = tags.reduce((acc, tag) => {
acc[tag] = Object.values(oas.getPaths())
.flatMap(ops => Object.values(ops))
.filter(op => op.getTags().some(t => t.name === tag));
return acc;
}, {} as Record<string, Operation[]>);The Oas constructor and methods handle various error conditions:
getVersion() throws if openapi field is missing or invalid$ref pointerstry {
const oas = new Oas(invalidJsonString);
} catch (error) {
console.error("Invalid OpenAPI definition:", error.message);
}
try {
const version = oas.getVersion();
} catch (error) {
console.error("Cannot determine OpenAPI version:", error.message);
}Install with Tessl CLI
npx tessl i tessl/npm-oasdocs