@moccona/apicodegen 0.0.2 → 0.0.4

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