@moccona/apicodegen 0.0.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.
package/bin/cli.cjs ADDED
@@ -0,0 +1,2137 @@
1
+ #!/bin/env node
2
+ "use strict";
3
+
4
+ // src/core/base/Adaptor.ts
5
+ var Adapter = class {
6
+ };
7
+
8
+ // src/core/constants/keywords.ts
9
+ var typescriptKeywords = /* @__PURE__ */ new Set([
10
+ "break",
11
+ "case",
12
+ "catch",
13
+ "class",
14
+ "const",
15
+ "continue",
16
+ "debugger",
17
+ "default",
18
+ "delete",
19
+ "do",
20
+ "else",
21
+ "enum",
22
+ "export",
23
+ "extends",
24
+ "false",
25
+ "finally",
26
+ "for",
27
+ "function",
28
+ "if",
29
+ "import",
30
+ "in",
31
+ "instanceof",
32
+ "new",
33
+ "null",
34
+ "return",
35
+ "super",
36
+ "switch",
37
+ "this",
38
+ "throw",
39
+ "true",
40
+ "try",
41
+ "typeof",
42
+ "var",
43
+ "void",
44
+ "while",
45
+ "with",
46
+ "as",
47
+ "implements",
48
+ "interface",
49
+ "let",
50
+ "package",
51
+ "private",
52
+ "protected",
53
+ "public",
54
+ "static",
55
+ "yield",
56
+ "abstract",
57
+ "any",
58
+ "async",
59
+ "await",
60
+ "constructor",
61
+ "declare",
62
+ "from",
63
+ "get",
64
+ "is",
65
+ "module",
66
+ "namespace",
67
+ "never",
68
+ "require",
69
+ "set",
70
+ "type",
71
+ "unknown",
72
+ "readonly",
73
+ "of",
74
+ "asserts",
75
+ "infer",
76
+ "keyof",
77
+ "boolean",
78
+ "number",
79
+ "string",
80
+ "symbol",
81
+ "object",
82
+ "undefined",
83
+ "bigint"
84
+ ]);
85
+
86
+ // src/core/interface.ts
87
+ var MediaTypes = /* @__PURE__ */ ((MediaTypes2) => {
88
+ MediaTypes2["JSON"] = "application/json";
89
+ MediaTypes2["TEXT"] = "text";
90
+ MediaTypes2["IMAGE"] = "image";
91
+ MediaTypes2["AUDIO"] = "audio";
92
+ MediaTypes2["VIDEO"] = "video";
93
+ return MediaTypes2;
94
+ })(MediaTypes || {});
95
+ var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
96
+ HttpMethods2["GET"] = "get";
97
+ HttpMethods2["PUT"] = "put";
98
+ HttpMethods2["POST"] = "post";
99
+ HttpMethods2["DELETE"] = "delete";
100
+ HttpMethods2["OPTIONS"] = "options";
101
+ HttpMethods2["HEAD"] = "head";
102
+ HttpMethods2["PATCH"] = "patch";
103
+ HttpMethods2["TRACE"] = "trace";
104
+ return HttpMethods2;
105
+ })(HttpMethods || {});
106
+
107
+ // src/core/base/Base.ts
108
+ var import_undici = require("undici");
109
+ var Base = class _Base {
110
+ constructor() {
111
+ if (new.target === _Base) {
112
+ throw new Error("Cannot instantiate abstract class");
113
+ }
114
+ }
115
+ /**
116
+ * Converts a reference string to a meaningful name.
117
+ * @param ref - The reference string to process.
118
+ * @param [doc] - Optional document reference for context.
119
+ * @returns - The processed name.
120
+ */
121
+ static ref2name(ref, doc) {
122
+ const paths = ref.replace(/^#/, "").split("/").filter(Boolean);
123
+ if (!doc) {
124
+ return paths.slice(-1)[0];
125
+ }
126
+ let temporary = doc;
127
+ let lastPath = "";
128
+ for (const path of paths) {
129
+ const adjustedPath = path.replaceAll("~1", "/");
130
+ temporary = temporary[adjustedPath];
131
+ lastPath = adjustedPath;
132
+ }
133
+ if (!temporary) {
134
+ return "unknown";
135
+ }
136
+ return temporary.$ref ? this.ref2name(temporary.$ref, doc) : lastPath;
137
+ }
138
+ /**
139
+ * Converts an API path to a function name.
140
+ * @param path - The API endpoint path.
141
+ * @param [method] - The HTTP method (e.g., GET, POST).
142
+ * @param [operationId] - Unique identifier for the operation.
143
+ * @returns - The generated function name.
144
+ */
145
+ static pathToFnName(path, method, operationId) {
146
+ const name = this.camelCase(this.normalize(path));
147
+ const suffix = method ? this.capitalize(this.upperCamelCase(`using_${method}`)) : "";
148
+ return (operationId ? this.camelCase(this.normalize(operationId)) : name) + suffix;
149
+ }
150
+ /**
151
+ * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
152
+ * @param text - Input text to normalize.
153
+ * @returns - The normalized string.
154
+ */
155
+ static normalize(text) {
156
+ if (typescriptKeywords.has(text)) {
157
+ text += "_";
158
+ }
159
+ return text.replace(/[/\-_{}():\s`,*<>$]/gm, "_").replaceAll("...", "");
160
+ }
161
+ /**
162
+ * Capitalizes the first character of a string.
163
+ * @param text - Input string.
164
+ * @returns - Capitalized string.
165
+ */
166
+ static capitalize(text) {
167
+ text = text.trim();
168
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
169
+ }
170
+ /**
171
+ * Converts a string to camelCase.
172
+ * @param text - Input string.
173
+ * @returns - CamelCase string.
174
+ */
175
+ static camelCase(text) {
176
+ text = text.trim();
177
+ return text.split("_").filter(Boolean).map((t4, index) => index === 0 ? t4 : this.capitalize(t4)).join("");
178
+ }
179
+ /**
180
+ * Converts a string to UpperCamelCase.
181
+ * @param text - Input string.
182
+ * @returns - UpperCamelCase string.
183
+ */
184
+ static upperCamelCase(text) {
185
+ return this.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(this.capitalize).join("");
186
+ }
187
+ /**
188
+ * Fetches documentation from a given URL.
189
+ * @param url - The URL to fetch the documentation from.
190
+ * @param requestInit - Additional request parameters.
191
+ * @returns - A promise resolving to the fetched documentation data.
192
+ */
193
+ static async fetchDoc(url, requestInit = {}) {
194
+ const agent = new import_undici.Agent({
195
+ connect: {
196
+ rejectUnauthorized: false
197
+ }
198
+ });
199
+ try {
200
+ const { body } = await (0, import_undici.request)(url, {
201
+ method: "GET",
202
+ dispatcher: agent,
203
+ ...requestInit
204
+ });
205
+ return body.json();
206
+ } catch (error) {
207
+ throw error;
208
+ }
209
+ }
210
+ /**
211
+ * Determines the media type from a given media type string.
212
+ * @param mediaType - The media type string to evaluate.
213
+ * @returns - The matched MediaTypes or null.
214
+ */
215
+ static getMediaType(mediaType) {
216
+ for (const type in Object.values(MediaTypes)) {
217
+ if (new RegExp(type).test(mediaType)) {
218
+ return type;
219
+ }
220
+ }
221
+ return;
222
+ }
223
+ /**
224
+ * Checks if a schema is a valid enum type that isn't boolean.
225
+ * @param a - The schema object to evaluate.
226
+ * @returns - True if the schema is a valid non-boolean enum.
227
+ */
228
+ static isValidEnumType(a) {
229
+ return a.type !== "boolean" && !this.isBooleanEnum(a);
230
+ }
231
+ /**
232
+ * Checks if a schema represents a boolean enum.
233
+ * @param a - The schema object to evaluate.
234
+ * @returns - True if the schema is a boolean enum.
235
+ */
236
+ static isBooleanEnum(a) {
237
+ return a.type === "boolean" || !!a.enum?.some(
238
+ (member) => typeof member === "boolean"
239
+ );
240
+ }
241
+ /**
242
+ * Checks if two enum schemas are identical.
243
+ * @param a - First enum schema to compare.
244
+ * @param b - Second enum schema to compare.
245
+ * @returns - True if the enums are identical.
246
+ */
247
+ static isSameEnum(a, b) {
248
+ return a.enum.length === b.enum.length && a.enum.sort().every((v, index) => v === b.enum.sort()[index]);
249
+ }
250
+ /**
251
+ * Filters out duplicate enum schemas from an array.
252
+ * @param enums - Array of enum schemas to process.
253
+ * @returns - Array of unique enum schemas.
254
+ */
255
+ static uniqueEnums(enums) {
256
+ const uniqueEnums_ = [];
257
+ for (const enumObject of enums) {
258
+ if (uniqueEnums_.length === 0) {
259
+ uniqueEnums_.push(enumObject);
260
+ } else {
261
+ if (!uniqueEnums_.some((a) => this.isSameEnum(a, enumObject))) {
262
+ uniqueEnums_.push(enumObject);
263
+ }
264
+ }
265
+ }
266
+ return uniqueEnums_;
267
+ }
268
+ /**
269
+ * Finds the first occurrence of a matching enum schema in an array.
270
+ * @param a - The enum schema to find.
271
+ * @param enums - Array of enum schemas to search.
272
+ * @returns - The found schema or undefined.
273
+ */
274
+ static findSameSchema(a, enums) {
275
+ return enums.find((b) => this.isSameEnum(b, a));
276
+ }
277
+ /**
278
+ * Checks if an object is a reference object.
279
+ * @param schema - The object to check.
280
+ * @returns - True if the object is a reference.
281
+ */
282
+ static isRef(schema) {
283
+ return "$ref" in schema && typeof schema.$ref === "string";
284
+ }
285
+ };
286
+
287
+ // src/core/base/Provider.ts
288
+ var Provider = class {
289
+ /** collection of enum schemas */
290
+ enums = [];
291
+ /** collection of schemas indexed by name */
292
+ schemas = {};
293
+ /** collection of parameters indexed by name */
294
+ parameters = {};
295
+ /** collection of API responses indexed by name */
296
+ responses = {};
297
+ /** collection of request bodies indexed by name */
298
+ requestBodies = {};
299
+ /** collection of API endpoints (operations) indexed by path */
300
+ apis = {};
301
+ /** URL for fetching API documentation */
302
+ docURL;
303
+ /** base URL for API endpoints */
304
+ baseURL;
305
+ /** output directory for generated code */
306
+ output;
307
+ /** request options for API documentation fetch */
308
+ requestOptions;
309
+ /** source path for imported client */
310
+ importClientSource;
311
+ /**
312
+ * Provider Constructor.
313
+ * @param {ProviderInitOptions} initOptions - Initial configuration for the provider.
314
+ * @param {unknown} doc - Raw API documentation data to be parsed.
315
+ */
316
+ constructor(initOptions, doc) {
317
+ this.docURL = initOptions.docURL;
318
+ this.baseURL = initOptions.baseURL ?? "";
319
+ this.output = initOptions.output ?? ".";
320
+ this.requestOptions = initOptions.requestOptions ?? {};
321
+ this.importClientSource = initOptions.importClientSource ?? "";
322
+ const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
323
+ this.enums = enums;
324
+ this.schemas = schemas;
325
+ this.responses = responses;
326
+ this.parameters = parameters;
327
+ this.requestBodies = requestBodies;
328
+ this.apis = apis;
329
+ }
330
+ };
331
+
332
+ // src/core/generator/index.ts
333
+ var import_promises = require("fs/promises");
334
+ var import_prettier = require("prettier");
335
+ var import_typescript = require("typescript");
336
+ var Generator = class _Generator {
337
+ /**
338
+ * Converts an array of TypeScript statements into a formatted string of code.
339
+ *
340
+ * @param statements - The array of TypeScript statement nodes.
341
+ * @returns Formatted code as a string.
342
+ * @throws {Error} If no valid statements are provided.
343
+ */
344
+ static toCode(statements) {
345
+ if (statements.length === 0) {
346
+ return "// No api declaration found.";
347
+ }
348
+ const sourceFile = import_typescript.factory.createSourceFile(
349
+ statements,
350
+ import_typescript.factory.createToken(import_typescript.SyntaxKind.EndOfFileToken),
351
+ import_typescript.NodeFlags.None
352
+ );
353
+ return (0, import_typescript.createPrinter)().printFile(sourceFile);
354
+ }
355
+ static async write(code, filepath) {
356
+ try {
357
+ await (0, import_promises.writeFile)(filepath, code);
358
+ } catch (error) {
359
+ console.error(error);
360
+ }
361
+ }
362
+ /**
363
+ * Converts a path string with parameters into a TypeScript template expression.
364
+ * Handles query parameters and path placeholders.
365
+ *
366
+ * @param path - The base path string containing placeholders.
367
+ * @param parameters - Array of parameter objects defining the parameters.
368
+ * @param basePath - Optional base path to prepend (default: "").
369
+ * @returns A TypeScript template expression node.
370
+ */
371
+ static toUrlTemplate(path, parameters, basePath = "") {
372
+ const queryParameters = parameters.filter(
373
+ (p) => p.in === "query" /* query */
374
+ );
375
+ if (queryParameters.length > 0) {
376
+ const queryString = queryParameters.map(
377
+ (qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${qp.name}}`
378
+ ).join("");
379
+ path += queryString;
380
+ }
381
+ const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
382
+ if (pathSegments.length === 1) {
383
+ return import_typescript.factory.createNoSubstitutionTemplateLiteral(basePath + path);
384
+ }
385
+ return import_typescript.factory.createTemplateExpression(
386
+ import_typescript.factory.createTemplateHead(basePath + pathSegments[0]),
387
+ pathSegments.slice(1).map((segment, index) => {
388
+ const match = /^{(.+)}(.+)?/gm.exec(segment);
389
+ const isLastSegment = index === pathSegments.length - 2;
390
+ if (!match) {
391
+ throw new Error(`Invalid path segment: ${segment}`);
392
+ }
393
+ return import_typescript.factory.createTemplateSpan(
394
+ import_typescript.factory.createIdentifier(match[1]),
395
+ !isLastSegment ? import_typescript.factory.createTemplateMiddle(match[2]) : import_typescript.factory.createTemplateTail(match[2] || "")
396
+ );
397
+ })
398
+ );
399
+ }
400
+ /**
401
+ * Adds synthetic comments to a TypeScript AST node.
402
+ *
403
+ * @param node - The target AST node.
404
+ * @param comments - Array of comment objects to add.
405
+ */
406
+ static addComments(node, comments) {
407
+ if (!Array.isArray(comments) || comments.filter(Boolean).length === 0)
408
+ return;
409
+ const formatComment = (comment) => {
410
+ return comment.tag ? ` @${comment.tag} ${comment.comment ?? ""}` : ` ${comment.comment}`;
411
+ };
412
+ const formattedComments = "*\n" + comments.map(formatComment).join("\n").trim() + "\n";
413
+ (0, import_typescript.addSyntheticLeadingComment)(
414
+ node,
415
+ import_typescript.SyntaxKind.MultiLineCommentTrivia,
416
+ formattedComments,
417
+ true
418
+ );
419
+ }
420
+ /**
421
+ * Checks if a schema represents a binary type.
422
+ *
423
+ * @param schema - The schema object to check.
424
+ * @returns true if the schema is a binary type, false otherwise.
425
+ */
426
+ static isBinarySchema(schema) {
427
+ if (schema.type === "array") {
428
+ const arraySchema = schema;
429
+ return this.isBinarySchema(arraySchema.items);
430
+ }
431
+ const nonArraySchema = schema;
432
+ return nonArraySchema.format === "blob" /* blob */ || nonArraySchema.format === "binary" /* binary */ || nonArraySchema.type === "file" /* file */;
433
+ }
434
+ static toRequestBodyTypeNode(schema) {
435
+ return import_typescript.factory.createParameterDeclaration(
436
+ void 0,
437
+ void 0,
438
+ import_typescript.factory.createIdentifier("req"),
439
+ void 0,
440
+ this.toTypeNode(schema)
441
+ );
442
+ }
443
+ static toTypeNode(schema) {
444
+ const { type, ref } = schema;
445
+ if (ref) {
446
+ const identify = Base.ref2name(ref);
447
+ return import_typescript.factory.createTypeReferenceNode(
448
+ import_typescript.factory.createIdentifier(
449
+ identify === "unknown" ? identify : Base.upperCamelCase(identify)
450
+ )
451
+ );
452
+ }
453
+ switch (type) {
454
+ case "array" /* array */:
455
+ const { items } = schema;
456
+ return import_typescript.factory.createArrayTypeNode(this.toTypeNode(items));
457
+ case "object" /* object */:
458
+ const propsCount = Object.keys(schema.properties ?? {}).length;
459
+ if (!schema.properties || propsCount === 0) {
460
+ return import_typescript.factory.createTypeReferenceNode(import_typescript.factory.createIdentifier("Record"), [
461
+ import_typescript.factory.createToken(import_typescript.SyntaxKind.StringKeyword),
462
+ import_typescript.factory.createToken(import_typescript.SyntaxKind.UnknownKeyword)
463
+ ]);
464
+ }
465
+ const props = Object.keys(schema.properties);
466
+ return import_typescript.factory.createTypeLiteralNode(
467
+ props.map((propKey) => {
468
+ const propSchema = schema.properties[propKey];
469
+ return import_typescript.factory.createPropertySignature(
470
+ void 0,
471
+ import_typescript.factory.createStringLiteral(propKey),
472
+ // When field is required, a refrence or binary value, don't add question mark.
473
+ schema.required || schema.ref || this.isBinarySchema(schema) ? void 0 : import_typescript.factory.createToken(import_typescript.SyntaxKind.QuestionToken),
474
+ this.toTypeNode(propSchema)
475
+ );
476
+ })
477
+ );
478
+ case "integer" /* integer */:
479
+ case "number" /* number */:
480
+ if (schema.enum) {
481
+ return import_typescript.factory.createUnionTypeNode(
482
+ schema.enum.map(
483
+ (e) => import_typescript.factory.createLiteralTypeNode(import_typescript.factory.createNumericLiteral(e))
484
+ )
485
+ );
486
+ }
487
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.NumberKeyword);
488
+ // case NonArraySchemaType.string:
489
+ case "boolean" /* boolean */:
490
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.BooleanKeyword);
491
+ case "file" /* file */:
492
+ return import_typescript.factory.createTypeReferenceNode(import_typescript.factory.createIdentifier("File"));
493
+ default:
494
+ const {
495
+ format: format2,
496
+ oneOf,
497
+ allOf,
498
+ anyOf,
499
+ type: type2,
500
+ enum: enum_
501
+ } = schema;
502
+ switch (format2) {
503
+ case "number" /* number */:
504
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.NumberKeyword);
505
+ case "string" /* string */:
506
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.StringKeyword);
507
+ case "boolean" /* boolean */:
508
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.BooleanKeyword);
509
+ case "blob" /* blob */:
510
+ case "binary" /* binary */:
511
+ return import_typescript.factory.createTypeReferenceNode(import_typescript.factory.createIdentifier("File"));
512
+ default:
513
+ }
514
+ if (enum_) {
515
+ return import_typescript.factory.createUnionTypeNode(
516
+ enum_.map(
517
+ (e) => import_typescript.factory.createLiteralTypeNode(import_typescript.factory.createStringLiteral(e))
518
+ )
519
+ );
520
+ }
521
+ if (type2 === "string" /* string */) {
522
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.StringKeyword);
523
+ }
524
+ if (oneOf) {
525
+ return import_typescript.factory.createUnionTypeNode(
526
+ oneOf.map((schema2) => this.toTypeNode(schema2))
527
+ );
528
+ }
529
+ if (anyOf) {
530
+ return import_typescript.factory.createUnionTypeNode(
531
+ anyOf.map((schema2) => this.toTypeNode(schema2))
532
+ );
533
+ }
534
+ if (allOf) {
535
+ return import_typescript.factory.createUnionTypeNode(
536
+ allOf.map((schema2) => this.toTypeNode(schema2))
537
+ );
538
+ }
539
+ if (type2 && typeof type2 === "string") {
540
+ return import_typescript.factory.createTypeReferenceNode(
541
+ type2 !== "unknown" ? import_typescript.factory.createIdentifier(Base.upperCamelCase(type2)) : type2
542
+ );
543
+ }
544
+ }
545
+ return import_typescript.factory.createToken(import_typescript.SyntaxKind.UnknownKeyword);
546
+ }
547
+ static toDeclarationNode(parameters) {
548
+ const objectElements = [];
549
+ const typeObjectElements = [];
550
+ for (const parameter of parameters) {
551
+ if (parameter.ref) {
552
+ import_typescript.factory.createParameterDeclaration(
553
+ void 0,
554
+ void 0,
555
+ import_typescript.factory.createIdentifier(
556
+ Base.camelCase(Base.normalize(Base.ref2name(parameter.ref)))
557
+ ),
558
+ void 0,
559
+ import_typescript.factory.createTypeReferenceNode(
560
+ import_typescript.factory.createIdentifier(
561
+ Base.upperCamelCase(Base.normalize(Base.ref2name(parameter.ref)))
562
+ )
563
+ ),
564
+ void 0
565
+ );
566
+ } else {
567
+ const { name, schema, required } = parameter;
568
+ objectElements.push(
569
+ import_typescript.factory.createBindingElement(
570
+ void 0,
571
+ void 0,
572
+ import_typescript.factory.createIdentifier(Base.camelCase(Base.normalize(name)))
573
+ )
574
+ );
575
+ typeObjectElements.push(
576
+ import_typescript.factory.createPropertySignature(
577
+ [],
578
+ import_typescript.factory.createIdentifier(Base.camelCase(Base.normalize(name))),
579
+ required ? void 0 : import_typescript.factory.createToken(import_typescript.SyntaxKind.QuestionToken),
580
+ !schema ? import_typescript.factory.createToken(import_typescript.SyntaxKind.UnknownKeyword) : this.toTypeNode(schema)
581
+ )
582
+ );
583
+ }
584
+ }
585
+ return import_typescript.factory.createParameterDeclaration(
586
+ void 0,
587
+ void 0,
588
+ import_typescript.factory.createObjectBindingPattern(objectElements),
589
+ void 0,
590
+ import_typescript.factory.createTypeLiteralNode(typeObjectElements),
591
+ void 0
592
+ );
593
+ }
594
+ static toFormDataStatement(parameters, requestBody) {
595
+ const statements = [];
596
+ const fdDeclaration = import_typescript.factory.createVariableStatement(
597
+ void 0,
598
+ import_typescript.factory.createVariableDeclarationList(
599
+ [
600
+ import_typescript.factory.createVariableDeclaration(
601
+ import_typescript.factory.createIdentifier("fd"),
602
+ void 0,
603
+ void 0,
604
+ import_typescript.factory.createNewExpression(
605
+ import_typescript.factory.createIdentifier("FormData"),
606
+ void 0,
607
+ []
608
+ )
609
+ )
610
+ ],
611
+ import_typescript.NodeFlags.Const
612
+ )
613
+ );
614
+ statements.push(fdDeclaration);
615
+ parameters.filter(
616
+ (parameter) => parameter.ref !== void 0 && (parameter.in === "formData" /* formData */ || parameter.schema && this.isBinarySchema(parameter.schema))
617
+ ).forEach((parameter) => {
618
+ statements.push(
619
+ import_typescript.factory.createExpressionStatement(
620
+ import_typescript.factory.createBinaryExpression(
621
+ import_typescript.factory.createElementAccessExpression(
622
+ import_typescript.factory.createIdentifier("req"),
623
+ import_typescript.factory.createStringLiteral(parameter.name)
624
+ ),
625
+ import_typescript.factory.createToken(import_typescript.SyntaxKind.AmpersandAmpersandToken),
626
+ import_typescript.factory.createCallExpression(
627
+ import_typescript.factory.createPropertyAccessExpression(
628
+ import_typescript.factory.createIdentifier("fd"),
629
+ import_typescript.factory.createIdentifier("append")
630
+ ),
631
+ void 0,
632
+ [
633
+ import_typescript.factory.createStringLiteral(parameter.name),
634
+ import_typescript.factory.createIdentifier(parameter.name)
635
+ ]
636
+ )
637
+ )
638
+ )
639
+ );
640
+ });
641
+ if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
642
+ Object.keys(requestBody.properties).forEach((key) => {
643
+ const schemaByKey = requestBody.properties[key];
644
+ if (schemaByKey.type === "array" /* array */ && this.isBinarySchema(schemaByKey)) {
645
+ statements.push(
646
+ import_typescript.factory.createForOfStatement(
647
+ void 0,
648
+ import_typescript.factory.createVariableDeclarationList(
649
+ [import_typescript.factory.createVariableDeclaration("file")],
650
+ import_typescript.NodeFlags.Const
651
+ ),
652
+ import_typescript.factory.createElementAccessExpression(
653
+ import_typescript.factory.createIdentifier("req"),
654
+ import_typescript.factory.createStringLiteral(key)
655
+ ),
656
+ import_typescript.factory.createBlock([
657
+ import_typescript.factory.createExpressionStatement(
658
+ import_typescript.factory.createCallExpression(
659
+ import_typescript.factory.createPropertyAccessExpression(
660
+ import_typescript.factory.createIdentifier("fd"),
661
+ import_typescript.factory.createIdentifier("append")
662
+ ),
663
+ [],
664
+ [
665
+ import_typescript.factory.createStringLiteral(key),
666
+ import_typescript.factory.createIdentifier("file"),
667
+ import_typescript.factory.createPropertyAccessExpression(
668
+ import_typescript.factory.createIdentifier("file"),
669
+ import_typescript.factory.createIdentifier("name")
670
+ )
671
+ ]
672
+ )
673
+ )
674
+ ])
675
+ )
676
+ );
677
+ } else {
678
+ if (schemaByKey.required) {
679
+ statements.push(
680
+ import_typescript.factory.createExpressionStatement(
681
+ import_typescript.factory.createCallExpression(
682
+ import_typescript.factory.createPropertyAccessExpression(
683
+ import_typescript.factory.createIdentifier("fd"),
684
+ import_typescript.factory.createIdentifier("append")
685
+ ),
686
+ void 0,
687
+ [
688
+ import_typescript.factory.createStringLiteral(key),
689
+ schemaByKey.type === "string" ? import_typescript.factory.createElementAccessExpression(
690
+ import_typescript.factory.createIdentifier("req"),
691
+ import_typescript.factory.createStringLiteral(key)
692
+ ) : import_typescript.factory.createCallExpression(
693
+ import_typescript.factory.createIdentifier("String"),
694
+ void 0,
695
+ [
696
+ import_typescript.factory.createElementAccessExpression(
697
+ import_typescript.factory.createIdentifier("req"),
698
+ import_typescript.factory.createStringLiteral(key)
699
+ )
700
+ ]
701
+ )
702
+ ]
703
+ )
704
+ )
705
+ );
706
+ } else {
707
+ statements.push(
708
+ import_typescript.factory.createExpressionStatement(
709
+ import_typescript.factory.createBinaryExpression(
710
+ import_typescript.factory.createElementAccessExpression(
711
+ import_typescript.factory.createIdentifier("req"),
712
+ import_typescript.factory.createStringLiteral(key)
713
+ ),
714
+ import_typescript.factory.createToken(import_typescript.SyntaxKind.AmpersandAmpersandToken),
715
+ import_typescript.factory.createCallExpression(
716
+ import_typescript.factory.createPropertyAccessExpression(
717
+ import_typescript.factory.createIdentifier("fd"),
718
+ import_typescript.factory.createIdentifier("append")
719
+ ),
720
+ void 0,
721
+ [
722
+ import_typescript.factory.createStringLiteral(key),
723
+ schemaByKey.type === "string" ? import_typescript.factory.createElementAccessExpression(
724
+ import_typescript.factory.createIdentifier("req"),
725
+ import_typescript.factory.createStringLiteral(key)
726
+ ) : import_typescript.factory.createCallExpression(
727
+ import_typescript.factory.createIdentifier("String"),
728
+ void 0,
729
+ [
730
+ import_typescript.factory.createElementAccessExpression(
731
+ import_typescript.factory.createIdentifier("req"),
732
+ import_typescript.factory.createStringLiteral(key)
733
+ )
734
+ ]
735
+ )
736
+ ]
737
+ )
738
+ )
739
+ )
740
+ );
741
+ }
742
+ }
743
+ });
744
+ }
745
+ return statements;
746
+ }
747
+ static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
748
+ const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(
749
+ requestBody.type
750
+ );
751
+ const shouldParseResponseToJSON = "application/json" === response?.type;
752
+ const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" /* array */ && this.isBinarySchema(requestBody.schema);
753
+ const inFormDataParameters = parameters.filter(
754
+ (p) => p.in === "formData" /* formData */
755
+ );
756
+ const notInFormDataParameters = parameters.filter(
757
+ (p) => p.in !== "formData" /* formData */
758
+ );
759
+ const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema.properties).some(
760
+ (p) => this.isBinarySchema(p)
761
+ );
762
+ const hasBinaryInParameters = parameters.some(
763
+ (p) => p?.schema && this.isBinarySchema(p.schema)
764
+ );
765
+ const shouldPutParametersOrBodyInFormData = isFormDataRequest || isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || inFormDataParameters.length > 0;
766
+ return import_typescript.factory.createBlock([
767
+ ...shouldPutParametersOrBodyInFormData ? this.toFormDataStatement(inFormDataParameters, requestBody?.schema) : [],
768
+ ...adapter.client(
769
+ uri,
770
+ method,
771
+ notInFormDataParameters,
772
+ requestBody,
773
+ response,
774
+ adapter,
775
+ shouldPutParametersOrBodyInFormData,
776
+ shouldParseResponseToJSON
777
+ )
778
+ ]);
779
+ }
780
+ static schemaToStatemets(parsedDoc, adaptor, options) {
781
+ const statements = [];
782
+ const { apis, schemas = {}, enums } = parsedDoc;
783
+ const enumNames = [];
784
+ for (const enumObject of enums) {
785
+ enumNames.push(Base.capitalize(enumObject.name));
786
+ statements.push(
787
+ import_typescript.factory.createEnumDeclaration(
788
+ [import_typescript.factory.createToken(import_typescript.SyntaxKind.ExportKeyword)],
789
+ import_typescript.factory.createIdentifier(Base.upperCamelCase(enumObject.name)),
790
+ enumObject.enum.map((member) => {
791
+ return import_typescript.factory.createEnumMember(
792
+ import_typescript.factory.createStringLiteral(
793
+ typeof member === "string" ? member : `${member}_`
794
+ ),
795
+ typeof member === "string" ? import_typescript.factory.createStringLiteral(member) : import_typescript.factory.createNumericLiteral(member)
796
+ );
797
+ })
798
+ )
799
+ );
800
+ }
801
+ for (const schemaKey in schemas) {
802
+ if (Object.hasOwnProperty.call(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
803
+ const schema = schemas[schemaKey];
804
+ statements.push(
805
+ import_typescript.factory.createTypeAliasDeclaration(
806
+ [import_typescript.factory.createModifier(import_typescript.SyntaxKind.ExportKeyword)],
807
+ import_typescript.factory.createIdentifier(Base.upperCamelCase(schemaKey)),
808
+ void 0,
809
+ this.toTypeNode(schema)
810
+ )
811
+ );
812
+ }
813
+ }
814
+ for (const uri in apis) {
815
+ const operations = apis[uri];
816
+ for (const operation of operations) {
817
+ const {
818
+ method,
819
+ operationId,
820
+ requestBody = [],
821
+ responses = [],
822
+ summary,
823
+ deprecated,
824
+ description
825
+ } = operation;
826
+ let { parameters = [] } = operation;
827
+ parameters = parameters.filter((p) => p.in !== "cookie");
828
+ if (requestBody.length === 0) {
829
+ requestBody.push({ type: "application/json" /* JSON */ });
830
+ }
831
+ const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
832
+ for (const req of requestBody) {
833
+ const statement = import_typescript.factory.createFunctionDeclaration(
834
+ [
835
+ import_typescript.factory.createModifier(import_typescript.SyntaxKind.ExportKeyword),
836
+ import_typescript.factory.createModifier(import_typescript.SyntaxKind.AsyncKeyword)
837
+ ],
838
+ void 0,
839
+ Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.capitalize(req.type.split("/")[1]) : ""),
840
+ void 0,
841
+ [
842
+ parameters.length > 0 ? _Generator.toDeclarationNode(parameters) : void 0,
843
+ req?.schema ? _Generator.toRequestBodyTypeNode(req.schema) : void 0
844
+ ].filter(Boolean),
845
+ void 0,
846
+ this.bodyBlock(
847
+ options.baseURL + uri,
848
+ method,
849
+ parameters,
850
+ req,
851
+ responses[0],
852
+ adaptor
853
+ )
854
+ );
855
+ this.addComments(
856
+ statement,
857
+ [
858
+ description && {
859
+ comment: description
860
+ },
861
+ summary && {
862
+ comment: summary
863
+ },
864
+ deprecated && {
865
+ tag: "deprecated"
866
+ }
867
+ ].filter(Boolean)
868
+ );
869
+ statements.push(statement);
870
+ }
871
+ }
872
+ }
873
+ return statements;
874
+ }
875
+ static async prettier(code) {
876
+ return await (0, import_prettier.format)(code, {
877
+ parser: "typescript"
878
+ });
879
+ }
880
+ static async genCode(schema, initOptions, adaptor) {
881
+ const { importClientSource } = initOptions;
882
+ const statements = this.schemaToStatemets(schema, adaptor, {
883
+ baseURL: initOptions.baseURL ?? ""
884
+ });
885
+ let code = this.toCode(statements);
886
+ if (importClientSource) {
887
+ code = importClientSource + "\n\n" + code;
888
+ }
889
+ return await this.prettier(code);
890
+ }
891
+ };
892
+
893
+ // src/core/client/axios.ts
894
+ var import_typescript2 = require("typescript");
895
+ var AxiosAdapter = class extends Adapter {
896
+ /**
897
+ * Name of the field used to specify the HTTP method in the request configuration.
898
+ */
899
+ methodFieldName = "method";
900
+ /**
901
+ * Name of the field used to specify the request body (data) in the request configuration.
902
+ */
903
+ bodyFieldName = "data";
904
+ /**
905
+ * Name of the field used to specify the request headers in the request configuration.
906
+ */
907
+ headersFieldName = "headers";
908
+ /**
909
+ * Name of the field used to specify the query parameters in the request configuration.
910
+ */
911
+ queryFieldName = "params";
912
+ /**
913
+ * The name of the client this adapter is configured for, which is 'axios' in this case.
914
+ */
915
+ name = "axios";
916
+ /**
917
+ * Method that should generate and return the client-specific configuration statements.
918
+ *
919
+ * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
920
+ *
921
+ * @throws {Error} Indicates that the method is not yet implemented and needs to be filled in.
922
+ */
923
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData) {
924
+ const statements = [];
925
+ const inBody = parameters.filter((p) => !p.in || p.in === "body");
926
+ const inHeader = parameters.filter((p) => p.in === "header");
927
+ const toLiterlExpression = () => {
928
+ return import_typescript2.factory.createObjectLiteralExpression(
929
+ [
930
+ // Set the HTTP method
931
+ import_typescript2.factory.createPropertyAssignment(
932
+ import_typescript2.factory.createIdentifier(adapter.methodFieldName),
933
+ import_typescript2.factory.createStringLiteral(method.toUpperCase())
934
+ )
935
+ ].concat(
936
+ // Add headers if there are any
937
+ inHeader.length > 0 ? import_typescript2.factory.createPropertyAssignment(
938
+ import_typescript2.factory.createIdentifier(adapter.headersFieldName),
939
+ import_typescript2.factory.createObjectLiteralExpression(
940
+ inHeader.map(
941
+ (p) => import_typescript2.factory.createPropertyAssignment(
942
+ import_typescript2.factory.createStringLiteral(p.name),
943
+ import_typescript2.factory.createCallExpression(
944
+ import_typescript2.factory.createIdentifier("encodeURIComponent"),
945
+ void 0,
946
+ [
947
+ import_typescript2.factory.createCallExpression(
948
+ import_typescript2.factory.createIdentifier("String"),
949
+ void 0,
950
+ [
951
+ import_typescript2.factory.createIdentifier(
952
+ Base.camelCase(Base.normalize(p.name))
953
+ )
954
+ ]
955
+ )
956
+ ]
957
+ )
958
+ )
959
+ )
960
+ )
961
+ ) : []
962
+ ).concat(
963
+ // Add body if needed
964
+ shouldUseFormData || inBody.length > 0 || requestBody?.schema ? import_typescript2.factory.createPropertyAssignment(
965
+ import_typescript2.factory.createIdentifier(adapter.bodyFieldName),
966
+ shouldUseFormData ? import_typescript2.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? import_typescript2.factory.createIdentifier("req") : import_typescript2.factory.createIdentifier("req")
967
+ ) : []
968
+ ),
969
+ true
970
+ );
971
+ };
972
+ statements.push(
973
+ import_typescript2.factory.createReturnStatement(
974
+ import_typescript2.factory.createCallExpression(
975
+ import_typescript2.factory.createIdentifier(adapter.name),
976
+ response?.schema ? [
977
+ Generator.toTypeNode(
978
+ response.schema
979
+ )
980
+ ] : void 0,
981
+ [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]
982
+ )
983
+ )
984
+ );
985
+ return statements;
986
+ }
987
+ };
988
+
989
+ // src/core/client/fetch.ts
990
+ var import_typescript3 = require("typescript");
991
+ var FetchAdapter = class extends Adapter {
992
+ methodFieldName = "method";
993
+ bodyFieldName = "body";
994
+ headersFieldName = "headers";
995
+ queryFieldName = "";
996
+ name = "fetch";
997
+ /**
998
+ * Generates client code for making API requests using the Fetch API.
999
+ * @param uri - The API endpoint URI
1000
+ * @param method - The HTTP method (GET, POST, etc.)
1001
+ * @param parameters - Array of parameters to include in the request
1002
+ * @param requestBody - The request body media type definition
1003
+ * @param response - The response media type definition
1004
+ * @param adapter - The adapter instance
1005
+ * @param shouldUseFormData - Flag to use FormData for the request body
1006
+ * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1007
+ * @return - An array of generated TypeScript statements
1008
+ */
1009
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse) {
1010
+ const statements = [];
1011
+ const inBody = parameters.filter((p) => !p.in || p.in === "body");
1012
+ const inHeader = parameters.filter((p) => p.in === "header");
1013
+ const toLiterlExpression = () => {
1014
+ return import_typescript3.factory.createObjectLiteralExpression(
1015
+ [
1016
+ // Set the HTTP method
1017
+ import_typescript3.factory.createPropertyAssignment(
1018
+ import_typescript3.factory.createIdentifier(adapter.methodFieldName),
1019
+ import_typescript3.factory.createStringLiteral(method.toUpperCase())
1020
+ )
1021
+ ].concat(
1022
+ // Add headers if there are any
1023
+ inHeader.length > 0 ? import_typescript3.factory.createPropertyAssignment(
1024
+ import_typescript3.factory.createIdentifier(adapter.headersFieldName),
1025
+ import_typescript3.factory.createObjectLiteralExpression(
1026
+ inHeader.map(
1027
+ (p) => import_typescript3.factory.createPropertyAssignment(
1028
+ import_typescript3.factory.createStringLiteral(p.name),
1029
+ import_typescript3.factory.createCallExpression(
1030
+ import_typescript3.factory.createIdentifier("encodeURIComponent"),
1031
+ void 0,
1032
+ [
1033
+ import_typescript3.factory.createCallExpression(
1034
+ import_typescript3.factory.createIdentifier("String"),
1035
+ void 0,
1036
+ [
1037
+ import_typescript3.factory.createIdentifier(
1038
+ Base.camelCase(Base.normalize(p.name))
1039
+ )
1040
+ ]
1041
+ )
1042
+ ]
1043
+ )
1044
+ )
1045
+ )
1046
+ )
1047
+ ) : []
1048
+ ).concat(
1049
+ // Add body if needed
1050
+ shouldUseFormData || inBody.length > 0 || requestBody?.schema ? import_typescript3.factory.createPropertyAssignment(
1051
+ import_typescript3.factory.createIdentifier(adapter.bodyFieldName),
1052
+ shouldUseFormData ? import_typescript3.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? import_typescript3.factory.createCallExpression(
1053
+ import_typescript3.factory.createPropertyAccessExpression(
1054
+ import_typescript3.factory.createIdentifier("JSON"),
1055
+ import_typescript3.factory.createIdentifier("stringify")
1056
+ ),
1057
+ [],
1058
+ [
1059
+ requestBody ? import_typescript3.factory.createIdentifier("req") : import_typescript3.factory.createObjectLiteralExpression(
1060
+ inBody.map(
1061
+ (b) => import_typescript3.factory.createShorthandPropertyAssignment(
1062
+ import_typescript3.factory.createIdentifier(b.name)
1063
+ )
1064
+ ),
1065
+ true
1066
+ )
1067
+ ]
1068
+ ) : (
1069
+ // One File parameter
1070
+ import_typescript3.factory.createIdentifier("req")
1071
+ )
1072
+ ) : []
1073
+ ),
1074
+ true
1075
+ );
1076
+ };
1077
+ statements.push(
1078
+ import_typescript3.factory.createReturnStatement(
1079
+ shouldUseJSONResponse ? (
1080
+ // Handle JSON response with proper type checking
1081
+ import_typescript3.factory.createCallExpression(
1082
+ import_typescript3.factory.createPropertyAccessExpression(
1083
+ import_typescript3.factory.createCallExpression(
1084
+ import_typescript3.factory.createIdentifier(adapter.name),
1085
+ void 0,
1086
+ [
1087
+ Generator.toUrlTemplate(uri, parameters),
1088
+ toLiterlExpression()
1089
+ ]
1090
+ ),
1091
+ import_typescript3.factory.createIdentifier("then")
1092
+ ),
1093
+ void 0,
1094
+ [
1095
+ import_typescript3.factory.createArrowFunction(
1096
+ [import_typescript3.factory.createModifier(import_typescript3.SyntaxKind.AsyncKeyword)],
1097
+ [],
1098
+ [
1099
+ import_typescript3.factory.createParameterDeclaration(
1100
+ void 0,
1101
+ void 0,
1102
+ import_typescript3.factory.createIdentifier("response")
1103
+ )
1104
+ ],
1105
+ void 0,
1106
+ import_typescript3.factory.createToken(import_typescript3.SyntaxKind.EqualsGreaterThanToken),
1107
+ import_typescript3.factory.createAsExpression(
1108
+ import_typescript3.factory.createParenthesizedExpression(
1109
+ import_typescript3.factory.createAwaitExpression(
1110
+ import_typescript3.factory.createCallExpression(
1111
+ import_typescript3.factory.createPropertyAccessExpression(
1112
+ import_typescript3.factory.createIdentifier("response"),
1113
+ import_typescript3.factory.createIdentifier("json")
1114
+ ),
1115
+ void 0,
1116
+ []
1117
+ )
1118
+ )
1119
+ ),
1120
+ response?.schema ? Generator.toTypeNode(response.schema) : import_typescript3.factory.createToken(import_typescript3.SyntaxKind.UnknownKeyword)
1121
+ )
1122
+ )
1123
+ ]
1124
+ )
1125
+ ) : (
1126
+ // Simple fetch call without JSON parsing
1127
+ import_typescript3.factory.createCallExpression(
1128
+ import_typescript3.factory.createIdentifier(adapter.name),
1129
+ void 0,
1130
+ [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]
1131
+ )
1132
+ )
1133
+ )
1134
+ );
1135
+ return statements;
1136
+ }
1137
+ };
1138
+
1139
+ // src/openapi/index.ts
1140
+ var import_logger = require("@moccona/logger");
1141
+
1142
+ // src/openapi/V2.ts
1143
+ var V2 = class {
1144
+ doc;
1145
+ constructor(doc) {
1146
+ this.doc = doc;
1147
+ }
1148
+ /**
1149
+ * Is array schema.
1150
+ */
1151
+ isOpenAPIArraySchema(schema) {
1152
+ return typeof schema === "object" && schema.type === "array";
1153
+ }
1154
+ /**
1155
+ * OpenAPI schema to base schema.
1156
+ */
1157
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1158
+ let refName = "";
1159
+ if (Base.isRef(schema)) {
1160
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1161
+ if (reserveRef) {
1162
+ return {
1163
+ type: upLevelSchemaKey + refName
1164
+ };
1165
+ }
1166
+ if (!this.doc.definitions) {
1167
+ this.doc.definitions = {};
1168
+ }
1169
+ schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
1170
+ }
1171
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1172
+ }
1173
+ /**
1174
+ * Transform all OpenAPI schema to Base Schema
1175
+ */
1176
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1177
+ if (!schema) {
1178
+ return {
1179
+ type: "unknown"
1180
+ };
1181
+ }
1182
+ if (Base.isRef(schema)) {
1183
+ return this.getSchemaByRef(schema, true);
1184
+ }
1185
+ if (this.isOpenAPIArraySchema(schema)) {
1186
+ const { type, description, items, required } = schema;
1187
+ return {
1188
+ type,
1189
+ required: !!required,
1190
+ description,
1191
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1192
+ };
1193
+ } else {
1194
+ const {
1195
+ required = [],
1196
+ allOf,
1197
+ anyOf,
1198
+ description,
1199
+ enum: enum_,
1200
+ format: format2,
1201
+ oneOf,
1202
+ properties = {}
1203
+ } = schema;
1204
+ let { type } = schema;
1205
+ if (enum_ && type !== "boolean") {
1206
+ const name = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(schemaKey);
1207
+ const enumObject = {
1208
+ name,
1209
+ enum: [...new Set(enum_)]
1210
+ };
1211
+ const sameObject = Base.findSameSchema(enumObject, enums);
1212
+ if (!sameObject && Base.isValidEnumType(schema)) {
1213
+ enums.push(enumObject);
1214
+ }
1215
+ return {
1216
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1217
+ required,
1218
+ description
1219
+ };
1220
+ }
1221
+ if (type === void 0 && Object.keys(properties).length > 0) {
1222
+ type = "object" /* object */;
1223
+ }
1224
+ return {
1225
+ type,
1226
+ required,
1227
+ description,
1228
+ enum: enum_,
1229
+ format: format2,
1230
+ allOf: allOf?.map(
1231
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1232
+ ),
1233
+ anyOf: anyOf?.map(
1234
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1235
+ ),
1236
+ oneOf: oneOf?.map(
1237
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1238
+ ),
1239
+ properties: Object.keys(properties).reduce((acc, p) => {
1240
+ const propSchema = properties[p];
1241
+ return {
1242
+ ...acc,
1243
+ [p]: Base.isRef(propSchema) ? {
1244
+ type: Base.upperCamelCase(
1245
+ Base.ref2name(propSchema.$ref, this.doc)
1246
+ )
1247
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1248
+ };
1249
+ }, {})
1250
+ };
1251
+ }
1252
+ }
1253
+ /**
1254
+ * OpenAPI parameter to base parameter.
1255
+ */
1256
+ getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1257
+ if (Base.isRef(parameter)) {
1258
+ parameter = this.doc.parameters[Base.ref2name(parameter.$ref, this.doc)];
1259
+ }
1260
+ const {
1261
+ name,
1262
+ required,
1263
+ description,
1264
+ type,
1265
+ items,
1266
+ enum: enum_,
1267
+ properties
1268
+ } = parameter;
1269
+ if (enum_) {
1270
+ const type2 = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(name);
1271
+ const enumSchema = {
1272
+ name: type2,
1273
+ enum: [...new Set(enum_)]
1274
+ };
1275
+ const sameEnum = Base.findSameSchema(enumSchema, enums);
1276
+ if (!sameEnum && Base.isValidEnumType({ type: type2, enum: enums })) {
1277
+ enums.push(enumSchema);
1278
+ }
1279
+ return {
1280
+ name,
1281
+ required,
1282
+ description,
1283
+ in: parameter.in,
1284
+ schema: {
1285
+ type: sameEnum?.name ?? type2
1286
+ }
1287
+ };
1288
+ }
1289
+ return {
1290
+ name,
1291
+ required,
1292
+ description,
1293
+ in: parameter.in,
1294
+ schema: items ? {
1295
+ type,
1296
+ items
1297
+ } : {
1298
+ type,
1299
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1300
+ properties
1301
+ }
1302
+ };
1303
+ }
1304
+ /**
1305
+ * OpenAPI schema to base response
1306
+ */
1307
+ getResponseByRef(schema) {
1308
+ if (Base.isRef(schema)) {
1309
+ schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1310
+ }
1311
+ const { schema: responseSchema } = schema;
1312
+ return [
1313
+ {
1314
+ type: "application/json" /* JSON */,
1315
+ schema: responseSchema && this.getSchemaByRef(responseSchema, true)
1316
+ }
1317
+ ];
1318
+ }
1319
+ init() {
1320
+ const { definitions = {}, responses = {}, paths = {} } = this.doc;
1321
+ const enums = [];
1322
+ const definitions_ = Object.keys(definitions).reduce((acc, key) => {
1323
+ const schema = definitions[key];
1324
+ return {
1325
+ ...acc,
1326
+ [key]: this.getSchemaByRef(schema, false, enums, key)
1327
+ };
1328
+ }, {});
1329
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1330
+ const response = responses[key];
1331
+ return {
1332
+ ...acc,
1333
+ [key]: this.getResponseByRef(response)
1334
+ };
1335
+ }, {});
1336
+ const apis = Object.keys(paths).reduce((acc, path) => {
1337
+ const pathObject = paths[path] ?? {};
1338
+ const { $ref } = pathObject;
1339
+ const methodApis = [];
1340
+ if ($ref) {
1341
+ } else {
1342
+ const { parameters = [] } = pathObject;
1343
+ Object.values(HttpMethods).forEach((method) => {
1344
+ const methodObject = pathObject[method];
1345
+ if (methodObject) {
1346
+ const {
1347
+ deprecated,
1348
+ operationId,
1349
+ summary: summary_,
1350
+ description: description_,
1351
+ responses: responses2 = {}
1352
+ } = methodObject;
1353
+ const { parameters: parameters_ = [] } = methodObject;
1354
+ const baseParameters = [...parameters, ...parameters_].map(
1355
+ (parameter) => this.getParameterByRef(parameter, enums)
1356
+ );
1357
+ const uniqueParameterName = [
1358
+ ...new Set(baseParameters.map((p) => p.name))
1359
+ ];
1360
+ if (Object.keys(responses2).length === 0) {
1361
+ Object.assign(responses2, {
1362
+ 200: {
1363
+ description: "Successful response"
1364
+ }
1365
+ });
1366
+ }
1367
+ const inBody = baseParameters.filter(
1368
+ (p) => p.in === "body" || p.in === "formData"
1369
+ );
1370
+ const notInBody = baseParameters.filter(
1371
+ (p) => p.in !== "body" && p.in !== "formData"
1372
+ );
1373
+ const httpCodes = Object.keys(responses2);
1374
+ for (const code of httpCodes) {
1375
+ if (code in responses2) {
1376
+ const response = responses2[code];
1377
+ const responseSchema = this.getResponseByRef(response);
1378
+ methodApis.push({
1379
+ method,
1380
+ operationId,
1381
+ summary: summary_,
1382
+ deprecated,
1383
+ description: description_,
1384
+ parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
1385
+ responses: responseSchema,
1386
+ requestBody: inBody.length > 0 ? [
1387
+ {
1388
+ type: "application/json" /* JSON */,
1389
+ schema: {
1390
+ type: "object" /* object */,
1391
+ properties: inBody.reduce((a, p) => {
1392
+ return {
1393
+ ...a,
1394
+ [p.name]: {
1395
+ type: p.schema?.type ?? "unknown",
1396
+ required: p.schema?.required,
1397
+ // @ts-expect-error items can be undefined
1398
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1399
+ items: p.schema?.items,
1400
+ description: p.schema?.description
1401
+ }
1402
+ };
1403
+ }, {})
1404
+ }
1405
+ }
1406
+ ] : void 0
1407
+ });
1408
+ break;
1409
+ }
1410
+ }
1411
+ }
1412
+ });
1413
+ }
1414
+ return {
1415
+ ...acc,
1416
+ [path]: methodApis
1417
+ };
1418
+ }, {});
1419
+ return {
1420
+ enums: Base.uniqueEnums(enums),
1421
+ schemas: definitions_,
1422
+ responses: responses_,
1423
+ parameters: {},
1424
+ requestBodies: {},
1425
+ apis
1426
+ };
1427
+ }
1428
+ };
1429
+
1430
+ // src/openapi/V3.ts
1431
+ var V3 = class {
1432
+ doc;
1433
+ constructor(doc) {
1434
+ this.doc = doc;
1435
+ }
1436
+ /**
1437
+ * Is array schema.
1438
+ */
1439
+ isOpenAPIArraySchema(schema) {
1440
+ return typeof schema === "object" && schema.type === "array";
1441
+ }
1442
+ /**
1443
+ * OpenAPI schema to base schema.
1444
+ */
1445
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1446
+ let refName = "";
1447
+ if (Base.isRef(schema)) {
1448
+ refName = Base.capitalize(Base.ref2name(schema.$ref));
1449
+ if (reserveRef) {
1450
+ return {
1451
+ type: upLevelSchemaKey + refName
1452
+ };
1453
+ }
1454
+ schema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1455
+ }
1456
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1457
+ }
1458
+ /**
1459
+ * OpenAPI parameter to base parameter.
1460
+ */
1461
+ getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1462
+ if (Base.isRef(schema)) {
1463
+ schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1464
+ }
1465
+ const {
1466
+ name,
1467
+ required,
1468
+ deprecated,
1469
+ description,
1470
+ schema: parameterSchema
1471
+ } = schema;
1472
+ if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1473
+ const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1474
+ const enumSchema = {
1475
+ name: type,
1476
+ enum: [...new Set(parameterSchema.enum)]
1477
+ };
1478
+ const sameEnum = Base.findSameSchema(enumSchema, enums);
1479
+ if (!sameEnum && Base.isValidEnumType(parameterSchema)) {
1480
+ enums.push(enumSchema);
1481
+ }
1482
+ return {
1483
+ name,
1484
+ required,
1485
+ description,
1486
+ deprecated,
1487
+ in: schema.in,
1488
+ schema: {
1489
+ type: sameEnum?.name ?? type
1490
+ }
1491
+ };
1492
+ }
1493
+ return {
1494
+ name,
1495
+ required,
1496
+ description,
1497
+ deprecated,
1498
+ in: schema.in,
1499
+ schema: schema.schema && this.getSchemaByRef(
1500
+ schema.schema,
1501
+ false,
1502
+ enums,
1503
+ upLevelSchemaKey + Base.capitalize(name)
1504
+ )
1505
+ };
1506
+ }
1507
+ /**
1508
+ * OpenAPI schema to base response
1509
+ */
1510
+ getResponseByRef(schema) {
1511
+ if (Base.isRef(schema)) {
1512
+ schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1513
+ }
1514
+ const { content = {} } = schema;
1515
+ return Object.keys(content).map((c) => ({
1516
+ type: c,
1517
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1518
+ }));
1519
+ }
1520
+ /**
1521
+ * OpenAPI schema to requestBody.
1522
+ */
1523
+ getRequestBodyByRef(schema, enums = []) {
1524
+ if (Base.isRef(schema)) {
1525
+ schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1526
+ }
1527
+ const { content = {} } = schema;
1528
+ return Object.keys(content).map((c) => ({
1529
+ type: c,
1530
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
1531
+ }));
1532
+ }
1533
+ /**
1534
+ * Transform all OpenAPI schema to Base Schema
1535
+ */
1536
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1537
+ if (!schema) {
1538
+ return {
1539
+ type: "unknown"
1540
+ };
1541
+ }
1542
+ if (Base.isRef(schema)) {
1543
+ return this.getSchemaByRef(schema, true);
1544
+ }
1545
+ if (this.isOpenAPIArraySchema(schema)) {
1546
+ const { type, description, items, required } = schema;
1547
+ return {
1548
+ type,
1549
+ required: !!required,
1550
+ description,
1551
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1552
+ };
1553
+ } else {
1554
+ const {
1555
+ required = [],
1556
+ allOf,
1557
+ anyOf,
1558
+ description,
1559
+ deprecated,
1560
+ enum: enum_,
1561
+ format: format2,
1562
+ oneOf,
1563
+ properties = {}
1564
+ } = schema;
1565
+ let { type } = schema;
1566
+ if (enum_ && type !== "boolean") {
1567
+ const name = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey));
1568
+ const enumObject = {
1569
+ name,
1570
+ enum: [...new Set(enum_)]
1571
+ };
1572
+ const sameObject = Base.findSameSchema(enumObject, enums);
1573
+ if (!sameObject && Base.isValidEnumType(schema)) {
1574
+ enums.push(enumObject);
1575
+ }
1576
+ return {
1577
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1578
+ required,
1579
+ description,
1580
+ deprecated
1581
+ };
1582
+ }
1583
+ if (type === void 0 && Object.keys(properties).length > 0) {
1584
+ type = "object" /* object */;
1585
+ }
1586
+ return {
1587
+ type,
1588
+ required,
1589
+ description,
1590
+ deprecated,
1591
+ enum: enum_,
1592
+ format: format2,
1593
+ allOf: allOf?.map(
1594
+ (s) => Base.isRef(s) ? { type: Base.capitalize(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1595
+ ),
1596
+ anyOf: anyOf?.map(
1597
+ (s) => Base.isRef(s) ? { type: Base.capitalize(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1598
+ ),
1599
+ oneOf: oneOf?.map(
1600
+ (s) => Base.isRef(s) ? { type: Base.capitalize(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1601
+ ),
1602
+ properties: Object.keys(properties).reduce((acc, p) => {
1603
+ const propSchema = properties[p];
1604
+ return {
1605
+ ...acc,
1606
+ [p]: Base.isRef(propSchema) ? {
1607
+ type: Base.capitalize(
1608
+ Base.ref2name(propSchema.$ref, this.doc)
1609
+ )
1610
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1611
+ };
1612
+ }, {})
1613
+ };
1614
+ }
1615
+ }
1616
+ init() {
1617
+ const { components = {}, paths = {} } = this.doc;
1618
+ const enums = [];
1619
+ const {
1620
+ requestBodies = {},
1621
+ responses = {},
1622
+ parameters = {},
1623
+ schemas = {}
1624
+ } = components;
1625
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1626
+ const schema = schemas[key];
1627
+ return {
1628
+ ...acc,
1629
+ [key]: this.getSchemaByRef(schema, false, enums, key)
1630
+ };
1631
+ }, {});
1632
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
1633
+ const parameter = parameters[key];
1634
+ return {
1635
+ ...acc,
1636
+ [key]: this.getParameterByRef(parameter, enums, key)
1637
+ };
1638
+ }, {});
1639
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1640
+ const response = responses[key];
1641
+ return {
1642
+ ...acc,
1643
+ [key]: this.getResponseByRef(response)
1644
+ };
1645
+ }, {});
1646
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
1647
+ const requestBody = requestBodies[key];
1648
+ return {
1649
+ ...acc,
1650
+ [key]: this.getRequestBodyByRef(requestBody, enums)
1651
+ };
1652
+ }, {});
1653
+ const apis = Object.keys(paths).reduce((acc, path) => {
1654
+ const pathObject = paths[path] ?? {};
1655
+ const { $ref } = pathObject;
1656
+ const methodApis = [];
1657
+ if ($ref) {
1658
+ } else {
1659
+ const { parameters: parameters2 = [], description, summary } = pathObject;
1660
+ Object.values(HttpMethods).forEach((method) => {
1661
+ const methodObject = pathObject[method];
1662
+ if (methodObject) {
1663
+ const {
1664
+ deprecated,
1665
+ operationId,
1666
+ responses: responses2 = {},
1667
+ summary: summary_,
1668
+ description: description_,
1669
+ requestBody = { content: {} }
1670
+ } = methodObject;
1671
+ const { parameters: parameters_2 = [] } = methodObject;
1672
+ const baseParameters = [...parameters2, ...parameters_2].map(
1673
+ (parameter) => this.getParameterByRef(parameter, enums)
1674
+ );
1675
+ const baseRequestBody = this.getRequestBodyByRef(
1676
+ requestBody,
1677
+ enums
1678
+ );
1679
+ const uniqueParameterName = [
1680
+ ...new Set(baseParameters.map((p) => p.name))
1681
+ ];
1682
+ if (Object.keys(responses2).length === 0) {
1683
+ Object.assign(responses2, {
1684
+ 200: {
1685
+ description: "Successful response"
1686
+ }
1687
+ });
1688
+ }
1689
+ const httpCodes = Object.keys(responses2);
1690
+ for (const code of httpCodes) {
1691
+ if (code in responses2) {
1692
+ const response = responses2[code];
1693
+ const responseSchema = this.getResponseByRef(response);
1694
+ methodApis.push({
1695
+ method,
1696
+ operationId,
1697
+ summary: summary_ ?? summary,
1698
+ description: description_ ?? description,
1699
+ deprecated,
1700
+ parameters: uniqueParameterName.map(
1701
+ (name) => baseParameters.find((p) => p.name === name)
1702
+ ),
1703
+ responses: responseSchema,
1704
+ requestBody: baseRequestBody
1705
+ });
1706
+ break;
1707
+ }
1708
+ }
1709
+ }
1710
+ });
1711
+ }
1712
+ return {
1713
+ ...acc,
1714
+ [path]: methodApis
1715
+ };
1716
+ }, {});
1717
+ return {
1718
+ enums: Base.uniqueEnums(enums),
1719
+ schemas: schemas_,
1720
+ responses: responses_,
1721
+ parameters: parameters_,
1722
+ requestBodies: requestBodies_,
1723
+ apis
1724
+ };
1725
+ }
1726
+ };
1727
+
1728
+ // src/openapi/V3_1.ts
1729
+ var V3_1 = class {
1730
+ doc;
1731
+ constructor(doc) {
1732
+ this.doc = doc;
1733
+ }
1734
+ /**
1735
+ * Is array schema.
1736
+ */
1737
+ isOpenAPIArraySchema(schema) {
1738
+ return typeof schema === "object" && schema.type === "array";
1739
+ }
1740
+ /**
1741
+ * OpenAPI schema to base schema.
1742
+ */
1743
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1744
+ let refName = "";
1745
+ if (Base.isRef(schema)) {
1746
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1747
+ if (reserveRef) {
1748
+ return {
1749
+ type: upLevelSchemaKey + refName
1750
+ };
1751
+ }
1752
+ if (!this.doc.components) {
1753
+ this.doc.components = {
1754
+ schemas: {}
1755
+ };
1756
+ }
1757
+ schema = this.doc.components.schemas[Base.ref2name(schema.$ref, this.doc)];
1758
+ }
1759
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1760
+ }
1761
+ /**
1762
+ * OpenAPI parameter to base parameter.
1763
+ */
1764
+ getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1765
+ if (Base.isRef(schema)) {
1766
+ schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1767
+ }
1768
+ const {
1769
+ name,
1770
+ required,
1771
+ deprecated,
1772
+ description,
1773
+ schema: parameterSchema
1774
+ } = schema;
1775
+ if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1776
+ const type = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(name);
1777
+ const enumSchema = {
1778
+ name: type,
1779
+ enum: [...new Set(parameterSchema.enum)]
1780
+ };
1781
+ const sameEnum = Base.findSameSchema(enumSchema, enums);
1782
+ if (!sameEnum && Base.isValidEnumType(parameterSchema)) {
1783
+ enums.push(enumSchema);
1784
+ }
1785
+ return {
1786
+ name,
1787
+ required,
1788
+ description,
1789
+ deprecated,
1790
+ in: schema.in,
1791
+ schema: {
1792
+ type: sameEnum?.name ?? type
1793
+ }
1794
+ };
1795
+ }
1796
+ return {
1797
+ name,
1798
+ required,
1799
+ description,
1800
+ deprecated,
1801
+ in: schema.in,
1802
+ schema: schema.schema && this.getSchemaByRef(
1803
+ schema.schema,
1804
+ false,
1805
+ enums,
1806
+ upLevelSchemaKey + Base.capitalize(name)
1807
+ )
1808
+ };
1809
+ }
1810
+ /**
1811
+ * OpenAPI schema to base response
1812
+ */
1813
+ getResponseByRef(schema) {
1814
+ if (Base.isRef(schema)) {
1815
+ schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1816
+ }
1817
+ const { content = {} } = schema;
1818
+ return Object.keys(content).map((c) => ({
1819
+ type: c,
1820
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1821
+ }));
1822
+ }
1823
+ /**
1824
+ * OpenAPI schema to requestBody.
1825
+ */
1826
+ getRequestBodyByRef(schema, enums = [], reserveRef = false) {
1827
+ if (Base.isRef(schema)) {
1828
+ schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1829
+ }
1830
+ const { content = {} } = schema;
1831
+ return Object.keys(content).map((c) => ({
1832
+ type: c,
1833
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, reserveRef, enums)
1834
+ }));
1835
+ }
1836
+ /**
1837
+ * Transform all OpenAPI schema to Base Schema
1838
+ */
1839
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1840
+ if (!schema) {
1841
+ return {
1842
+ type: "unknown"
1843
+ };
1844
+ }
1845
+ if (Base.isRef(schema)) {
1846
+ return this.getSchemaByRef(schema, true);
1847
+ }
1848
+ if (this.isOpenAPIArraySchema(schema)) {
1849
+ const { type, description, items, required } = schema;
1850
+ return {
1851
+ type,
1852
+ required: !!required,
1853
+ description,
1854
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1855
+ };
1856
+ } else {
1857
+ const {
1858
+ required = [],
1859
+ allOf,
1860
+ anyOf,
1861
+ description,
1862
+ deprecated,
1863
+ enum: enum_,
1864
+ format: format2,
1865
+ oneOf,
1866
+ properties = {}
1867
+ } = schema;
1868
+ let { type } = schema;
1869
+ if (enum_ && type !== "boolean") {
1870
+ const name = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(schemaKey);
1871
+ const enumObject = {
1872
+ name,
1873
+ enum: [...new Set(enum_)]
1874
+ };
1875
+ const sameObject = Base.findSameSchema(enumObject, enums);
1876
+ if (!sameObject && Base.isValidEnumType(schema)) {
1877
+ enums.push(enumObject);
1878
+ }
1879
+ return {
1880
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1881
+ required,
1882
+ description,
1883
+ deprecated
1884
+ };
1885
+ }
1886
+ if (type === void 0 && Object.keys(properties).length > 0) {
1887
+ type = "object" /* object */;
1888
+ }
1889
+ return {
1890
+ type,
1891
+ required,
1892
+ description,
1893
+ deprecated,
1894
+ enum: enum_,
1895
+ format: format2,
1896
+ allOf: allOf?.map(
1897
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1898
+ ),
1899
+ anyOf: anyOf?.map(
1900
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1901
+ ),
1902
+ oneOf: oneOf?.map(
1903
+ (s) => Base.isRef(s) ? { type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc)) } : this.toBaseSchema(s, enums)
1904
+ ),
1905
+ properties: Object.keys(properties).reduce((acc, p) => {
1906
+ const propSchema = properties[p];
1907
+ return {
1908
+ ...acc,
1909
+ [p]: Base.isRef(propSchema) ? {
1910
+ type: Base.upperCamelCase(
1911
+ Base.ref2name(propSchema.$ref, this.doc)
1912
+ )
1913
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1914
+ };
1915
+ }, {})
1916
+ };
1917
+ }
1918
+ }
1919
+ init() {
1920
+ const { components = {}, paths = {} } = this.doc;
1921
+ const enums = [];
1922
+ const {
1923
+ requestBodies = {},
1924
+ responses = {},
1925
+ parameters = {},
1926
+ schemas = {}
1927
+ } = components;
1928
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1929
+ const schema = schemas[key];
1930
+ return {
1931
+ ...acc,
1932
+ [key]: this.getSchemaByRef(schema, false, enums, key)
1933
+ };
1934
+ }, {});
1935
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
1936
+ const parameter = parameters[key];
1937
+ return {
1938
+ ...acc,
1939
+ [key]: this.getParameterByRef(parameter, enums, key)
1940
+ };
1941
+ }, {});
1942
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1943
+ const response = responses[key];
1944
+ return {
1945
+ ...acc,
1946
+ [key]: this.getResponseByRef(response)
1947
+ };
1948
+ }, {});
1949
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
1950
+ const requestBody = requestBodies[key];
1951
+ return {
1952
+ ...acc,
1953
+ [key]: this.getRequestBodyByRef(requestBody, enums)
1954
+ };
1955
+ }, {});
1956
+ const apis = Object.keys(paths).reduce((acc, path) => {
1957
+ const pathObject = paths[path] ?? {};
1958
+ const { $ref } = pathObject;
1959
+ const methodApis = [];
1960
+ if ($ref) {
1961
+ } else {
1962
+ const { parameters: parameters2 = [], description, summary } = pathObject;
1963
+ Object.values(HttpMethods).forEach((method) => {
1964
+ const methodObject = pathObject[method];
1965
+ if (methodObject) {
1966
+ const {
1967
+ deprecated,
1968
+ operationId,
1969
+ summary: summary_,
1970
+ description: description_,
1971
+ responses: responses2 = {},
1972
+ requestBody = { content: {} }
1973
+ } = methodObject;
1974
+ const { parameters: parameters_2 = [] } = methodObject;
1975
+ const baseParameters = [...parameters2, ...parameters_2].map(
1976
+ (parameter) => this.getParameterByRef(parameter, enums)
1977
+ );
1978
+ const baseRequestBody = this.getRequestBodyByRef(
1979
+ requestBody,
1980
+ enums,
1981
+ true
1982
+ );
1983
+ const uniqueParameterName = [
1984
+ ...new Set(baseParameters.map((p) => p.name))
1985
+ ];
1986
+ if (Object.keys(responses2).length === 0) {
1987
+ Object.assign(responses2, {
1988
+ 200: {
1989
+ description: "Successful response"
1990
+ }
1991
+ });
1992
+ }
1993
+ const httpCodes = Object.keys(responses2);
1994
+ for (const code of httpCodes) {
1995
+ if (code in responses2) {
1996
+ const response = responses2[code];
1997
+ const responseSchema = this.getResponseByRef(response);
1998
+ methodApis.push({
1999
+ method,
2000
+ operationId,
2001
+ summary: summary_ ?? summary,
2002
+ description: description_ ?? description,
2003
+ deprecated,
2004
+ parameters: uniqueParameterName.map(
2005
+ (name) => baseParameters.find((p) => p.name === name)
2006
+ ),
2007
+ responses: responseSchema,
2008
+ requestBody: baseRequestBody
2009
+ });
2010
+ break;
2011
+ }
2012
+ }
2013
+ }
2014
+ });
2015
+ }
2016
+ return {
2017
+ ...acc,
2018
+ [path]: methodApis
2019
+ };
2020
+ }, {});
2021
+ return {
2022
+ enums: Base.uniqueEnums(enums),
2023
+ schemas: schemas_,
2024
+ responses: responses_,
2025
+ parameters: parameters_,
2026
+ requestBodies: requestBodies_,
2027
+ apis
2028
+ };
2029
+ }
2030
+ };
2031
+
2032
+ // src/openapi/index.ts
2033
+ var logger = (0, import_logger.createScopedLogger)("OpenAPI");
2034
+ function getDocVersion(doc) {
2035
+ const version2 = (doc.openapi || doc.swagger).slice(0, 3);
2036
+ switch (version2) {
2037
+ case "2.0":
2038
+ return "v2" /* v2 */;
2039
+ case "3.0":
2040
+ return "v3" /* v3 */;
2041
+ case "3.1":
2042
+ return "v3_1" /* v3_1 */;
2043
+ default:
2044
+ return "unknown" /* unknown */;
2045
+ }
2046
+ }
2047
+ var OpenAPIProvider = class extends Provider {
2048
+ parse(doc) {
2049
+ const version2 = getDocVersion(doc);
2050
+ logger.debug(`openapi version ${version2}`);
2051
+ let returnValue;
2052
+ switch (version2) {
2053
+ case "v2" /* v2 */:
2054
+ returnValue = new V2(doc).init();
2055
+ break;
2056
+ case "v3" /* v3 */:
2057
+ returnValue = new V3(doc).init();
2058
+ break;
2059
+ case "v3_1" /* v3_1 */:
2060
+ returnValue = new V3_1(doc).init();
2061
+ break;
2062
+ default:
2063
+ logger.error(`Not a valid OpenAPI version ${version2}`);
2064
+ process.exit(1);
2065
+ }
2066
+ return returnValue;
2067
+ }
2068
+ };
2069
+ function getAdaptor(type) {
2070
+ switch (type) {
2071
+ case "axios" /* axios */:
2072
+ return new AxiosAdapter();
2073
+ case "fetch" /* fetch */:
2074
+ return new FetchAdapter();
2075
+ default:
2076
+ throw TypeError(`Not Supported Adaptor ${type}`);
2077
+ }
2078
+ }
2079
+ async function codeGen(initOptions) {
2080
+ const { verbose } = initOptions;
2081
+ if (verbose) {
2082
+ logger.setLevel("debug");
2083
+ } else {
2084
+ logger.setLevel("info");
2085
+ }
2086
+ logger.info(`Fech document from ${initOptions.docURL}`);
2087
+ const doc = await Base.fetchDoc(
2088
+ initOptions.docURL,
2089
+ initOptions.requestOptions
2090
+ );
2091
+ const provider = new OpenAPIProvider(initOptions, doc);
2092
+ const { enums, schemas, parameters, responses, requestBodies, apis } = provider;
2093
+ const adaptor = getAdaptor(initOptions.adaptor ?? "fetch" /* fetch */);
2094
+ const code = await Generator.genCode(
2095
+ {
2096
+ enums,
2097
+ schemas,
2098
+ parameters,
2099
+ responses,
2100
+ requestBodies,
2101
+ apis
2102
+ },
2103
+ initOptions,
2104
+ adaptor
2105
+ );
2106
+ if (process.env.NODE_ENV === "test") {
2107
+ await Generator.write(code, initOptions.output);
2108
+ }
2109
+ return code;
2110
+ }
2111
+
2112
+ // src/cli.ts
2113
+ var import_commander = require("commander");
2114
+
2115
+ // package.json
2116
+ var version = "0.0.1";
2117
+
2118
+ // src/cli.ts
2119
+ var cli = (0, import_commander.createCommand)("apicodegen");
2120
+ cli.version(version).argument("<docURL>", "DOc url for tool to read").option("--output", "Where code generated", "./output.ts").option("--adaptor", "Adaptor for api call", "fetch").option("--baseURL", "Base path of the api endpoint", "").option("--verbose", "More logs", false).option("--importClientSource", "Where request tool comes from").action(
2121
+ async (docURL, options) => {
2122
+ try {
2123
+ const code = await codeGen({
2124
+ docURL,
2125
+ baseURL: options.baseURL,
2126
+ output: options.output,
2127
+ verbose: options.verbose,
2128
+ adaptor: options.adaptor,
2129
+ importClientSource: options.importClientSource
2130
+ });
2131
+ await Generator.write(code, options.output);
2132
+ } catch (err) {
2133
+ cli.error(err.message);
2134
+ }
2135
+ }
2136
+ );
2137
+ cli.parse();