@contractkit/openapi-to-ck 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.turbo/turbo-build$colon$ci.log +40 -0
  2. package/.turbo/turbo-build.log +20 -0
  3. package/.turbo/turbo-format.log +36 -0
  4. package/.turbo/turbo-test$colon$ci.log +77 -0
  5. package/.turbo/turbo-test.log +19 -0
  6. package/CHANGELOG.md +108 -0
  7. package/coverage/base.css +224 -0
  8. package/coverage/block-navigation.js +87 -0
  9. package/coverage/clover.xml +878 -0
  10. package/coverage/coverage-final.json +10 -0
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +131 -0
  13. package/coverage/prettify.css +1 -0
  14. package/coverage/prettify.js +2 -0
  15. package/coverage/sort-arrow-sprite.png +0 -0
  16. package/coverage/sorter.js +210 -0
  17. package/coverage/src/ast-to-ck.ts.html +1336 -0
  18. package/coverage/src/circular-refs.ts.html +298 -0
  19. package/coverage/src/convert.ts.html +535 -0
  20. package/coverage/src/index.html +221 -0
  21. package/coverage/src/normalize.ts.html +1162 -0
  22. package/coverage/src/paths-to-ast.ts.html +1165 -0
  23. package/coverage/src/schema-to-ast.ts.html +1378 -0
  24. package/coverage/src/tag-splitter.ts.html +685 -0
  25. package/coverage/src/warnings.ts.html +154 -0
  26. package/coverage/tests/helpers.ts.html +559 -0
  27. package/coverage/tests/index.html +116 -0
  28. package/dist/ast-to-ck.d.ts +8 -0
  29. package/dist/ast-to-ck.d.ts.map +1 -0
  30. package/dist/chunk-CQGFQKBJ.js +1681 -0
  31. package/dist/chunk-CQGFQKBJ.js.map +1 -0
  32. package/dist/chunk-FNUU2DWY.js +1779 -0
  33. package/dist/chunk-FNUU2DWY.js.map +1 -0
  34. package/dist/chunk-LD2HAFZG.js +1681 -0
  35. package/dist/chunk-LD2HAFZG.js.map +1 -0
  36. package/dist/chunk-LQ2B3EJG.js +1777 -0
  37. package/dist/chunk-LQ2B3EJG.js.map +1 -0
  38. package/dist/chunk-M6JA6WY2.js +1714 -0
  39. package/dist/chunk-M6JA6WY2.js.map +1 -0
  40. package/dist/chunk-MQTKLXTN.js +1681 -0
  41. package/dist/chunk-MQTKLXTN.js.map +1 -0
  42. package/dist/chunk-NV7RGUUS.js +1699 -0
  43. package/dist/chunk-NV7RGUUS.js.map +1 -0
  44. package/dist/chunk-REM25FDE.js +1779 -0
  45. package/dist/chunk-REM25FDE.js.map +1 -0
  46. package/dist/chunk-SNW7GJOM.js +1681 -0
  47. package/dist/chunk-SNW7GJOM.js.map +1 -0
  48. package/dist/chunk-UWOSCBRG.js +1681 -0
  49. package/dist/chunk-UWOSCBRG.js.map +1 -0
  50. package/dist/chunk-YP7FWA4H.js +1779 -0
  51. package/dist/chunk-YP7FWA4H.js.map +1 -0
  52. package/dist/circular-refs.d.ts +12 -0
  53. package/dist/circular-refs.d.ts.map +1 -0
  54. package/dist/convert.d.ts +6 -0
  55. package/dist/convert.d.ts.map +1 -0
  56. package/dist/index.d.ts +9 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +29 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/normalize.d.ts +12 -0
  61. package/dist/normalize.d.ts.map +1 -0
  62. package/dist/paths-to-ast.d.ts +22 -0
  63. package/dist/paths-to-ast.d.ts.map +1 -0
  64. package/dist/plugin.d.ts +4 -0
  65. package/dist/plugin.d.ts.map +1 -0
  66. package/dist/plugin.js +86 -0
  67. package/dist/plugin.js.map +1 -0
  68. package/dist/schema-to-ast.d.ts +39 -0
  69. package/dist/schema-to-ast.d.ts.map +1 -0
  70. package/dist/tag-splitter.d.ts +16 -0
  71. package/dist/tag-splitter.d.ts.map +1 -0
  72. package/dist/types.d.ts +137 -0
  73. package/dist/types.d.ts.map +1 -0
  74. package/dist/warnings.d.ts +10 -0
  75. package/dist/warnings.d.ts.map +1 -0
  76. package/eslint.config.js +6 -0
  77. package/package.json +46 -0
  78. package/src/ast-to-ck.ts +417 -0
  79. package/src/circular-refs.ts +71 -0
  80. package/src/convert.ts +150 -0
  81. package/src/index.ts +8 -0
  82. package/src/normalize.ts +359 -0
  83. package/src/paths-to-ast.ts +360 -0
  84. package/src/plugin.ts +89 -0
  85. package/src/schema-to-ast.ts +431 -0
  86. package/src/tag-splitter.ts +200 -0
  87. package/src/types.ts +133 -0
  88. package/src/warnings.ts +23 -0
  89. package/tests/ast-to-ck.test.ts +425 -0
  90. package/tests/circular-refs.test.ts +71 -0
  91. package/tests/convert.test.ts +330 -0
  92. package/tests/fixtures/petstore-3.1.json +187 -0
  93. package/tests/helpers.ts +158 -0
  94. package/tests/normalize.test.ts +114 -0
  95. package/tests/schema-to-ast.test.ts +341 -0
  96. package/tests/tag-splitter.test.ts +75 -0
  97. package/tsconfig.json +9 -0
