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