CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-openapi3-ts

TypeScript models and utilities for building OpenAPI 3.x specification documents with fluent DSL builder pattern

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

server-management.mddocs/

Server Management

Classes for defining and managing OpenAPI server configurations with variable support and extension capabilities.

Capabilities

Server Class

Implementation class for OpenAPI server objects with fluent variable management.

/**
 * Server implementation class
 */
class Server implements ServerObject {
  url: string;
  description?: string;
  variables: { [v: string]: ServerVariable };
  [k: IExtensionName]: IExtensionType;
  
  /**
   * Create a new server instance
   * @param url - Server URL with optional variables
   * @param desc - Optional server description
   */
  constructor(url: string, desc?: string);
  
  /**
   * Add a server variable
   * @param name - Variable name (used in URL template)
   * @param variable - ServerVariable instance
   */
  addVariable(name: string, variable: ServerVariable): void;
}

Usage Examples:

import { Server, ServerVariable } from "openapi3-ts";

// Basic server
const prodServer = new Server(
  "https://api.example.com/v1",
  "Production server"
);

// Server with variables
const apiServer = new Server(
  "https://{environment}.example.com/{version}",
  "Configurable API server"
);

// Add server variables
apiServer.addVariable("environment", new ServerVariable(
  "prod",
  ["prod", "staging", "dev"],
  "Server environment"
));

apiServer.addVariable("version", new ServerVariable(
  "v1",
  ["v1", "v2"],
  "API version"
));

// Use with OpenAPI builder
import { oas30 } from "openapi3-ts";

const spec = oas30.OpenApiBuilder.create()
  .addServer(prodServer)
  .addServer(apiServer)
  .getSpec();

ServerVariable Class

Implementation class for server variables with enum and default value support.

/**
 * Server variable implementation class
 */
class ServerVariable implements ServerVariableObject {
  enum?: string[] | boolean[] | number[];
  default: string | boolean | number;
  description?: string;
  [k: IExtensionName]: IExtensionType;
  
  /**
   * Create a new server variable
   * @param defaultValue - Default value for the variable
   * @param enums - Optional array of allowed values
   * @param description - Optional variable description
   */
  constructor(
    defaultValue: string | boolean | number,
    enums?: string[] | boolean[] | number[],
    description?: string
  );
}

Usage Examples:

import { ServerVariable } from "openapi3-ts";

// String variable with enum
const environmentVar = new ServerVariable(
  "production",
  ["production", "staging", "development"],
  "Deployment environment"
);

// Numeric variable with range
const portVar = new ServerVariable(
  8080,
  [8080, 8443, 9000],
  "Server port number"
);

// Boolean variable
const tlsVar = new ServerVariable(
  true,
  [true, false],
  "Whether to use TLS"
);

// Variable without enum (any value allowed)
const tenantVar = new ServerVariable(
  "default",
  undefined,
  "Tenant identifier"
);

Server Interface Definitions

Core interfaces that the implementation classes satisfy.

/**
 * Server object interface
 */
interface ServerObject extends ISpecificationExtension {
  url: string;
  description?: string;
  variables?: { [v: string]: ServerVariableObject };
}

/**
 * Server variable object interface
 */
interface ServerVariableObject extends ISpecificationExtension {
  enum?: string[] | boolean[] | number[];
  default: string | boolean | number;
  description?: string;
}

Utility Functions

Helper functions for working with server configurations.

/**
 * Get an extension value from a server object
 * @param obj - Object with potential extensions
 * @param extensionName - Extension name (must start with 'x-')
 * @returns Extension value or undefined
 */
function getExtension(
  obj: ISpecificationExtension | undefined,
  extensionName: string
): any;

/**
 * Add an extension to a server object
 * @param obj - Object to add extension to
 * @param extensionName - Extension name (must start with 'x-')
 * @param extension - Extension value
 */
function addExtension(
  obj: ISpecificationExtension | undefined,
  extensionName: string,
  extension: any
): void;

Complete Examples

Multi-Environment Server Setup

import { oas30, Server, ServerVariable } from "openapi3-ts";

// Create environment-specific servers
const servers = [
  new Server("https://api.production.com", "Production server"),
  new Server("https://api.staging.com", "Staging server"),
  new Server("https://api.dev.com", "Development server")
];

// Create configurable server with variables
const configurableServer = new Server(
  "https://{subdomain}.example.com/{basePath}",
  "Configurable server endpoint"
);

configurableServer.addVariable("subdomain", new ServerVariable(
  "api",
  ["api", "api-v2", "beta-api"],
  "API subdomain"
));

configurableServer.addVariable("basePath", new ServerVariable(
  "v1",
  ["v1", "v2", "beta"],
  "API base path version"
));

// Build OpenAPI spec with servers
const spec = oas30.OpenApiBuilder.create()
  .addTitle("Multi-Environment API")
  .addVersion("1.0.0")
  .addServer(servers[0]) // Production
  .addServer(servers[1]) // Staging  
  .addServer(servers[2]) // Development
  .addServer(configurableServer) // Configurable
  .getSpec();

console.log(JSON.stringify(spec.servers, null, 2));