@@ -0,0 +1,360 @@
1
+ import type {
2
+ OpRouteNode,
3
+ OpOperationNode,
4
+ OpParamNode,
5
+ OpRequestNode,
6
+ OpResponseNode,
7
+ OpResponseHeaderNode,
8
+ HttpMethod,
9
+ ModelNode,
10
+ SourceLocation,
11
+ SecurityNode,
12
+ } from '@contractkit/core';
13
+ import type {
14
+ NormalizedDocument,
15
+ NormalizedPathItem,
16
+ NormalizedOperation,
17
+ NormalizedParameter,
18
+ NormalizedRequestBody,
19
+ NormalizedResponse,
20
+ } from './types.js';
21
+ import { schemaToTypeNode, extractInlineModel } from './schema-to-ast.js';
22
+ import type { SchemaContext } from './schema-to-ast.js';
23
+ import type { WarningCollector } from './warnings.js';
24
+
25
+ const LOC: SourceLocation = { file: '', line: 0 };
26
+ const HTTP_METHODS: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete'];
27
+
28
+ // ─── Public API ───────────────────────────────────────────────────────────
29
+
30
+ export interface PathsContext {
31
+ circularRefs: Set<string>;
32
+ warnings: WarningCollector;
33
+ includeComments: boolean;
34
+ namedSchemas: Record<string, unknown>;
35
+ /** Accumulates inline models extracted from request/response bodies. */
36
+ extractedModels: ModelNode[];
37
+ /** Global security from the spec (for detecting explicit overrides). */
38
+ globalSecurity?: Record<string, string[]>[];
39
+ }
40
+
41
+ /**
42
+ * Convert OpenAPI paths to OpRouteNode[].
43
+ * Returns routes along with a tag mapping for each route.
44
+ */
45
+ export function pathsToRoutes(doc: NormalizedDocument, ctx: PathsContext): { routes: OpRouteNode[]; routeTags: Map<OpRouteNode, string> } {
46
+ const routes: OpRouteNode[] = [];
47
+ const routeTags = new Map<OpRouteNode, string>();
48
+ const paths = doc.paths ?? {};
49
+
50
+ for (const [path, pathItem] of Object.entries(paths)) {
51
+ if (!pathItem) continue;
52
+ const result = pathItemToRoute(path, pathItem, ctx);
53
+ if (result) {
54
+ routes.push(result.route);
55
+ routeTags.set(result.route, result.tag);
56
+ }
57
+ }
58
+
59
+ return { routes, routeTags };
60
+ }
61
+
62
+ // ─── Path Item → Route ───────────────────────────────────────────────────
63
+
64
+ function pathItemToRoute(path: string, pathItem: NormalizedPathItem, ctx: PathsContext): { route: OpRouteNode; tag: string } | null {
65
+ const operations: OpOperationNode[] = [];
66
+ let primaryTag = 'default';
67
+
68
+ // Collect path-level parameters
69
+ const pathParams = (pathItem.parameters ?? []).filter(p => p.in === 'path');
70
+
71
+ for (const method of HTTP_METHODS) {
72
+ const op = pathItem[method];
73
+ if (!op) continue;
74
+
75
+ const opNode = operationToNode(method, op, path, ctx);
76
+ operations.push(opNode);
77
+
78
+ // Use first tag of first operation as the route's tag
79
+ if (op.tags && op.tags.length > 0 && primaryTag === 'default') {
80
+ primaryTag = op.tags[0]!;
81
+ }
82
+ }
83
+
84
+ if (operations.length === 0) return null;
85
+
86
+ // Build params from path-level + inferred from path template
87
+ const params = buildPathParams(path, pathParams, pathItem, ctx);
88
+
89
+ const route: OpRouteNode = {
90
+ path,
91
+ operations,
92
+ loc: LOC,
93
+ };
94
+
95
+ if (params.length > 0) {
96
+ route.params = { kind: 'params', nodes: params };
97
+ }
98
+
99
+ if (pathItem.description && ctx.includeComments) {
100
+ route.description = pathItem.description;
101
+ }
102
+
103
+ return { route, tag: primaryTag };
104
+ }
105
+
106
+ // ─── Operation → Node ─────────────────────────────────────────────────────
107
+
108
+ function operationToNode(method: HttpMethod, op: NormalizedOperation, path: string, ctx: PathsContext): OpOperationNode {
109
+ const pathPrefix = `#/paths/${encodePathSegment(path)}/${method}`;
110
+ const schemaCtx = makeSchemaCtx(ctx, pathPrefix);
111
+
112
+ const node: OpOperationNode = {
113
+ method,
114
+ responses: [],
115
+ loc: LOC,
116
+ };
117
+
118
+ // operationId → sdk
119
+ if (op.operationId) {
120
+ node.sdk = op.operationId;
121
+ }
122
+
123
+ // Description
124
+ if (op.description && ctx.includeComments) {
125
+ node.description = op.description;
126
+ }
127
+
128
+ // Deprecated
129
+ if (op.deprecated) {
130
+ node.modifiers = ['deprecated'];
131
+ }
132
+
133
+ // Query and header parameters
134
+ const queryParams: OpParamNode[] = [];
135
+ const headerParams: OpParamNode[] = [];
136
+
137
+ for (const param of op.parameters ?? []) {
138
+ if (param.in === 'query') {
139
+ queryParams.push(parameterToNode(param, schemaCtx));
140
+ } else if (param.in === 'header') {
141
+ headerParams.push(parameterToNode(param, schemaCtx));
142
+ }
143
+ }
144
+
145
+ if (queryParams.length > 0) {
146
+ node.query = { kind: 'params', nodes: queryParams };
147
+ }
148
+ if (headerParams.length > 0) {
149
+ node.headers = { kind: 'params', nodes: headerParams };
150
+ }
151
+
152
+ // Request body
153
+ if (op.requestBody) {
154
+ node.request = requestBodyToNode(op.requestBody, op.operationId ?? `${method}${toPascalCase(path)}`, schemaCtx, ctx);
155
+ }
156
+
157
+ // Responses
158
+ const responses = op.responses ?? {};
159
+ for (const [code, resp] of Object.entries(responses)) {
160
+ const statusCode = parseInt(code, 10);
161
+ if (isNaN(statusCode)) continue;
162
+ const respNode = responseToNode(statusCode, resp, op.operationId ?? `${method}${toPascalCase(path)}`, schemaCtx, ctx);
163
+ node.responses.push(respNode);
164
+ }
165
+
166
+ // Security
167
+ if (op.security !== undefined) {
168
+ node.security = convertSecurity(op.security);
169
+ }
170
+
171
+ return node;
172
+ }
173
+
174
+ // ─── Parameters ───────────────────────────────────────────────────────────
175
+
176
+ function buildPathParams(path: string, pathLevelParams: NormalizedParameter[], pathItem: NormalizedPathItem, ctx: PathsContext): OpParamNode[] {
177
+ const schemaCtx = makeSchemaCtx(ctx, `#/paths/${encodePathSegment(path)}`);
178
+
179
+ // Collect all path params from path-level and operation-level
180
+ const paramMap = new Map<string, NormalizedParameter>();
181
+
182
+ for (const p of pathLevelParams) {
183
+ paramMap.set(p.name, p);
184
+ }
185
+
186
+ // Also check operation-level path params
187
+ for (const method of HTTP_METHODS) {
188
+ const op = pathItem[method];
189
+ if (!op?.parameters) continue;
190
+ for (const p of op.parameters) {
191
+ if (p.in === 'path' && !paramMap.has(p.name)) {
192
+ paramMap.set(p.name, p);
193
+ }
194
+ }
195
+ }
196
+
197
+ // Extract param names from path template
198
+ const templateNames = [...path.matchAll(/\{([^}]+)\}/g)].map(m => m[1]!);
199
+
200
+ return templateNames.map(name => {
201
+ const param = paramMap.get(name);
202
+ if (param) {
203
+ return parameterToNode(param, schemaCtx);
204
+ }
205
+ // Infer as uuid if no schema is given
206
+ return {
207
+ name,
208
+ optional: false,
209
+ nullable: false,
210
+ type: { kind: 'scalar' as const, name: 'string' as const },
211
+ loc: LOC,
212
+ };
213
+ });
214
+ }
215
+
216
+ function parameterToNode(param: NormalizedParameter, ctx: SchemaContext): OpParamNode {
217
+ const type = param.schema ? schemaToTypeNode(param.schema, ctx) : { kind: 'scalar' as const, name: 'string' as const };
218
+
219
+ return {
220
+ name: param.name,
221
+ optional: param.in !== 'path' && !param.required,
222
+ nullable: false,
223
+ type,
224
+ description: ctx.includeComments ? param.description : undefined,
225
+ loc: LOC,
226
+ };
227
+ }
228
+
229
+ // ─── Request Body ─────────────────────────────────────────────────────────
230
+
231
+ function requestBodyToNode(
232
+ reqBody: NormalizedRequestBody,
233
+ operationName: string,
234
+ schemaCtx: SchemaContext,
235
+ ctx: PathsContext,
236
+ ): OpRequestNode | undefined {
237
+ const content = reqBody.content;
238
+ if (!content) return undefined;
239
+
240
+ const supported = new Set<string>(['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']);
241
+ const bodies: OpRequestNode['bodies'] = [];
242
+
243
+ for (const [contentType, mediaType] of Object.entries(content)) {
244
+ if (!supported.has(contentType) || !mediaType?.schema) continue;
245
+ const { typeNode, model } = extractInlineModel(mediaType.schema, `${toPascalCase(operationName)}Request`, schemaCtx);
246
+ if (model) {
247
+ ctx.extractedModels.push(model);
248
+ }
249
+ bodies.push({
250
+ contentType: contentType as OpRequestNode['bodies'][number]['contentType'],
251
+ bodyType: typeNode,
252
+ });
253
+ }
254
+
255
+ if (bodies.length === 0) return undefined;
256
+ return { bodies };
257
+ }
258
+
259
+ // ─── Responses ────────────────────────────────────────────────────────────
260
+
261
+ function responseToNode(
262
+ statusCode: number,
263
+ resp: NormalizedResponse,
264
+ operationName: string,
265
+ schemaCtx: SchemaContext,
266
+ ctx: PathsContext,
267
+ ): OpResponseNode {
268
+ const headers = convertResponseHeaders(resp.headers, schemaCtx);
269
+
270
+ if (!resp.content) {
271
+ return headers ? { statusCode, headers } : { statusCode };
272
+ }
273
+
274
+ // Pick the first content type
275
+ const [contentType, mediaType] = Object.entries(resp.content)[0] ?? [];
276
+ if (!contentType || !mediaType?.schema) {
277
+ return headers ? { statusCode, headers } : { statusCode };
278
+ }
279
+
280
+ const { typeNode, model } = extractInlineModel(mediaType.schema, `${toPascalCase(operationName)}Response${statusCode}`, schemaCtx);
281
+
282
+ if (model) {
283
+ ctx.extractedModels.push(model);
284
+ }
285
+
286
+ return {
287
+ statusCode,
288
+ contentType: contentType as 'application/json',
289
+ bodyType: typeNode,
290
+ ...(headers ? { headers } : {}),
291
+ };
292
+ }
293
+
294
+ function convertResponseHeaders(headers: NormalizedResponse['headers'], schemaCtx: SchemaContext): OpResponseHeaderNode[] | undefined {
295
+ if (!headers) return undefined;
296
+ const out: OpResponseHeaderNode[] = [];
297
+ for (const [name, header] of Object.entries(headers)) {
298
+ if (!header) continue;
299
+ const type = header.schema ? schemaToTypeNode(header.schema, schemaCtx) : { kind: 'scalar' as const, name: 'string' as const };
300
+ out.push({
301
+ name,
302
+ optional: !header.required,
303
+ type,
304
+ description: schemaCtx.includeComments ? header.description : undefined,
305
+ });
306
+ }
307
+ return out.length > 0 ? out : undefined;
308
+ }
309
+
310
+ // ─── Security ─────────────────────────────────────────────────────────────
311
+
312
+ function convertSecurity(security: Record<string, string[]>[]): SecurityNode {
313
+ // Empty array = explicitly no security
314
+ if (security.length === 0) {
315
+ return 'none';
316
+ }
317
+
318
+ // The DSL's security model is simpler — extract roles if present
319
+ // For most security schemes, just note that security is required
320
+ const allScopes: string[] = [];
321
+ for (const requirement of security) {
322
+ for (const scopes of Object.values(requirement)) {
323
+ allScopes.push(...scopes);
324
+ }
325
+ }
326
+
327
+ if (allScopes.length > 0) {
328
+ return { roles: allScopes, loc: LOC };
329
+ }
330
+
331
+ // Security required but no specific scopes/roles
332
+ return { roles: [], loc: LOC };
333
+ }
334
+
335
+ // ─── Helpers ──────────────────────────────────────────────────────────────
336
+
337
+ function makeSchemaCtx(ctx: PathsContext, path: string): SchemaContext {
338
+ return {
339
+ circularRefs: ctx.circularRefs,
340
+ warnings: ctx.warnings,
341
+ path,
342
+ includeComments: ctx.includeComments,
343
+ namedSchemas: ctx.namedSchemas as Record<string, never>,
344
+ extractedModels: ctx.extractedModels,
345
+ inlineCounter: 0,
346
+ };
347
+ }
348
+
349
+ function toPascalCase(input: string): string {
350
+ return input
351
+ .replace(/[^a-zA-Z0-9]/g, ' ')
352
+ .split(/\s+/)
353
+ .filter(Boolean)
354
+ .map(part => part.charAt(0).toUpperCase() + part.slice(1))
355
+ .join('');
356
+ }
357
+
358
+ function encodePathSegment(s: string): string {
359
+ return s.replace(/~/g, '~0').replace(/\//g, '~1');
360
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { writeFileSync, mkdirSync } from 'node:fs';
2
+ import { resolve, join } from 'node:path';
3
+ import { convertOpenApiToCk } from './convert.js';
4
+ import type { Warning } from './types.js';
5
+ import type { ContractKitPlugin, CommandContext } from '@contractkit/core';
6
+
7
+ interface ImportArgs {
8
+ specPath: string;
9
+ output: string;
10
+ split: 'single' | 'by-tag';
11
+ }
12
+
13
+ function parseImportArgs(argv: string[]): ImportArgs {
14
+ let specPath = '';
15
+ let output = '.';
16
+ let split: 'single' | 'by-tag' = 'by-tag';
17
+
18
+ for (let i = 0; i < argv.length; i++) {
19
+ const arg = argv[i]!;
20
+ if (arg === '--output' || arg === '-o') {
21
+ output = argv[++i] ?? '.';
22
+ } else if (arg === '--split') {
23
+ const val = argv[++i];
24
+ if (val === 'single' || val === 'by-tag') split = val;
25
+ } else if (!arg.startsWith('-')) {
26
+ specPath = arg;
27
+ }
28
+ }
29
+
30
+ return { specPath, output, split };
31
+ }
32
+
33
+ const USAGE = `Usage: contractkit import-openapi <spec-path> [options]
34
+
35
+ Convert an OpenAPI 2.0/3.0/3.1 YAML or JSON spec into .ck contract files.
36
+
37
+ Arguments:
38
+ <spec-path> Path to the OpenAPI spec file
39
+
40
+ Options:
41
+ -o, --output <dir> Output directory for .ck files (default: current directory)
42
+ --split <mode> How to split output: "by-tag" (one file per tag) or "single" (default: by-tag)
43
+ -h, --help Show this help message`;
44
+
45
+ const plugin: ContractKitPlugin = {
46
+ name: 'import-openapi',
47
+ command: {
48
+ name: 'import-openapi',
49
+ description: 'Convert an OpenAPI YAML/JSON spec to .ck contracts',
50
+ usage: USAGE,
51
+ async run(args: string[], _ctx: CommandContext): Promise<void> {
52
+ const parsed = parseImportArgs(args);
53
+
54
+ if (!parsed.specPath) {
55
+ console.error(USAGE);
56
+ process.exit(1);
57
+ }
58
+
59
+ console.log(`Converting ${parsed.specPath} → .ck files...`);
60
+
61
+ const result = await convertOpenApiToCk({
62
+ input: resolve(parsed.specPath),
63
+ split: parsed.split,
64
+ includeComments: true,
65
+ onWarning: (w: Warning) => {
66
+ const prefix = w.severity === 'warn' ? '⚠' : 'ℹ';
67
+ console.warn(` ${prefix} ${w.path}: ${w.message}`);
68
+ },
69
+ });
70
+
71
+ const outputDir = resolve(parsed.output);
72
+ mkdirSync(outputDir, { recursive: true });
73
+
74
+ for (const [filename, content] of result.files) {
75
+ const outPath = join(outputDir, filename);
76
+ writeFileSync(outPath, content, 'utf-8');
77
+ console.log(` ✓ ${outPath}`);
78
+ }
79
+
80
+ if (result.warnings.length > 0) {
81
+ console.log(`\n${result.warnings.length} warning(s) during conversion.`);
82
+ }
83
+
84
+ console.log(`\nGenerated ${result.files.size} file(s).`);
85
+ },
86
+ },
87
+ };
88
+
89
+ export default plugin;