@pikku/openapi-parser 0.12.3

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.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Parses OpenAPI YAML/JSON specs, resolves $ref pointers, and produces a normalized IR.
3
+ */
4
+ import { createHash } from 'crypto';
5
+ import { readFile } from 'fs/promises';
6
+ import { parse as parseYAML } from 'yaml';
7
+ /**
8
+ * Read and parse an OpenAPI spec from a file path.
9
+ * Supports both YAML (.yaml, .yml) and JSON (.json) files.
10
+ */
11
+ export async function parseOpenAPISpec(filePath) {
12
+ const content = await readFile(filePath, 'utf-8');
13
+ let doc;
14
+ if (filePath.endsWith('.json')) {
15
+ doc = JSON.parse(content);
16
+ }
17
+ else {
18
+ doc = parseYAML(content);
19
+ }
20
+ // Validate spec version
21
+ const specVersion = doc.openapi ?? doc.swagger;
22
+ if (!specVersion) {
23
+ throw new Error('Not a valid OpenAPI/Swagger spec: missing "openapi" or "swagger" version field.');
24
+ }
25
+ const major = String(specVersion).split('.')[0];
26
+ if (major !== '2' && major !== '3') {
27
+ throw new Error(`Unsupported spec version "${specVersion}". Only OpenAPI 3.x and Swagger 2.x are supported.`);
28
+ }
29
+ // Resolve all $ref pointers in-place
30
+ resolveRefs(doc, doc);
31
+ const info = {
32
+ title: doc.info?.title ?? 'Unknown API',
33
+ version: doc.info?.version ?? '1.0.0',
34
+ description: doc.info?.description,
35
+ };
36
+ const serverUrls = extractServerUrls(doc);
37
+ const baseUrl = serverUrls[0] ?? '';
38
+ const authType = detectAuthType(doc);
39
+ const securitySchemes = extractSecuritySchemes(doc);
40
+ const tagDescriptions = extractTagDescriptions(doc);
41
+ // Extract component schemas
42
+ const componentSchemas = {};
43
+ if (doc.components?.schemas) {
44
+ for (const [name, schema] of Object.entries(doc.components.schemas)) {
45
+ componentSchemas[name] = schema;
46
+ }
47
+ }
48
+ // Extract operations (skip deprecated)
49
+ const operations = [];
50
+ if (doc.paths) {
51
+ for (const [path, pathItem] of Object.entries(doc.paths)) {
52
+ // Shared parameters at the path level
53
+ const sharedParams = pathItem.parameters ?? [];
54
+ for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
55
+ const op = pathItem[method];
56
+ if (!op)
57
+ continue;
58
+ // Skip deprecated operations
59
+ if (op.deprecated === true)
60
+ continue;
61
+ const allParams = [...sharedParams, ...(op.parameters ?? [])];
62
+ const body = op.requestBody;
63
+ operations.push({
64
+ operationId: op.operationId,
65
+ method,
66
+ path,
67
+ summary: op.summary,
68
+ description: op.description,
69
+ tags: op.tags ?? [],
70
+ pathParams: extractParams(allParams, 'path'),
71
+ queryParams: extractParams(allParams, 'query'),
72
+ headerParams: extractParams(allParams, 'header'),
73
+ requestBody: extractRequestBody(op),
74
+ requestBodyDescription: body?.description,
75
+ requestBodyRequired: body?.required,
76
+ responseSchema: extractResponseSchema(op),
77
+ responseDescription: extractResponseDescription(op),
78
+ errorResponses: extractErrorResponses(op),
79
+ deprecated: false,
80
+ });
81
+ }
82
+ }
83
+ }
84
+ return {
85
+ info,
86
+ baseUrl,
87
+ serverUrls,
88
+ authType,
89
+ operations,
90
+ componentSchemas,
91
+ securitySchemes,
92
+ tagDescriptions,
93
+ };
94
+ }
95
+ /** Recursively resolve $ref pointers in-place */
96
+ function resolveRefs(node, root) {
97
+ if (node === null || typeof node !== 'object')
98
+ return node;
99
+ if (Array.isArray(node)) {
100
+ for (let i = 0; i < node.length; i++) {
101
+ node[i] = resolveRefs(node[i], root);
102
+ }
103
+ return node;
104
+ }
105
+ if (typeof node.$ref === 'string') {
106
+ const resolved = resolveRefPath(node.$ref, root);
107
+ if (resolved && typeof resolved === 'object') {
108
+ // Merge any sibling properties (like description overrides)
109
+ const { $ref, ...siblings } = node;
110
+ const result = { ...resolved, ...siblings };
111
+ // Don't recurse infinitely — mark as resolved
112
+ return result;
113
+ }
114
+ return node;
115
+ }
116
+ for (const key of Object.keys(node)) {
117
+ node[key] = resolveRefs(node[key], root);
118
+ }
119
+ return node;
120
+ }
121
+ function resolveRefPath(ref, root) {
122
+ if (!ref.startsWith('#/'))
123
+ return undefined;
124
+ const parts = ref.slice(2).split('/');
125
+ let current = root;
126
+ for (const part of parts) {
127
+ const decoded = part.replace(/~1/g, '/').replace(/~0/g, '~');
128
+ if (current == null || typeof current !== 'object')
129
+ return undefined;
130
+ current = current[decoded];
131
+ }
132
+ return current;
133
+ }
134
+ function extractServerUrls(doc) {
135
+ // OpenAPI 3.x
136
+ if (doc.servers && doc.servers.length > 0) {
137
+ return doc.servers.map((s) => s.url).filter((url) => !!url);
138
+ }
139
+ // Swagger 2.x
140
+ if (doc.host) {
141
+ const schemes = doc.schemes?.length ? doc.schemes : ['https'];
142
+ const basePath = doc.basePath ?? '';
143
+ return schemes.map((scheme) => `${scheme}://${doc.host}${basePath}`);
144
+ }
145
+ return [];
146
+ }
147
+ function detectAuthType(doc) {
148
+ const securitySchemes = doc.components?.securitySchemes ?? doc.securityDefinitions ?? {};
149
+ for (const scheme of Object.values(securitySchemes)) {
150
+ if (scheme.type === 'oauth2')
151
+ return 'oauth2';
152
+ if (scheme.type === 'http' && scheme.scheme === 'bearer')
153
+ return 'bearer';
154
+ if (scheme.type === 'apiKey')
155
+ return 'apiKey';
156
+ }
157
+ return 'none';
158
+ }
159
+ /**
160
+ * Build an OpenAPI schema object from v2-style parameter-level properties
161
+ * (type, enum, items, format, default) that aren't nested under `schema`.
162
+ */
163
+ function paramToSchema(p) {
164
+ const schema = { type: p.type ?? 'string' };
165
+ if (p.enum)
166
+ schema.enum = p.enum;
167
+ if (p.items)
168
+ schema.items = p.items;
169
+ if (p.format)
170
+ schema.format = p.format;
171
+ if (p.default !== undefined)
172
+ schema.default = p.default;
173
+ return schema;
174
+ }
175
+ function extractParams(params, location) {
176
+ return params
177
+ .filter((p) => p.in === location)
178
+ .map((p) => ({
179
+ name: p.name,
180
+ required: p.required ?? location === 'path',
181
+ schema: (p.schema ?? paramToSchema(p)),
182
+ description: p.description,
183
+ example: p.example,
184
+ }));
185
+ }
186
+ function extractRequestBody(op) {
187
+ const body = op.requestBody;
188
+ if (!body)
189
+ return undefined;
190
+ const content = body.content;
191
+ if (!content)
192
+ return undefined;
193
+ // Prefer JSON
194
+ const jsonContent = content['application/json'];
195
+ if (jsonContent?.schema)
196
+ return jsonContent.schema;
197
+ // Fallback to first content type
198
+ const firstKey = Object.keys(content)[0];
199
+ if (firstKey && content[firstKey]?.schema) {
200
+ return content[firstKey].schema;
201
+ }
202
+ return undefined;
203
+ }
204
+ function extractResponseDescription(op) {
205
+ const responses = op.responses;
206
+ if (!responses)
207
+ return undefined;
208
+ for (const code of ['200', '201', '202']) {
209
+ const resp = responses[code];
210
+ if (resp?.description)
211
+ return resp.description;
212
+ }
213
+ return undefined;
214
+ }
215
+ function extractResponseSchema(op) {
216
+ const responses = op.responses;
217
+ if (!responses)
218
+ return undefined;
219
+ // Look for 2xx responses in order of preference
220
+ for (const code of ['200', '201', '202', '204']) {
221
+ const resp = responses[code];
222
+ if (!resp)
223
+ continue;
224
+ const content = resp.content;
225
+ if (!content)
226
+ continue;
227
+ const jsonContent = content['application/json'];
228
+ if (jsonContent?.schema)
229
+ return jsonContent.schema;
230
+ const firstKey = Object.keys(content)[0];
231
+ if (firstKey && content[firstKey]?.schema) {
232
+ return content[firstKey].schema;
233
+ }
234
+ }
235
+ // Fallback: any 2xx
236
+ for (const [code, resp] of Object.entries(responses)) {
237
+ if (code.startsWith('2') && resp.content) {
238
+ const jsonContent = resp.content['application/json'];
239
+ if (jsonContent?.schema)
240
+ return jsonContent.schema;
241
+ }
242
+ }
243
+ return undefined;
244
+ }
245
+ function extractErrorResponses(op) {
246
+ const responses = op.responses;
247
+ if (!responses)
248
+ return [];
249
+ const errors = [];
250
+ for (const [code, resp] of Object.entries(responses)) {
251
+ const statusCode = parseInt(code, 10);
252
+ if (isNaN(statusCode))
253
+ continue;
254
+ if (statusCode >= 400) {
255
+ errors.push({
256
+ statusCode,
257
+ description: resp.description ?? `Error ${statusCode}`,
258
+ });
259
+ }
260
+ }
261
+ return errors;
262
+ }
263
+ function extractSecuritySchemes(doc) {
264
+ const raw = doc.components?.securitySchemes ?? doc.securityDefinitions ?? {};
265
+ const result = {};
266
+ for (const [name, scheme] of Object.entries(raw)) {
267
+ const info = {
268
+ type: scheme.type === 'http' ? 'http' : scheme.type,
269
+ };
270
+ if (scheme.type === 'http') {
271
+ info.scheme = scheme.scheme;
272
+ info.bearerFormat = scheme.bearerFormat;
273
+ }
274
+ if (scheme.type === 'apiKey') {
275
+ info.name = scheme.name;
276
+ info.in = scheme.in;
277
+ }
278
+ if (scheme.type === 'oauth2') {
279
+ // Extract flows — prefer authorizationCode, then implicit, then clientCredentials
280
+ const flows = scheme.flows ?? {};
281
+ const flow = flows.authorizationCode ??
282
+ flows.implicit ??
283
+ flows.clientCredentials ??
284
+ flows.password;
285
+ if (flow) {
286
+ info.flows = {
287
+ authorizationUrl: flow.authorizationUrl,
288
+ tokenUrl: flow.tokenUrl,
289
+ scopes: flow.scopes,
290
+ };
291
+ }
292
+ }
293
+ result[name] = info;
294
+ }
295
+ return result;
296
+ }
297
+ /**
298
+ * Compute a SHA-256 hash of the contract-relevant parts of a parsed spec.
299
+ * Excludes presentation fields (summary, description, tags, operationId)
300
+ * so that only structural API changes produce a different hash.
301
+ */
302
+ export function computeContractHash(spec) {
303
+ const contract = {
304
+ operations: spec.operations.map((op) => ({
305
+ method: op.method,
306
+ path: op.path,
307
+ pathParams: op.pathParams.map((p) => ({
308
+ name: p.name,
309
+ required: p.required,
310
+ schema: p.schema,
311
+ })),
312
+ queryParams: op.queryParams.map((p) => ({
313
+ name: p.name,
314
+ required: p.required,
315
+ schema: p.schema,
316
+ })),
317
+ headerParams: op.headerParams.map((p) => ({
318
+ name: p.name,
319
+ required: p.required,
320
+ schema: p.schema,
321
+ })),
322
+ requestBody: op.requestBody,
323
+ requestBodyRequired: op.requestBodyRequired,
324
+ responseSchema: op.responseSchema,
325
+ errorResponses: op.errorResponses,
326
+ })),
327
+ componentSchemas: spec.componentSchemas,
328
+ securitySchemes: spec.securitySchemes,
329
+ serverUrls: spec.serverUrls,
330
+ };
331
+ return createHash('sha256')
332
+ .update(JSON.stringify(contract))
333
+ .digest('hex')
334
+ .slice(0, 16);
335
+ }
336
+ function extractTagDescriptions(doc) {
337
+ const result = {};
338
+ if (Array.isArray(doc.tags)) {
339
+ for (const tag of doc.tags) {
340
+ if (tag.name && tag.description) {
341
+ result[tag.name] = tag.description;
342
+ }
343
+ }
344
+ }
345
+ return result;
346
+ }
@@ -0,0 +1 @@
1
+ export { type OpenAPISchema, type ZodCodegenContext, createContext, schemaToZod, schemaVarName, sanitizeTypeName, } from './openapi-to-zod-schema.js';
@@ -0,0 +1 @@
1
+ export { createContext, schemaToZod, schemaVarName, sanitizeTypeName, } from './openapi-to-zod-schema.js';
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@pikku/openapi-parser",
3
+ "version": "0.12.3",
4
+ "description": "OpenAPI spec parser and code generator for Pikku",
5
+ "author": "yasser.fadl@gmail.com",
6
+ "license": "MIT",
7
+ "module": "dist/index.js",
8
+ "main": "dist/index.js",
9
+ "type": "module",
10
+ "scripts": {
11
+ "tsc": "tsc",
12
+ "ncu": "npx npm-check-updates",
13
+ "build": "tsc -b",
14
+ "test": "node --import tsx --test src/**/*.test.ts",
15
+ "prepublishOnly": "yarn build"
16
+ },
17
+ "exports": {
18
+ ".": "./dist/index.js"
19
+ },
20
+ "dependencies": {
21
+ "yaml": "^2.7.1"
22
+ },
23
+ "devDependencies": {
24
+ "typescript": "^5.9"
25
+ }
26
+ }