Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | 1x 1x 16x 16x 16x 16x 34x 34x 34x 34x 34x 16x 34x 34x 34x 34x 170x 170x 54x 54x 54x 30x 34x 34x 34x 34x 12x 34x 34x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 10x 10x 54x 10x 54x 54x 10x 54x 54x 64x 64x 64x 64x 54x 10x 54x 34x 34x 34x 12x 34x 170x 170x 10x 10x 34x 34x 12x 12x 12x 22x 22x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 64x 64x 21x 43x 64x 43x 43x 43x 64x 3x 3x 4x 4x 4x 3x 10x 10x 88x 53x 53x 88x | import type {
OpRouteNode,
OpOperationNode,
OpParamNode,
OpRequestNode,
OpResponseNode,
OpResponseHeaderNode,
HttpMethod,
ModelNode,
SourceLocation,
SecurityNode,
} from '@contractkit/core';
import type {
NormalizedDocument,
NormalizedPathItem,
NormalizedOperation,
NormalizedParameter,
NormalizedRequestBody,
NormalizedResponse,
} from './types.js';
import { schemaToTypeNode, extractInlineModel } from './schema-to-ast.js';
import type { SchemaContext } from './schema-to-ast.js';
import type { WarningCollector } from './warnings.js';
const LOC: SourceLocation = { file: '', line: 0 };
const HTTP_METHODS: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete'];
// ─── Public API ───────────────────────────────────────────────────────────
export interface PathsContext {
circularRefs: Set<string>;
warnings: WarningCollector;
includeComments: boolean;
namedSchemas: Record<string, unknown>;
/** Accumulates inline models extracted from request/response bodies. */
extractedModels: ModelNode[];
/** Global security from the spec (for detecting explicit overrides). */
globalSecurity?: Record<string, string[]>[];
}
/**
* Convert OpenAPI paths to OpRouteNode[].
* Returns routes along with a tag mapping for each route.
*/
export function pathsToRoutes(doc: NormalizedDocument, ctx: PathsContext): { routes: OpRouteNode[]; routeTags: Map<OpRouteNode, string> } {
const routes: OpRouteNode[] = [];
const routeTags = new Map<OpRouteNode, string>();
const paths = doc.paths ?? {};
for (const [path, pathItem] of Object.entries(paths)) {
Iif (!pathItem) continue;
const result = pathItemToRoute(path, pathItem, ctx);
Eif (result) {
routes.push(result.route);
routeTags.set(result.route, result.tag);
}
}
return { routes, routeTags };
}
// ─── Path Item → Route ───────────────────────────────────────────────────
function pathItemToRoute(path: string, pathItem: NormalizedPathItem, ctx: PathsContext): { route: OpRouteNode; tag: string } | null {
const operations: OpOperationNode[] = [];
let primaryTag = 'default';
// Collect path-level parameters
const pathParams = (pathItem.parameters ?? []).filter(p => p.in === 'path');
for (const method of HTTP_METHODS) {
const op = pathItem[method];
if (!op) continue;
const opNode = operationToNode(method, op, path, ctx);
operations.push(opNode);
// Use first tag of first operation as the route's tag
if (op.tags && op.tags.length > 0 && primaryTag === 'default') {
primaryTag = op.tags[0]!;
}
}
Iif (operations.length === 0) return null;
// Build params from path-level + inferred from path template
const params = buildPathParams(path, pathParams, pathItem, ctx);
const route: OpRouteNode = {
path,
operations,
loc: LOC,
};
if (params.length > 0) {
route.params = { kind: 'params', nodes: params };
}
Iif (pathItem.description && ctx.includeComments) {
route.description = pathItem.description;
}
return { route, tag: primaryTag };
}
// ─── Operation → Node ─────────────────────────────────────────────────────
function operationToNode(method: HttpMethod, op: NormalizedOperation, path: string, ctx: PathsContext): OpOperationNode {
const pathPrefix = `#/paths/${encodePathSegment(path)}/${method}`;
const schemaCtx = makeSchemaCtx(ctx, pathPrefix);
const node: OpOperationNode = {
method,
responses: [],
loc: LOC,
};
// operationId → sdk
Eif (op.operationId) {
node.sdk = op.operationId;
}
// Description
Iif (op.description && ctx.includeComments) {
node.description = op.description;
}
// Deprecated
Iif (op.deprecated) {
node.modifiers = ['deprecated'];
}
// Query and header parameters
const queryParams: OpParamNode[] = [];
const headerParams: OpParamNode[] = [];
for (const param of op.parameters ?? []) {
if (param.in === 'query') {
queryParams.push(parameterToNode(param, schemaCtx));
E} else if (param.in === 'header') {
headerParams.push(parameterToNode(param, schemaCtx));
}
}
if (queryParams.length > 0) {
node.query = { kind: 'params', nodes: queryParams };
}
Iif (headerParams.length > 0) {
node.headers = { kind: 'params', nodes: headerParams };
}
// Request body
if (op.requestBody) {
node.request = requestBodyToNode(op.requestBody, op.operationId ?? `${method}${toPascalCase(path)}`, schemaCtx, ctx);
}
// Responses
const responses = op.responses ?? {};
for (const [code, resp] of Object.entries(responses)) {
const statusCode = parseInt(code, 10);
Iif (isNaN(statusCode)) continue;
const respNode = responseToNode(statusCode, resp, op.operationId ?? `${method}${toPascalCase(path)}`, schemaCtx, ctx);
node.responses.push(respNode);
}
// Security
if (op.security !== undefined) {
node.security = convertSecurity(op.security);
}
return node;
}
// ─── Parameters ───────────────────────────────────────────────────────────
function buildPathParams(path: string, pathLevelParams: NormalizedParameter[], pathItem: NormalizedPathItem, ctx: PathsContext): OpParamNode[] {
const schemaCtx = makeSchemaCtx(ctx, `#/paths/${encodePathSegment(path)}`);
// Collect all path params from path-level and operation-level
const paramMap = new Map<string, NormalizedParameter>();
for (const p of pathLevelParams) {
paramMap.set(p.name, p);
}
// Also check operation-level path params
for (const method of HTTP_METHODS) {
const op = pathItem[method];
if (!op?.parameters) continue;
for (const p of op.parameters) {
Iif (p.in === 'path' && !paramMap.has(p.name)) {
paramMap.set(p.name, p);
}
}
}
// Extract param names from path template
const templateNames = [...path.matchAll(/\{([^}]+)\}/g)].map(m => m[1]!);
return templateNames.map(name => {
const param = paramMap.get(name);
Eif (param) {
return parameterToNode(param, schemaCtx);
}
// Infer as uuid if no schema is given
return {
name,
optional: false,
nullable: false,
type: { kind: 'scalar' as const, name: 'string' as const },
loc: LOC,
};
});
}
function parameterToNode(param: NormalizedParameter, ctx: SchemaContext): OpParamNode {
const type = param.schema ? schemaToTypeNode(param.schema, ctx) : { kind: 'scalar' as const, name: 'string' as const };
return {
name: param.name,
optional: param.in !== 'path' && !param.required,
nullable: false,
type,
description: ctx.includeComments ? param.description : undefined,
loc: LOC,
};
}
// ─── Request Body ─────────────────────────────────────────────────────────
function requestBodyToNode(
reqBody: NormalizedRequestBody,
operationName: string,
schemaCtx: SchemaContext,
ctx: PathsContext,
): OpRequestNode | undefined {
const content = reqBody.content;
Iif (!content) return undefined;
const supported = new Set<string>(['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']);
const bodies: OpRequestNode['bodies'] = [];
for (const [contentType, mediaType] of Object.entries(content)) {
Iif (!supported.has(contentType) || !mediaType?.schema) continue;
const { typeNode, model } = extractInlineModel(mediaType.schema, `${toPascalCase(operationName)}Request`, schemaCtx);
Iif (model) {
ctx.extractedModels.push(model);
}
bodies.push({
contentType: contentType as OpRequestNode['bodies'][number]['contentType'],
bodyType: typeNode,
});
}
Iif (bodies.length === 0) return undefined;
return { bodies };
}
// ─── Responses ────────────────────────────────────────────────────────────
function responseToNode(
statusCode: number,
resp: NormalizedResponse,
operationName: string,
schemaCtx: SchemaContext,
ctx: PathsContext,
): OpResponseNode {
const headers = convertResponseHeaders(resp.headers, schemaCtx);
if (!resp.content) {
return headers ? { statusCode, headers } : { statusCode };
}
// Pick the first content type
const [contentType, mediaType] = Object.entries(resp.content)[0] ?? [];
Iif (!contentType || !mediaType?.schema) {
return headers ? { statusCode, headers } : { statusCode };
}
const { typeNode, model } = extractInlineModel(mediaType.schema, `${toPascalCase(operationName)}Response${statusCode}`, schemaCtx);
Iif (model) {
ctx.extractedModels.push(model);
}
return {
statusCode,
contentType: contentType as 'application/json',
bodyType: typeNode,
...(headers ? { headers } : {}),
};
}
function convertResponseHeaders(headers: NormalizedResponse['headers'], schemaCtx: SchemaContext): OpResponseHeaderNode[] | undefined {
if (!headers) return undefined;
const out: OpResponseHeaderNode[] = [];
for (const [name, header] of Object.entries(headers)) {
Iif (!header) continue;
const type = header.schema ? schemaToTypeNode(header.schema, schemaCtx) : { kind: 'scalar' as const, name: 'string' as const };
out.push({
name,
optional: !header.required,
type,
description: schemaCtx.includeComments ? header.description : undefined,
});
}
return out.length > 0 ? out : undefined;
}
// ─── Security ─────────────────────────────────────────────────────────────
function convertSecurity(security: Record<string, string[]>[]): SecurityNode {
// Empty array = explicitly no security
Eif (security.length === 0) {
return 'none';
}
// The DSL's security model is simpler — extract roles if present
// For most security schemes, just note that security is required
const allScopes: string[] = [];
for (const requirement of security) {
for (const scopes of Object.values(requirement)) {
allScopes.push(...scopes);
}
}
if (allScopes.length > 0) {
return { roles: allScopes, loc: LOC };
}
// Security required but no specific scopes/roles
return { roles: [], loc: LOC };
}
// ─── Helpers ──────────────────────────────────────────────────────────────
function makeSchemaCtx(ctx: PathsContext, path: string): SchemaContext {
return {
circularRefs: ctx.circularRefs,
warnings: ctx.warnings,
path,
includeComments: ctx.includeComments,
namedSchemas: ctx.namedSchemas as Record<string, never>,
extractedModels: ctx.extractedModels,
inlineCounter: 0,
};
}
function toPascalCase(input: string): string {
return input
.replace(/[^a-zA-Z0-9]/g, ' ')
.split(/\s+/)
.filter(Boolean)
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
}
function encodePathSegment(s: string): string {
return s.replace(/~/g, '~0').replace(/\//g, '~1');
}
|