Server with Custom Extensions

import { Server, ServerVariable, addExtension } from "openapi3-ts";

// Create server with custom extensions
const server = new Server(
  "https://api.example.com",
  "Enhanced API server"
);

// Add custom extensions to server
addExtension(server, "x-rate-limit", {
  requests: 1000,
  window: "1h"
});

addExtension(server, "x-datacenter", "us-east-1");

// Create variable with extensions
const versionVar = new ServerVariable(
  "v1",
  ["v1", "v2", "v3"],
  "API version"
);

addExtension(versionVar, "x-deprecated-versions", ["v1"]);
addExtension(versionVar, "x-beta-versions", ["v3"]);

server.addVariable("version", versionVar);

// Verify extensions
console.log(server["x-rate-limit"]); // { requests: 1000, window: "1h" }
console.log(versionVar["x-deprecated-versions"]); // ["v1"]

Complex Server Configuration

import { oas31, Server, ServerVariable } from "openapi3-ts";

// Create a complex server setup for microservices
const createMicroserviceServer = (serviceName: string) => {
  const server = new Server(
    `https://{environment}-{serviceName}.api.company.com/{version}`,
    `${serviceName} microservice endpoint`
  );
  
  server.addVariable("environment", new ServerVariable(
    "prod",
    ["prod", "stage", "dev", "local"],
    "Deployment environment"
  ));
  
  server.addVariable("serviceName", new ServerVariable(
    serviceName,
    [serviceName], // Only this service name allowed
    `Service name (fixed as ${serviceName})`
  ));
  
  server.addVariable("version", new ServerVariable(
    "v1",
    ["v1", "v2"],
    "API version"
  ));
  
  return server;
};

// Build OpenAPI 3.1 spec with microservice servers
const spec = oas31.OpenApiBuilder.create()
  .addTitle("Microservices API Gateway")
  .addVersion("1.0.0")
  .addServer(createMicroserviceServer("users"))
  .addServer(createMicroserviceServer("orders")) 
  .addServer(createMicroserviceServer("payments"))
  .addServer(createMicroserviceServer("inventory"))
  .getSpec();

// Each server will have properly configured variables
spec.servers?.forEach(server => {
  console.log(`Server: ${server.url}`);
  console.log(`Variables:`, Object.keys(server.variables || {}));
});

Server Variable Validation

import { ServerVariable } from "openapi3-ts";

// Helper function to create validated server variables
function createValidatedVariable(
  defaultValue: string | number | boolean,
  allowedValues?: (string | number | boolean)[],
  description?: string
): ServerVariable {
  // Validate default value is in allowed values if provided
  if (allowedValues && !allowedValues.includes(defaultValue)) {
    throw new Error(`Default value ${defaultValue} not in allowed values: ${allowedValues}`);
  }
  
  return new ServerVariable(defaultValue, allowedValues, description);
}

// Usage with validation
try {
  const validVar = createValidatedVariable("prod", ["prod", "dev"], "Environment");
  console.log("Valid variable created:", validVar);
  
  const invalidVar = createValidatedVariable("invalid", ["prod", "dev"], "Environment");
} catch (error) {
  console.error("Validation failed:", error.message);
  // Output: "Validation failed: Default value invalid not in allowed values: prod,dev"
}

Extension Utility Functions

Utility functions for working with specification extensions on server objects.

/**
 * Get extension value from an object that supports specification extensions
 * @param obj - Object with potential extensions
 * @param extensionName - Extension name (must start with 'x-')
 * @returns Extension value or undefined if not found
 */
function getExtension(obj: ISpecificationExtension | undefined, extensionName: string): any;

/**
 * Add extension to an object that supports specification extensions
 * @param obj - Object to add extension to
 * @param extensionName - Extension name (must start with 'x-')
 * @param extension - Extension value
 */
function addExtension(
  obj: ISpecificationExtension | undefined,
  extensionName: string,
  extension: any
): void;

Extension Utility Usage

import { Server, ServerVariable, getExtension, addExtension } from "openapi3-ts";

// Create server and add extensions
const server = new Server("https://api.example.com", "API Server");

// Add extensions using utility function
addExtension(server, "x-rate-limit", { requests: 1000, window: "1h" });
addExtension(server, "x-health-check", "/health");
addExtension(server, "x-load-balancer", "round-robin");

// Retrieve extensions using utility function
const rateLimit = getExtension(server, "x-rate-limit");
const healthCheck = getExtension(server, "x-health-check");

console.log("Rate limit config:", rateLimit);
// Output: "Rate limit config: { requests: 1000, window: '1h' }"

console.log("Health check endpoint:", healthCheck);
// Output: "Health check endpoint: /health"

// Check for non-existent extension
const missing = getExtension(server, "x-nonexistent");
console.log("Missing extension:", missing); // Output: "Missing extension: undefined"

Install with Tessl CLI

npx tessl i tessl/npm-openapi3-ts

docs

index.md

openapi30-builder.md

openapi30-types.md

openapi31-builder.md

openapi31-types.md

server-management.md

specification-extensions.md

tile.json