swagger-typescript-api 13.0.22 → 13.0.24

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/dist/types.d.cts DELETED
@@ -1,1812 +0,0 @@
1
- import * as eta from 'eta';
2
- import * as lodash from 'lodash';
3
- import * as swagger_schema_official from 'swagger-schema-official';
4
-
5
- declare class NameResolver {
6
- reservedNames = [];
7
- getFallbackName = null;
8
-
9
- /** @type {CodeGenConfig} */
10
- config;
11
-
12
- /**
13
- * @param {CodeGenConfig} config;
14
- * @param {string[]} reservedNames
15
- */
16
- constructor(config, reservedNames, getFallbackName) {
17
- this.config = config;
18
- this.getFallbackName = getFallbackName;
19
- this.reserve(reservedNames);
20
- }
21
-
22
- /**
23
- * @param {string[]} names
24
- */
25
- reserve(names) {
26
- const fixedNames = lodash.uniq(lodash.compact(names));
27
- for (const name of fixedNames) {
28
- if (this.reservedNames.indexOf(name) === -1) {
29
- this.reservedNames.push(name);
30
- }
31
- }
32
- }
33
-
34
- unreserve(names) {
35
- this.reservedNames.filter(
36
- (reservedName) => !names.some((name) => name === reservedName),
37
- );
38
- }
39
-
40
- isReserved(name) {
41
- return this.reservedNames.some((reservedName) => reservedName === name);
42
- }
43
-
44
- /**
45
- *
46
- * @param {(string[])} variants
47
- * @param {(reserved: string[]) => string)} [resolver]
48
- * @param {any} [extras]
49
- * @returns {string | null}
50
- */
51
- resolve(variants, resolver, extras, shouldReserve = true) {
52
- if (typeof resolver === "function") {
53
- let usageName = null;
54
- while (usageName === null) {
55
- const variant = resolver(variants, extras);
56
-
57
- if (variant === undefined) {
58
- consola.warn(
59
- "unable to resolve name. current reserved names: ",
60
- this.reservedNames,
61
- );
62
- return null;
63
- }
64
- if (!shouldReserve || !this.isReserved(variant)) {
65
- usageName = variant;
66
- }
67
- }
68
-
69
- shouldReserve && this.reserve([usageName]);
70
- return usageName;
71
- }
72
-
73
- if (Array.isArray(variants)) {
74
- let usageName = null;
75
- const uniqVariants = lodash.uniq(lodash.compact(variants));
76
-
77
- for (const variant of uniqVariants) {
78
- if (!usageName && (!shouldReserve || !this.isReserved(variant))) {
79
- usageName = variant;
80
- }
81
- }
82
-
83
- if (usageName) {
84
- shouldReserve && this.reserve([usageName]);
85
- return usageName;
86
- }
87
-
88
- consola.debug(
89
- "trying to resolve name with using fallback name generator using variants",
90
- variants,
91
- );
92
- return this.resolve(variants, this.getFallbackName, extras);
93
- }
94
-
95
- consola.debug(
96
- "problem with reserving names. current reserved names: ",
97
- this.reservedNames,
98
- );
99
- return null;
100
- }
101
- }
102
-
103
- declare class ComponentTypeNameResolver extends NameResolver {
104
- counter = 1;
105
- fallbackNameCounter = 1;
106
- countersByVariant = new Map();
107
-
108
- /**
109
- * @param {CodeGenConfig} config;
110
- * @param {string[]} reservedNames
111
- */
112
- constructor(config, reservedNames) {
113
- super(config, reservedNames, (variants) => {
114
- const randomVariant = variants[getRandomInt(0, variants.length - 1)];
115
- if (randomVariant) {
116
- if (!this.countersByVariant.has(randomVariant)) {
117
- this.countersByVariant.set(randomVariant, 0);
118
- }
119
- const variantCounter = this.countersByVariant.get(randomVariant) + 1;
120
- this.countersByVariant.set(randomVariant, variantCounter);
121
- const dirtyResolvedName = `${randomVariant}${variantCounter}`;
122
- consola.debug(
123
- "generated dirty resolved type name for component - ",
124
- dirtyResolvedName,
125
- );
126
- return dirtyResolvedName;
127
- }
128
-
129
- const fallbackName = `${this.config.componentTypeNameResolver}${this
130
- .fallbackNameCounter++}`;
131
- consola.debug(
132
- "generated fallback type name for component - ",
133
- fallbackName,
134
- );
135
- return fallbackName;
136
- });
137
- }
138
- }
139
-
140
- declare class MonoSchemaParser {
141
- schema;
142
- typeName;
143
- schemaPath;
144
-
145
- /** @type {SchemaParser} */
146
- schemaParser;
147
- /** @type {SchemaParserFabric} */
148
- schemaParserFabric;
149
- /** @type {TypeNameFormatter} */
150
- typeNameFormatter;
151
- /** @type {SchemaComponentsMap} */
152
- schemaComponentsMap;
153
- /** @type {SchemaUtils} */
154
- schemaUtils;
155
- /** @type {CodeGenConfig} */
156
- config;
157
- /** @type {SchemaFormatters} */
158
- schemaFormatters;
159
-
160
- constructor(schemaParser, schema, typeName = null, schemaPath = []) {
161
- this.schemaParser = schemaParser;
162
- this.schemaParserFabric = schemaParser.schemaParserFabric;
163
- this.schema = schema;
164
- this.typeName = typeName;
165
- this.typeNameFormatter = schemaParser.typeNameFormatter;
166
- this.schemaPath = schemaPath;
167
- this.schemaComponentsMap = this.schemaParser.schemaComponentsMap;
168
- this.schemaUtils = this.schemaParser.schemaUtils;
169
- this.config = this.schemaParser.config;
170
- this.schemaFormatters = this.schemaParser.schemaFormatters;
171
- }
172
-
173
- parse() {
174
- throw new Error("not implemented");
175
- }
176
-
177
- buildTypeNameFromPath = () => {
178
- return this.schemaUtils.buildTypeNameFromPath(this.schemaPath);
179
- };
180
- }
181
-
182
- declare class SchemaParser {
183
- /** @type {SchemaParserFabric} */
184
- schemaParserFabric;
185
- /** @type {CodeGenConfig} */
186
- config;
187
- /** @type {SchemaComponentsMap} */
188
- schemaComponentsMap;
189
- /** @type {TypeNameFormatter} */
190
- typeNameFormatter;
191
- /** @type {SchemaFormatters} */
192
- schemaFormatters;
193
- /** @type {SchemaUtils} */
194
- schemaUtils;
195
- /** @type {TemplatesWorker} */
196
- templatesWorker;
197
- /** @type {SchemaWalker} */
198
- schemaWalker;
199
-
200
- typeName;
201
- schema;
202
- schemaPath = [];
203
-
204
- constructor(schemaParserFabric, { typeName, schema, schemaPath } = {}) {
205
- this.schemaParserFabric = schemaParserFabric;
206
- this.config = schemaParserFabric.config;
207
- this.templatesWorker = schemaParserFabric.templatesWorker;
208
- this.schemaComponentsMap = schemaParserFabric.schemaComponentsMap;
209
- this.typeNameFormatter = schemaParserFabric.typeNameFormatter;
210
- this.schemaWalker = schemaParserFabric.schemaWalker;
211
- this.schemaFormatters = schemaParserFabric.schemaFormatters;
212
- this.schemaUtils = schemaParserFabric.schemaUtils;
213
-
214
- this.typeName = typeName || null;
215
- this.schema = schema;
216
- this.schemaPath = [...(schemaPath || [])];
217
- }
218
-
219
- _complexSchemaParsers = {
220
- [SCHEMA_TYPES.COMPLEX_ONE_OF]: (schema) => {
221
- const SchemaParser =
222
- this.config.schemaParsers.complexOneOf || OneOfSchemaParser;
223
- const schemaParser = new SchemaParser(
224
- this,
225
- schema,
226
- null,
227
- this.schemaPath,
228
- );
229
- return schemaParser.parse();
230
- },
231
- [SCHEMA_TYPES.COMPLEX_ALL_OF]: (schema) => {
232
- const SchemaParser =
233
- this.config.schemaParsers.complexAllOf || AllOfSchemaParser;
234
- const schemaParser = new SchemaParser(
235
- this,
236
- schema,
237
- null,
238
- this.schemaPath,
239
- );
240
- return schemaParser.parse();
241
- },
242
- [SCHEMA_TYPES.COMPLEX_ANY_OF]: (schema) => {
243
- const SchemaParser =
244
- this.config.schemaParsers.complexAnyOf || AnyOfSchemaParser;
245
- const schemaParser = new SchemaParser(
246
- this,
247
- schema,
248
- null,
249
- this.schemaPath,
250
- );
251
- return schemaParser.parse();
252
- },
253
- [SCHEMA_TYPES.COMPLEX_NOT]: (schema) => {
254
- const SchemaParser =
255
- this.config.schemaParsers.complexNot || NotSchemaParser;
256
- const schemaParser = new SchemaParser(
257
- this,
258
- schema,
259
- null,
260
- this.schemaPath,
261
- );
262
- return schemaParser.parse();
263
- },
264
- };
265
-
266
- _baseSchemaParsers = {
267
- [SCHEMA_TYPES.ENUM]: (schema, typeName) => {
268
- const SchemaParser = this.config.schemaParsers.enum || EnumSchemaParser;
269
- const schemaParser = new SchemaParser(
270
- this,
271
- schema,
272
- typeName,
273
- this.schemaPath,
274
- );
275
- return schemaParser.parse();
276
- },
277
- [SCHEMA_TYPES.OBJECT]: (schema, typeName) => {
278
- const SchemaParser =
279
- this.config.schemaParsers.object || ObjectSchemaParser;
280
- const schemaParser = new SchemaParser(
281
- this,
282
- schema,
283
- typeName,
284
- this.schemaPath,
285
- );
286
- return schemaParser.parse();
287
- },
288
- [SCHEMA_TYPES.COMPLEX]: (schema, typeName) => {
289
- const SchemaParser =
290
- this.config.schemaParsers.complex || ComplexSchemaParser;
291
- const schemaParser = new SchemaParser(
292
- this,
293
- schema,
294
- typeName,
295
- this.schemaPath,
296
- );
297
- return schemaParser.parse();
298
- },
299
- [SCHEMA_TYPES.PRIMITIVE]: (schema, typeName) => {
300
- const SchemaParser =
301
- this.config.schemaParsers.primitive || PrimitiveSchemaParser;
302
- const schemaParser = new SchemaParser(
303
- this,
304
- schema,
305
- typeName,
306
- this.schemaPath,
307
- );
308
- return schemaParser.parse();
309
- },
310
- [SCHEMA_TYPES.DISCRIMINATOR]: (schema, typeName) => {
311
- const SchemaParser =
312
- this.config.schemaParsers.discriminator || DiscriminatorSchemaParser;
313
- const schemaParser = new SchemaParser(
314
- this,
315
- schema,
316
- typeName,
317
- this.schemaPath,
318
- );
319
- return schemaParser.parse();
320
- },
321
- [SCHEMA_TYPES.ARRAY]: (schema, typeName) => {
322
- const SchemaParser = this.config.schemaParsers.array || ArraySchemaParser;
323
- const schemaParser = new SchemaParser(
324
- this,
325
- schema,
326
- typeName,
327
- this.schemaPath,
328
- );
329
- return schemaParser.parse();
330
- },
331
- };
332
-
333
- /**
334
- * @return {Record<string, any>}
335
- */
336
- parseSchema = () => {
337
- if (!this.schema)
338
- return this._baseSchemaParsers[SCHEMA_TYPES.PRIMITIVE](
339
- null,
340
- this.typeName,
341
- );
342
-
343
- let schemaType = null;
344
- let parsedSchema = null;
345
-
346
- if (typeof this.schema === "string") {
347
- return this.schema;
348
- }
349
-
350
- if (!this.schema.$parsed) {
351
- if (!this.typeName && this.schemaUtils.isRefSchema(this.schema)) {
352
- this.typeName = this.schemaUtils.getSchemaType(this.schema);
353
- }
354
-
355
- //#region swagger schemas fixes
356
-
357
- // schema has items but don't have array type
358
- if (
359
- this.schema.items &&
360
- !Array.isArray(this.schema.items) &&
361
- !this.schema.type
362
- ) {
363
- this.schema.type = SCHEMA_TYPES.ARRAY;
364
- }
365
- // schema is enum with one null value
366
- if (
367
- Array.isArray(this.schema.enum) &&
368
- this.schema.enum.length === 1 &&
369
- this.schema.enum[0] == null
370
- ) {
371
- consola.debug("invalid enum schema", this.schema);
372
- this.schema = { type: this.config.Ts.Keyword.Null };
373
- }
374
- // schema is response schema
375
- if ("content" in this.schema && typeof this.schema.content === "object") {
376
- const schema = this.extractSchemaFromResponseStruct(this.schema);
377
- const schemaParser = this.schemaParserFabric.createSchemaParser({
378
- schema,
379
- typeName: this.typeName,
380
- schemaPath: this.schemaPath,
381
- });
382
- this.schema.$parsed = schemaParser.parseSchema();
383
- return this.schema.$parsed;
384
- }
385
-
386
- //#endregion
387
-
388
- schemaType = this.schemaUtils.getInternalSchemaType(this.schema);
389
-
390
- this.schemaPath.push(this.typeName);
391
-
392
- lodash.merge(
393
- this.schema,
394
- this.config.hooks.onPreParseSchema(
395
- this.schema,
396
- this.typeName,
397
- schemaType,
398
- ),
399
- );
400
- parsedSchema = this._baseSchemaParsers[schemaType](
401
- this.schema,
402
- this.typeName,
403
- );
404
- this.schema.$parsed =
405
- this.config.hooks.onParseSchema(this.schema, parsedSchema) ||
406
- parsedSchema;
407
-
408
- if (
409
- this.config.sortTypes &&
410
- Array.isArray(this.schema.$parsed?.content)
411
- ) {
412
- this.schema.$parsed.content = this.schema.$parsed.content.sort(
413
- sortByProperty("name"),
414
- );
415
- }
416
- }
417
-
418
- this.schemaPath.pop();
419
-
420
- return this.schema.$parsed;
421
- };
422
-
423
- getInlineParseContent = () => {
424
- const parsedSchema = this.parseSchema();
425
- const formattedSchema = this.schemaFormatters.formatSchema(
426
- parsedSchema,
427
- "inline",
428
- );
429
- return formattedSchema.content;
430
- };
431
-
432
- getParseContent = () => {
433
- const parsedSchema = this.parseSchema();
434
- const formattedSchema = this.schemaFormatters.formatSchema(
435
- parsedSchema,
436
- "base",
437
- );
438
- return formattedSchema.content;
439
- };
440
-
441
- extractSchemaFromResponseStruct = (responseStruct) => {
442
- const { content, ...extras } = responseStruct;
443
-
444
- const firstResponse = lodash.first(lodash.values(content));
445
- const firstSchema = lodash.get(firstResponse, "schema");
446
-
447
- if (!firstSchema) return;
448
-
449
- return {
450
- ...extras,
451
- ...lodash.omit(firstResponse, "schema"),
452
- ...firstSchema,
453
- };
454
- };
455
- }
456
-
457
- /**
458
- * @typedef {{ fileName: string, fileExtension: string, fileContent: string }} TranslatorIO
459
- */
460
-
461
- declare class Translator {
462
- /** @type {CodeGenConfig} */
463
- config;
464
- /** @type {CodeFormatter} */
465
- codeFormatter;
466
-
467
- /**
468
- * @param codeGenProcess
469
- */
470
- constructor(codeGenProcess) {
471
- this.config = codeGenProcess.config;
472
- this.codeFormatter = codeGenProcess.codeFormatter;
473
- }
474
-
475
- /**
476
- *
477
- * @param input {TranslatorIO}
478
- * @return {Promise<TranslatorIO[]>}
479
- */
480
- translate(input) {
481
- throw new Error("not implemented");
482
- }
483
- }
484
-
485
- declare class CodeGenProcess {
486
- /** @type {CodeGenConfig} */
487
- config;
488
- /** @type {SwaggerSchemaResolver} */
489
- swaggerSchemaResolver;
490
- /** @type {SchemaComponentsMap} */
491
- schemaComponentsMap;
492
- /** @type {TypeNameFormatter} */
493
- typeNameFormatter;
494
- /** @type {SchemaParserFabric} */
495
- schemaParserFabric;
496
- /** @type {SchemaRoutes} */
497
- schemaRoutes;
498
- /** @type {FileSystem} */
499
- fileSystem;
500
- /** @type {CodeFormatter} */
501
- codeFormatter;
502
- /** type {TemplatesWorker} */
503
- templatesWorker;
504
- /** @type {SchemaWalker} */
505
- schemaWalker;
506
- /** @type {JavascriptTranslator} */
507
- javascriptTranslator;
508
-
509
- /**
510
- *
511
- * @param config {Partial<import("../index.d.ts").GenerateApiConfiguration['config']>}
512
- */
513
- constructor(config) {
514
- this.config = new CodeGenConfig(config);
515
- this.fileSystem = new FileSystem(this);
516
- this.schemaWalker = new SchemaWalker(this);
517
- this.swaggerSchemaResolver = new SwaggerSchemaResolver(this);
518
- this.schemaComponentsMap = new SchemaComponentsMap(this);
519
- this.typeNameFormatter = new TypeNameFormatter(this);
520
- this.templatesWorker = new TemplatesWorker(this);
521
- this.codeFormatter = new CodeFormatter(this);
522
- this.schemaParserFabric = new SchemaParserFabric(this);
523
- this.schemaRoutes = new SchemaRoutes(this);
524
- this.javascriptTranslator = new JavascriptTranslator(this);
525
- }
526
-
527
- async start() {
528
- this.config.update({
529
- templatePaths: this.templatesWorker.getTemplatePaths(this.config),
530
- });
531
- this.config.update({
532
- templatesToRender: this.templatesWorker.getTemplates(this.config),
533
- });
534
-
535
- const swagger = await this.swaggerSchemaResolver.create();
536
-
537
- this.swaggerSchemaResolver.fixSwaggerSchema(swagger);
538
-
539
- this.config.update({
540
- swaggerSchema: swagger.usageSchema,
541
- originalSchema: swagger.originalSchema,
542
- });
543
-
544
- this.schemaWalker.addSchema("$usage", swagger.usageSchema);
545
- this.schemaWalker.addSchema("$original", swagger.originalSchema);
546
-
547
- consola.info("start generating your typescript api");
548
-
549
- this.config.update(
550
- this.config.hooks.onInit(this.config, this) || this.config,
551
- );
552
-
553
- this.schemaComponentsMap.clear();
554
-
555
- lodash.each(swagger.usageSchema.components, (component, componentName) =>
556
- lodash.each(component, (rawTypeData, typeName) => {
557
- this.schemaComponentsMap.createComponent(
558
- this.schemaComponentsMap.createRef([
559
- "components",
560
- componentName,
561
- typeName,
562
- ]),
563
- rawTypeData,
564
- );
565
- }),
566
- );
567
-
568
- /**
569
- * @type {SchemaComponent[]}
570
- */
571
- const componentsToParse = this.schemaComponentsMap.filter(
572
- lodash.compact(["schemas", this.config.extractResponses && "responses"]),
573
- );
574
-
575
- const parsedSchemas = componentsToParse.map((schemaComponent) => {
576
- const parsed = this.schemaParserFabric.parseSchema(
577
- schemaComponent.rawTypeData,
578
- schemaComponent.typeName,
579
- );
580
- schemaComponent.typeData = parsed;
581
- return parsed;
582
- });
583
-
584
- this.schemaRoutes.attachSchema({
585
- usageSchema: swagger.usageSchema,
586
- parsedSchemas,
587
- });
588
-
589
- const rawConfiguration = {
590
- apiConfig: this.createApiConfig(swagger.usageSchema),
591
- config: this.config,
592
- modelTypes: this.collectModelTypes(),
593
- hasSecurityRoutes: this.schemaRoutes.hasSecurityRoutes,
594
- hasQueryRoutes: this.schemaRoutes.hasQueryRoutes,
595
- hasFormDataRoutes: this.schemaRoutes.hasFormDataRoutes,
596
- generateResponses: this.config.generateResponses,
597
- routes: this.schemaRoutes.getGroupedRoutes(),
598
- extraTemplates: this.config.extraTemplates,
599
- fileName: this.config.fileName,
600
- translateToJavaScript: this.config.toJS,
601
- customTranslator: this.config.customTranslator
602
- ? new this.config.customTranslator(this)
603
- : null,
604
- utils: this.getRenderTemplateData().utils,
605
- };
606
-
607
- const configuration =
608
- this.config.hooks.onPrepareConfig(rawConfiguration) || rawConfiguration;
609
-
610
- if (this.fileSystem.pathIsExist(this.config.output)) {
611
- if (this.config.cleanOutput) {
612
- consola.debug("cleaning dir", this.config.output);
613
- this.fileSystem.cleanDir(this.config.output);
614
- }
615
- } else {
616
- consola.debug(
617
- `path ${this.config.output} is not exist. creating dir by this path`,
618
- );
619
- this.fileSystem.createDir(this.config.output);
620
- }
621
-
622
- const files = await this.generateOutputFiles({
623
- configuration: configuration,
624
- });
625
-
626
- const isDirPath = this.fileSystem.pathIsDir(this.config.output);
627
-
628
- if (isDirPath) {
629
- for (const file of files) {
630
- this.fileSystem.createFile({
631
- path: this.config.output,
632
- fileName: `${file.fileName}${file.fileExtension}`,
633
- content: file.fileContent,
634
- withPrefix: true,
635
- });
636
-
637
- consola.success(
638
- "api file",
639
- `"${file.fileName}${file.fileExtension}"`,
640
- `created in ${this.config.output}`,
641
- );
642
- }
643
- }
644
-
645
- return {
646
- files,
647
- configuration,
648
- getTemplate: this.templatesWorker.getTemplate,
649
- renderTemplate: this.templatesWorker.renderTemplate,
650
- createFile: this.fileSystem.createFile,
651
- formatTSContent: this.codeFormatter.formatCode,
652
- };
653
- }
654
-
655
- getRenderTemplateData = () => {
656
- return {
657
- utils: {
658
- Ts: this.config.Ts,
659
- formatDescription:
660
- this.schemaParserFabric.schemaFormatters.formatDescription,
661
- internalCase: internalCase,
662
- classNameCase: pascalCase,
663
- pascalCase: pascalCase,
664
- getInlineParseContent: this.schemaParserFabric.getInlineParseContent,
665
- getParseContent: this.schemaParserFabric.getParseContent,
666
- getComponentByRef: this.schemaComponentsMap.get,
667
- parseSchema: this.schemaParserFabric.parseSchema,
668
- checkAndAddNull: this.schemaParserFabric.schemaUtils.safeAddNullToType,
669
- safeAddNullToType:
670
- this.schemaParserFabric.schemaUtils.safeAddNullToType,
671
- isNeedToAddNull:
672
- this.schemaParserFabric.schemaUtils.isNullMissingInType,
673
- inlineExtraFormatters: this.schemaParserFabric.schemaFormatters.inline,
674
- formatters: this.schemaParserFabric.schemaFormatters.base,
675
- formatModelName: this.typeNameFormatter.format,
676
- fmtToJSDocLine: function fmtToJSDocLine(line, { eol = true }) {
677
- return ` * ${line}${eol ? "\n" : ""}`;
678
- },
679
- NameResolver: NameResolver,
680
- _: lodash,
681
- require: this.templatesWorker.requireFnFromTemplate,
682
- },
683
- config: this.config,
684
- };
685
- };
686
-
687
- collectModelTypes = () => {
688
- const components = this.schemaComponentsMap.getComponents();
689
- let modelTypes = [];
690
-
691
- const modelTypeComponents = lodash.compact([
692
- "schemas",
693
- this.config.extractResponses && "responses",
694
- ]);
695
-
696
- const getSchemaComponentsCount = () =>
697
- this.schemaComponentsMap.filter(...modelTypeComponents).length;
698
-
699
- let schemaComponentsCount = getSchemaComponentsCount();
700
- let processedCount = 0;
701
-
702
- while (processedCount < schemaComponentsCount) {
703
- modelTypes = [];
704
- processedCount = 0;
705
- for (const component of components) {
706
- if (modelTypeComponents.includes(component.componentName)) {
707
- const modelType = this.prepareModelType(component);
708
- if (modelType) {
709
- modelTypes.push(modelType);
710
- }
711
- processedCount++;
712
- }
713
- }
714
- schemaComponentsCount = getSchemaComponentsCount();
715
- }
716
-
717
- if (this.config.sortTypes) {
718
- return modelTypes.sort(sortByProperty("name"));
719
- }
720
-
721
- return modelTypes;
722
- };
723
-
724
- prepareModelType = (typeInfo) => {
725
- if (typeInfo.$prepared) return typeInfo.$prepared;
726
-
727
- if (!typeInfo.typeData) {
728
- typeInfo.typeData = this.schemaParserFabric.parseSchema(
729
- typeInfo.rawTypeData,
730
- typeInfo.typeName,
731
- );
732
- }
733
- const rawTypeData = typeInfo.typeData;
734
- const typeData = this.schemaParserFabric.schemaFormatters.base[
735
- rawTypeData.type
736
- ]
737
- ? this.schemaParserFabric.schemaFormatters.base[rawTypeData.type](
738
- rawTypeData,
739
- )
740
- : rawTypeData;
741
- const {
742
- typeIdentifier,
743
- name: originalName,
744
- content,
745
- description,
746
- } = typeData;
747
- const name = this.typeNameFormatter.format(originalName);
748
-
749
- if (name === null) return null;
750
-
751
- const preparedModelType = {
752
- ...typeData,
753
- typeIdentifier,
754
- name,
755
- description,
756
- $content: rawTypeData.content,
757
- rawContent: rawTypeData.content,
758
- content: content,
759
- typeData,
760
- };
761
-
762
- typeInfo.$prepared = preparedModelType;
763
-
764
- return preparedModelType;
765
- };
766
-
767
- /**
768
- *
769
- * @param configuration
770
- * @returns {Promise<TranslatorIO[]>}
771
- */
772
- generateOutputFiles = async ({ configuration }) => {
773
- const { modular, templatesToRender } = this.config;
774
-
775
- const output = modular
776
- ? await this.createMultipleFileInfos(templatesToRender, configuration)
777
- : await this.createSingleFileInfo(templatesToRender, configuration);
778
-
779
- if (!lodash.isEmpty(configuration.extraTemplates)) {
780
- for (const extraTemplate of configuration.extraTemplates) {
781
- const content = this.templatesWorker.renderTemplate(
782
- this.fileSystem.getFileContent(extraTemplate.path),
783
- configuration,
784
- );
785
- output.push(
786
- ...(await this.createOutputFileInfo(
787
- configuration,
788
- extraTemplate.name,
789
- content,
790
- )),
791
- );
792
- }
793
- }
794
-
795
- return output.filter((fileInfo) => !!fileInfo && !!fileInfo.fileContent);
796
- };
797
-
798
- /**
799
- * @param templatesToRender
800
- * @param configuration
801
- * @returns {Promise<TranslatorIO[]>}
802
- */
803
- createMultipleFileInfos = async (templatesToRender, configuration) => {
804
- const { routes } = configuration;
805
- const { fileNames, generateRouteTypes, generateClient } =
806
- configuration.config;
807
- /**
808
- * @type {TranslatorIO[]}
809
- */
810
- const modularApiFileInfos = [];
811
-
812
- if (routes.$outOfModule) {
813
- if (generateRouteTypes) {
814
- const outOfModuleRouteContent = this.templatesWorker.renderTemplate(
815
- templatesToRender.routeTypes,
816
- {
817
- ...configuration,
818
- route: configuration.routes.$outOfModule,
819
- },
820
- );
821
-
822
- modularApiFileInfos.push(
823
- ...(await this.createOutputFileInfo(
824
- configuration,
825
- fileNames.outOfModuleApi,
826
- outOfModuleRouteContent,
827
- )),
828
- );
829
- }
830
- if (generateClient) {
831
- const outOfModuleApiContent = this.templatesWorker.renderTemplate(
832
- templatesToRender.api,
833
- {
834
- ...configuration,
835
- route: configuration.routes.$outOfModule,
836
- },
837
- );
838
-
839
- modularApiFileInfos.push(
840
- ...(await this.createOutputFileInfo(
841
- configuration,
842
- fileNames.outOfModuleApi,
843
- outOfModuleApiContent,
844
- )),
845
- );
846
- }
847
- }
848
-
849
- if (routes.combined) {
850
- for (const route of routes.combined) {
851
- if (generateRouteTypes) {
852
- const routeModuleContent = this.templatesWorker.renderTemplate(
853
- templatesToRender.routeTypes,
854
- {
855
- ...configuration,
856
- route,
857
- },
858
- );
859
-
860
- modularApiFileInfos.push(
861
- ...(await this.createOutputFileInfo(
862
- configuration,
863
- pascalCase(`${route.moduleName}_Route`),
864
- routeModuleContent,
865
- )),
866
- );
867
- }
868
-
869
- if (generateClient) {
870
- const apiModuleContent = this.templatesWorker.renderTemplate(
871
- templatesToRender.api,
872
- {
873
- ...configuration,
874
- route,
875
- },
876
- );
877
-
878
- modularApiFileInfos.push(
879
- ...(await this.createOutputFileInfo(
880
- configuration,
881
- pascalCase(route.moduleName),
882
- apiModuleContent,
883
- )),
884
- );
885
- }
886
- }
887
- }
888
-
889
- return [
890
- ...(await this.createOutputFileInfo(
891
- configuration,
892
- fileNames.dataContracts,
893
- this.templatesWorker.renderTemplate(
894
- templatesToRender.dataContracts,
895
- configuration,
896
- ),
897
- )),
898
- ...(generateClient
899
- ? await this.createOutputFileInfo(
900
- configuration,
901
- fileNames.httpClient,
902
- this.templatesWorker.renderTemplate(
903
- templatesToRender.httpClient,
904
- configuration,
905
- ),
906
- )
907
- : []),
908
- ...modularApiFileInfos,
909
- ];
910
- };
911
-
912
- /**
913
- *
914
- * @param templatesToRender
915
- * @param configuration
916
- * @returns {Promise<TranslatorIO[]>}
917
- */
918
- createSingleFileInfo = async (templatesToRender, configuration) => {
919
- const { generateRouteTypes, generateClient } = configuration.config;
920
-
921
- return await this.createOutputFileInfo(
922
- configuration,
923
- configuration.fileName,
924
- lodash
925
- .compact([
926
- this.templatesWorker.renderTemplate(
927
- templatesToRender.dataContracts,
928
- configuration,
929
- ),
930
- generateRouteTypes &&
931
- this.templatesWorker.renderTemplate(
932
- templatesToRender.routeTypes,
933
- configuration,
934
- ),
935
- generateClient &&
936
- this.templatesWorker.renderTemplate(
937
- templatesToRender.httpClient,
938
- configuration,
939
- ),
940
- generateClient &&
941
- this.templatesWorker.renderTemplate(
942
- templatesToRender.api,
943
- configuration,
944
- ),
945
- ])
946
- .join("\n"),
947
- );
948
- };
949
-
950
- /**
951
- *
952
- * @param configuration
953
- * @param fileNameFull
954
- * @param content
955
- * @returns {Promise<TranslatorIO[]>}
956
- */
957
- createOutputFileInfo = async (configuration, fileNameFull, content) => {
958
- const fileName = this.fileSystem.cropExtension(fileNameFull);
959
- const fileExtension = typescript.Extension.Ts;
960
-
961
- if (configuration.translateToJavaScript) {
962
- consola.debug("using js translator for", fileName);
963
- return await this.javascriptTranslator.translate({
964
- fileName: fileName,
965
- fileExtension: fileExtension,
966
- fileContent: content,
967
- });
968
- }
969
-
970
- if (configuration.customTranslator) {
971
- consola.debug("using custom translator for", fileName);
972
- return await configuration.customTranslator.translate({
973
- fileName: fileName,
974
- fileExtension: fileExtension,
975
- fileContent: content,
976
- });
977
- }
978
-
979
- consola.debug("generating output for", `${fileName}${fileExtension}`);
980
-
981
- return [
982
- {
983
- fileName,
984
- fileExtension: fileExtension,
985
- fileContent: await this.codeFormatter.formatCode(content),
986
- },
987
- ];
988
- };
989
-
990
- createApiConfig = (swaggerSchema) => {
991
- const { info, servers, host, basePath, externalDocs, tags } = swaggerSchema;
992
- const server = servers?.[0] || { url: "" };
993
- const { title = "No title", version } = info || {};
994
- const { url: serverUrl } = server;
995
-
996
- return {
997
- info: info || {},
998
- servers: servers || [],
999
- basePath,
1000
- host,
1001
- externalDocs: lodash.merge(
1002
- {
1003
- url: "",
1004
- description: "",
1005
- },
1006
- externalDocs,
1007
- ),
1008
- tags: lodash.compact(tags),
1009
- baseUrl: serverUrl,
1010
- title,
1011
- version,
1012
- };
1013
- };
1014
-
1015
- injectClassInstance = (key, value) => {
1016
- this[key] = value;
1017
- for (const instanceKey of PATCHABLE_INSTANCES) {
1018
- if (instanceKey !== key && key in this[instanceKey]) {
1019
- this[instanceKey][key] = value;
1020
- }
1021
- }
1022
- };
1023
- }
1024
-
1025
- type HttpClientType = "axios" | "fetch";
1026
-
1027
- interface GenerateApiParamsBase {
1028
- /**
1029
- * default 'api.ts'
1030
- */
1031
- name?: string;
1032
-
1033
- /**
1034
- * name of the main exported class
1035
- */
1036
- apiClassName?: string;
1037
-
1038
- /**
1039
- * path to folder where will be located the created api module.
1040
- *
1041
- * may set to `false` to skip writing content to disk. in this case,
1042
- * you may access the `files` on the return value.
1043
- */
1044
- output?: string | false;
1045
-
1046
- /**
1047
- * path to folder containing templates (default: ./src/templates)
1048
- */
1049
- templates?: string;
1050
-
1051
- /**
1052
- * generate all "enum" types as union types (T1 | T2 | TN) (default: false)
1053
- */
1054
- generateUnionEnums?: boolean;
1055
-
1056
- /**
1057
- * generate type definitions for API routes (default: false)
1058
- */
1059
- generateRouteTypes?: boolean;
1060
-
1061
- /**
1062
- * do not generate an API class
1063
- */
1064
- generateClient?: boolean;
1065
- /**
1066
- * generated http client type
1067
- */
1068
- httpClientType?: HttpClientType;
1069
- /**
1070
- * use "default" response status code as success response too.
1071
- * some swagger schemas use "default" response status code as success response type by default.
1072
- */
1073
- defaultResponseAsSuccess?: boolean;
1074
-
1075
- /**
1076
- * generate additional information about request responses
1077
- * also add typings for bad responses
1078
- */
1079
- generateResponses?: boolean;
1080
-
1081
- /**
1082
- * unwrap the data item from the response
1083
- */
1084
- unwrapResponseData?: boolean;
1085
-
1086
- /**
1087
- * sort data contracts in alphabetical order
1088
- */
1089
- sortTypes?: boolean;
1090
-
1091
- /**
1092
- * sort routes in alphabetical order
1093
- */
1094
- sortRoutes?: boolean;
1095
-
1096
- /**
1097
- * generate js api module with declaration file (default: false)
1098
- */
1099
- toJS?: boolean;
1100
-
1101
- /**
1102
- * determines which path index should be used for routes separation
1103
- */
1104
- moduleNameIndex?: number;
1105
- /**
1106
- * users operation's first tag for route separation
1107
- */
1108
- moduleNameFirstTag?: boolean;
1109
- /**
1110
- * disabled SSL check
1111
- */
1112
- disableStrictSSL?: boolean;
1113
- /**
1114
- * disabled Proxy
1115
- */
1116
- disableProxy?: boolean;
1117
- /**
1118
- * generate separated files for http client, data contracts, and routes (default: false)
1119
- */
1120
- modular?: boolean;
1121
- /**
1122
- * extract request params to data contract (Also combine path params and query params into one object)
1123
- */
1124
- extractRequestParams?: boolean;
1125
- /**
1126
- * extract request body type to data contract
1127
- */
1128
- extractRequestBody?: boolean;
1129
- /**
1130
- * extract response body type to data contract
1131
- */
1132
- extractResponseBody?: boolean;
1133
- /**
1134
- * extract response error type to data contract
1135
- */
1136
- extractResponseError?: boolean;
1137
- /**
1138
- * prettier configuration
1139
- */
1140
- prettier?: object;
1141
- /**
1142
- * Output only errors to console (default: false)
1143
- */
1144
- silent?: boolean;
1145
- /**
1146
- * default type for empty response schema (default: "void")
1147
- */
1148
- defaultResponseType?: string;
1149
- /**
1150
- * Ability to send HttpClient instance to Api constructor
1151
- */
1152
- singleHttpClient?: boolean;
1153
- cleanOutput?: boolean;
1154
- enumNamesAsValues?: boolean;
1155
-
1156
- hooks?: Partial<Hooks>;
1157
- /**
1158
- * extra templates
1159
- */
1160
- extraTemplates?: { name: string; path: string }[];
1161
-
1162
- /**
1163
- * fix up small errors in the swagger source definition
1164
- */
1165
- patch?: boolean;
1166
- /**
1167
- * authorization token
1168
- */
1169
- authorizationToken?: string;
1170
- /**
1171
- * generate readonly properties (default: false)
1172
- */
1173
- addReadonly?: boolean;
1174
-
1175
- primitiveTypeConstructs?: (
1176
- struct: PrimitiveTypeStruct,
1177
- ) => Partial<PrimitiveTypeStruct>;
1178
-
1179
- codeGenConstructs?: (struct: CodeGenConstruct) => Partial<CodeGenConstruct>;
1180
-
1181
- /** extract all enums from nested types\interfaces to `enum` construction */
1182
- extractEnums?: boolean;
1183
-
1184
- /** prefix string value needed to fix invalid type names (default: 'Type') */
1185
- fixInvalidTypeNamePrefix?: string;
1186
-
1187
- /** prefix string value needed to fix invalid enum keys (default: 'Value') */
1188
- fixInvalidEnumKeyPrefix?: string;
1189
-
1190
- /** prefix string value for enum keys */
1191
- enumKeyPrefix?: string;
1192
-
1193
- /** suffix string value for enum keys */
1194
- enumKeySuffix?: string;
1195
-
1196
- /** prefix string value for type names */
1197
- typePrefix?: string;
1198
-
1199
- /** suffix string value for type names */
1200
- typeSuffix?: string;
1201
-
1202
- /** extra configuration for extracting type names operations */
1203
- extractingOptions?: Partial<ExtractingOptions>;
1204
-
1205
- /** configuration for fetching swagger schema requests */
1206
- requestOptions?: null | Partial<RequestInit>;
1207
-
1208
- /** ts compiler configuration object (for --to-js option) */
1209
- compilerTsConfig?: Record<string, unknown>;
1210
-
1211
- /**
1212
- * custom ts->* translator
1213
- * do not use constructor args, it can break functionality of this property, just send class reference
1214
- *
1215
- * @example
1216
- * ```ts
1217
- * import { Translator } from "swagger-typescript-api/src/translators/translator";
1218
- *
1219
- * class MyTranslator extends Translator {
1220
- *
1221
- * translate({ fileName, fileExtension, fileContent }) {
1222
- * this.codeFormatter.format()
1223
- * this.config.
1224
- *
1225
- * return [
1226
- * {
1227
- * fileName,
1228
- * fileExtension,
1229
- * fileContent,
1230
- * }
1231
- * ]
1232
- * }
1233
- * }
1234
- * ```
1235
- */
1236
- customTranslator?: new () => typeof Translator;
1237
- /** fallback name for enum key resolver */
1238
- enumKeyResolverName?: string;
1239
- /** fallback name for type name resolver */
1240
- typeNameResolverName?: string;
1241
- /** fallback name for specific arg name resolver */
1242
- specificArgNameResolverName?: string;
1243
- schemaParsers?: {
1244
- complexOneOf?: MonoSchemaParser;
1245
- complexAllOf?: MonoSchemaParser;
1246
- complexAnyOf?: MonoSchemaParser;
1247
- complexNot?: MonoSchemaParser;
1248
- enum?: MonoSchemaParser;
1249
- object?: MonoSchemaParser;
1250
- complex?: MonoSchemaParser;
1251
- primitive?: MonoSchemaParser;
1252
- discriminator?: MonoSchemaParser;
1253
- array?: MonoSchemaParser;
1254
- };
1255
- }
1256
-
1257
- type CodeGenConstruct = {
1258
- Keyword: {
1259
- Number: string;
1260
- String: string;
1261
- Boolean: string;
1262
- Any: string;
1263
- Void: string;
1264
- Unknown: string;
1265
- Null: string;
1266
- Undefined: string;
1267
- Object: string;
1268
- File: string;
1269
- Date: string;
1270
- Type: string;
1271
- Enum: string;
1272
- Interface: string;
1273
- Array: string;
1274
- Record: string;
1275
- Intersection: string;
1276
- Union: string;
1277
- };
1278
- CodeGenKeyword: {
1279
- UtilRequiredKeys: string;
1280
- };
1281
- ArrayType: (content: unknown) => string;
1282
- StringValue: (content: unknown) => string;
1283
- BooleanValue: (content: unknown) => string;
1284
- NumberValue: (content: unknown) => string;
1285
- NullValue: (content: unknown) => string;
1286
- UnionType: (content: unknown) => string;
1287
- ExpressionGroup: (content: unknown) => string;
1288
- IntersectionType: (content: unknown) => string;
1289
- RecordType: (content: unknown) => string;
1290
- TypeField: (content: unknown) => string;
1291
- InterfaceDynamicField: (content: unknown) => string;
1292
- EnumField: (content: unknown) => string;
1293
- EnumFieldsWrapper: (content: unknown) => string;
1294
- ObjectWrapper: (content: unknown) => string;
1295
- MultilineComment: (content: unknown) => string;
1296
- TypeWithGeneric: (content: unknown) => string;
1297
- };
1298
-
1299
- type PrimitiveTypeStructValue =
1300
- | string
1301
- | ((
1302
- schema: Record<string, unknown>,
1303
- parser: SchemaParser,
1304
- ) => string);
1305
-
1306
- type PrimitiveTypeStruct = Record<
1307
- "integer" | "number" | "boolean" | "object" | "file" | "string" | "array",
1308
- | string
1309
- | ({ $default: PrimitiveTypeStructValue } & Record<
1310
- string,
1311
- PrimitiveTypeStructValue
1312
- >)
1313
- >;
1314
-
1315
- interface GenerateApiParamsFromPath extends GenerateApiParamsBase {
1316
- /**
1317
- * path to swagger schema
1318
- */
1319
- input: string;
1320
- }
1321
-
1322
- interface GenerateApiParamsFromUrl extends GenerateApiParamsBase {
1323
- /**
1324
- * url to swagger schema
1325
- */
1326
- url: string;
1327
- }
1328
-
1329
- interface GenerateApiParamsFromSpecLiteral extends GenerateApiParamsBase {
1330
- /**
1331
- * swagger schema JSON
1332
- */
1333
- spec: swagger_schema_official.Spec;
1334
- }
1335
-
1336
- type GenerateApiParams =
1337
- | GenerateApiParamsFromPath
1338
- | GenerateApiParamsFromUrl
1339
- | GenerateApiParamsFromSpecLiteral;
1340
-
1341
- type BuildRouteParam = {
1342
- /** {bar} */
1343
- $match: string;
1344
- name: string;
1345
- required: boolean;
1346
- type: "string";
1347
- description: string;
1348
- schema: {
1349
- type: string;
1350
- };
1351
- in: "path" | "query";
1352
- };
1353
-
1354
- type BuildRoutePath = {
1355
- /** /foo/{bar}/baz */
1356
- originalRoute: string;
1357
- /** /foo/${bar}/baz */
1358
- route: string;
1359
- pathParams: BuildRouteParam[];
1360
- queryParams: BuildRouteParam[];
1361
- };
1362
-
1363
- interface Hooks {
1364
- /** calls before parse\process route path */
1365
- onPreBuildRoutePath: (routePath: string) => string | undefined;
1366
- /** calls after parse\process route path */
1367
- onBuildRoutePath: (data: BuildRoutePath) => BuildRoutePath | undefined;
1368
- /** calls before insert path param name into string path interpolation */
1369
- onInsertPathParam: (
1370
- paramName: string,
1371
- index: number,
1372
- arr: BuildRouteParam[],
1373
- resultRoute: string,
1374
- ) => string | undefined;
1375
- /** calls after parse schema component */
1376
- onCreateComponent: (
1377
- component: SchemaComponent,
1378
- ) => SchemaComponent | undefined;
1379
- /** calls before parse any kind of schema */
1380
- onPreParseSchema: (
1381
- originalSchema: unknown,
1382
- typeName: string,
1383
- schemaType: string,
1384
- ) => undefined;
1385
- /** calls after parse any kind of schema */
1386
- onParseSchema: (
1387
- originalSchema: unknown,
1388
- parsedSchema: unknown,
1389
- ) => unknown | undefined;
1390
- /** calls after parse route (return type: customized route (ParsedRoute), nothing change (void), false (ignore this route)) */
1391
- onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | false | undefined;
1392
- /** Start point of work this tool (after fetching schema) */
1393
- onInit?: <C extends GenerateApiConfiguration["config"]>(
1394
- configuration: C,
1395
- codeGenProcess: CodeGenProcess,
1396
- ) => C | undefined;
1397
- /** customize configuration object before sending it to ETA templates */
1398
- onPrepareConfig?: <C extends GenerateApiConfiguration>(
1399
- currentConfiguration: C,
1400
- ) => C | undefined;
1401
- /** customize route name as you need */
1402
- onCreateRouteName?: (
1403
- routeNameInfo: RouteNameInfo,
1404
- rawRouteInfo: RawRouteInfo,
1405
- ) => RouteNameInfo | undefined;
1406
- /** customize request params (path params, query params) */
1407
- onCreateRequestParams?: (
1408
- rawType: SchemaComponent["rawTypeData"],
1409
- ) => SchemaComponent["rawTypeData"] | undefined;
1410
- /** customize name of model type */
1411
- onFormatTypeName?: (
1412
- typeName: string,
1413
- rawTypeName?: string,
1414
- schemaType?: "type-name" | "enum-key",
1415
- ) => string | undefined;
1416
- /** customize name of route (operationId), you can do it with using onCreateRouteName too */
1417
- onFormatRouteName?: (
1418
- routeInfo: RawRouteInfo,
1419
- templateRouteName: string,
1420
- ) => string | undefined;
1421
- }
1422
-
1423
- type RouteNameRouteInfo = Record<string, unknown>;
1424
-
1425
- type RouteNameInfo = {
1426
- usage: string;
1427
- original: string;
1428
- duplicate: boolean;
1429
- };
1430
-
1431
- type SchemaTypePrimitiveContent = {
1432
- $parsedSchema: boolean;
1433
- schemaType: string;
1434
- type: string;
1435
- typeIdentifier: string;
1436
- name?: unknown;
1437
- description: string;
1438
- content: string;
1439
- };
1440
-
1441
- type SchemaTypeObjectContent = {
1442
- $$raw: {
1443
- type: string;
1444
- required: boolean;
1445
- $parsed: SchemaTypePrimitiveContent;
1446
- };
1447
- isRequired: boolean;
1448
- field: string;
1449
- }[];
1450
-
1451
- type SchemaTypeEnumContent = {
1452
- key: string;
1453
- type: string;
1454
- value: string;
1455
- };
1456
-
1457
- interface ParsedSchema<C> {
1458
- $parsedSchema: boolean;
1459
- schemaType: string;
1460
- type: string;
1461
- typeIdentifier: string;
1462
- name: string;
1463
- description?: string;
1464
- allFieldsAreOptional?: boolean;
1465
- content: C;
1466
- }
1467
-
1468
- interface PathArgInfo {
1469
- name: string;
1470
- optional: boolean;
1471
- type: string;
1472
- description?: string;
1473
- }
1474
-
1475
- interface SchemaComponent {
1476
- $ref: string;
1477
- typeName: string;
1478
- rawTypeData?: {
1479
- type: string;
1480
- required?: string[];
1481
- properties?: Record<
1482
- string,
1483
- {
1484
- name?: string;
1485
- type: string;
1486
- required: boolean;
1487
- $parsed?: SchemaTypePrimitiveContent;
1488
- }
1489
- >;
1490
- discriminator?: {
1491
- propertyName?: string;
1492
- };
1493
- $parsed: ParsedSchema<
1494
- | SchemaTypeObjectContent
1495
- | SchemaTypeEnumContent
1496
- | SchemaTypePrimitiveContent
1497
- >;
1498
- };
1499
- componentName: "schemas" | "paths";
1500
- typeData: ParsedSchema<
1501
- SchemaTypeObjectContent | SchemaTypeEnumContent | SchemaTypePrimitiveContent
1502
- > | null;
1503
- }
1504
-
1505
- declare enum RequestContentKind {
1506
- JSON = "JSON",
1507
- URL_ENCODED = "URL_ENCODED",
1508
- FORM_DATA = "FORM_DATA",
1509
- IMAGE = "IMAGE",
1510
- OTHER = "OTHER",
1511
- TEXT = "TEXT",
1512
- }
1513
-
1514
- interface RequestResponseInfo {
1515
- contentTypes: string[];
1516
- contentKind: RequestContentKind;
1517
- type: string;
1518
- description: string;
1519
- status: string | number;
1520
- isSuccess: boolean;
1521
- }
1522
-
1523
- type RawRouteInfo = {
1524
- operationId: string;
1525
- method: string;
1526
- route: string;
1527
- moduleName: string;
1528
- responsesTypes: RequestResponseInfo[];
1529
- description?: string;
1530
- tags?: string[];
1531
- summary?: string;
1532
- responses?: swagger_schema_official.Spec["responses"];
1533
- produces?: string[];
1534
- requestBody?: object;
1535
- consumes?: string[];
1536
- };
1537
-
1538
- interface ParsedRoute {
1539
- id: string;
1540
- jsDocLines: string;
1541
- namespace: string;
1542
- request: Request;
1543
- response: Response;
1544
- routeName: RouteNameInfo;
1545
- raw: RawRouteInfo;
1546
- }
1547
-
1548
- type ModelType = {
1549
- typeIdentifier: string;
1550
- name: string;
1551
- rawContent: string;
1552
- description: string;
1553
- content: string;
1554
- };
1555
-
1556
- declare enum SCHEMA_TYPES {
1557
- ARRAY = "array",
1558
- OBJECT = "object",
1559
- ENUM = "enum",
1560
- REF = "$ref",
1561
- PRIMITIVE = "primitive",
1562
- COMPLEX = "complex",
1563
- COMPLEX_ONE_OF = "oneOf",
1564
- COMPLEX_ANY_OF = "anyOf",
1565
- COMPLEX_ALL_OF = "allOf",
1566
- COMPLEX_NOT = "not",
1567
- COMPLEX_UNKNOWN = "__unknown",
1568
- }
1569
-
1570
- type MAIN_SCHEMA_TYPES =
1571
- | SCHEMA_TYPES.PRIMITIVE
1572
- | SCHEMA_TYPES.OBJECT
1573
- | SCHEMA_TYPES.ENUM;
1574
-
1575
- type ExtractingOptions = {
1576
- requestBodySuffix: string[];
1577
- responseBodySuffix: string[];
1578
- responseErrorSuffix: string[];
1579
- requestParamsSuffix: string[];
1580
- enumSuffix: string[];
1581
- discriminatorMappingSuffix: string[];
1582
- discriminatorAbstractPrefix: string[];
1583
- requestBodyNameResolver: (
1584
- name: string,
1585
- reservedNames: string,
1586
- ) => string | undefined;
1587
- responseBodyNameResolver: (
1588
- name: string,
1589
- reservedNames: string,
1590
- ) => string | undefined;
1591
- responseErrorNameResolver: (
1592
- name: string,
1593
- reservedNames: string,
1594
- ) => string | undefined;
1595
- requestParamsNameResolver: (
1596
- name: string,
1597
- reservedNames: string,
1598
- ) => string | undefined;
1599
- enumNameResolver: (name: string, reservedNames: string) => string | undefined;
1600
- discriminatorMappingNameResolver: (
1601
- name: string,
1602
- reservedNames: string,
1603
- ) => string | undefined;
1604
- discriminatorAbstractResolver: (
1605
- name: string,
1606
- reservedNames: string,
1607
- ) => string | undefined;
1608
- };
1609
-
1610
- interface GenerateApiConfiguration {
1611
- apiConfig: {
1612
- baseUrl: string;
1613
- title: string;
1614
- version: string;
1615
- description: string[];
1616
- hasDescription: boolean;
1617
- };
1618
- config: {
1619
- input: string;
1620
- output: string;
1621
- url: string;
1622
- spec: unknown;
1623
- fileName: string;
1624
- templatePaths: {
1625
- /** `templates/base` */
1626
- base: string;
1627
- /** `templates/default` */
1628
- default: string;
1629
- /** `templates/modular` */
1630
- modular: string;
1631
- /** usage path if `--templates` option is not set */
1632
- original: string;
1633
- /** custom path to templates (`--templates`) */
1634
- custom: string | null;
1635
- };
1636
- authorizationToken?: string;
1637
- generateResponses: boolean;
1638
- defaultResponseAsSuccess: boolean;
1639
- generateRouteTypes: boolean;
1640
- generateClient: boolean;
1641
- generateUnionEnums: boolean;
1642
- swaggerSchema: object;
1643
- originalSchema: object;
1644
- componentsMap: Record<string, SchemaComponent>;
1645
- convertedFromSwagger2: boolean;
1646
- moduleNameIndex: number;
1647
- moduleNameFirstTag: boolean;
1648
- extraTemplates: { name: string; path: string }[];
1649
- disableStrictSSL: boolean;
1650
- disableProxy: boolean;
1651
- extractRequestParams: boolean;
1652
- unwrapResponseData: boolean;
1653
- sortTypes: boolean;
1654
- sortRoutes: boolean;
1655
- singleHttpClient: boolean;
1656
- typePrefix: string;
1657
- typeSuffix: string;
1658
- enumKeyPrefix: string;
1659
- enumKeySuffix: string;
1660
- patch: boolean;
1661
- cleanOutput: boolean;
1662
- debug: boolean;
1663
- anotherArrayType: boolean;
1664
- extractRequestBody: boolean;
1665
- httpClientType: "axios" | "fetch";
1666
- addReadonly: boolean;
1667
- extractResponseBody: boolean;
1668
- extractResponseError: boolean;
1669
- extractEnums: boolean;
1670
- fixInvalidTypeNamePrefix: string;
1671
- fixInvalidEnumKeyPrefix: string;
1672
- defaultResponseType: string;
1673
- toJS: boolean;
1674
- disableThrowOnError: boolean;
1675
- silent: boolean;
1676
- hooks: Hooks;
1677
- enumNamesAsValues: boolean;
1678
- version: string;
1679
- compilerTsConfig: Record<string, unknown>;
1680
- enumKeyResolverName: string;
1681
- typeNameResolverName: string;
1682
- specificArgNameResolverName: string;
1683
- /** do not use constructor args, it can break functionality of this property, just send class reference */
1684
- customTranslator?: new (
1685
- ...args: never[]
1686
- ) => typeof Translator;
1687
- internalTemplateOptions: {
1688
- addUtilRequiredKeysType: boolean;
1689
- };
1690
- componentTypeNameResolver: typeof ComponentTypeNameResolver;
1691
- fileNames: {
1692
- dataContracts: string;
1693
- routeTypes: string;
1694
- httpClient: string;
1695
- outOfModuleApi: string;
1696
- };
1697
- templatesToRender: {
1698
- api: string;
1699
- dataContracts: string;
1700
- httpClient: string;
1701
- routeTypes: string;
1702
- routeName: string;
1703
- dataContractJsDoc: string;
1704
- interfaceDataContract: string;
1705
- typeDataContract: string;
1706
- enumDataContract: string;
1707
- objectFieldJsDoc: string;
1708
- };
1709
- routeNameDuplicatesMap: Map<string, string>;
1710
- apiClassName: string;
1711
- requestOptions?: RequestInit;
1712
- extractingOptions: ExtractingOptions;
1713
- };
1714
- modelTypes: ModelType[];
1715
- hasFormDataRoutes: boolean;
1716
- hasSecurityRoutes: boolean;
1717
- hasQueryRoutes: boolean;
1718
- generateResponses: boolean;
1719
- routes: {
1720
- outOfModule: ParsedRoute[];
1721
- combined?: {
1722
- moduleName: string;
1723
- routes: ParsedRoute[];
1724
- }[];
1725
- };
1726
- requestOptions?: null | Partial<RequestInit>;
1727
- utils: {
1728
- formatDescription: (description: string, inline?: boolean) => string;
1729
- internalCase: (value: string) => string;
1730
- /** @deprecated */
1731
- classNameCase: (value: string) => string;
1732
- pascalCase: (value: string) => string;
1733
- getInlineParseContent: (
1734
- rawTypeData: SchemaComponent["rawTypeData"],
1735
- typeName?: string,
1736
- ) => string;
1737
- getParseContent: (
1738
- rawTypeData: SchemaComponent["rawTypeData"],
1739
- typeName?: string,
1740
- ) => ModelType;
1741
- getComponentByRef: (ref: string) => SchemaComponent;
1742
- parseSchema: (
1743
- rawSchema: string | SchemaComponent["rawTypeData"],
1744
- typeName?: string,
1745
- formattersMap?: Record<MAIN_SCHEMA_TYPES, (content: ModelType) => string>,
1746
- ) => ModelType;
1747
- formatters: Record<
1748
- MAIN_SCHEMA_TYPES,
1749
- (content: string | object | string[] | object[]) => string
1750
- >;
1751
- inlineExtraFormatters: Record<
1752
- Exclude<MAIN_SCHEMA_TYPES, SCHEMA_TYPES.PRIMITIVE>,
1753
- (schema: ModelType) => string
1754
- >;
1755
- formatModelName: (name: string) => string;
1756
- fmtToJSDocLine: (line: string, params?: { eol?: boolean }) => string;
1757
- _: lodash.LoDashStatic;
1758
- require: (path: string) => unknown;
1759
- };
1760
- }
1761
-
1762
- type FileInfo = {
1763
- /** @example myFilename */
1764
- fileName: string;
1765
- /** @example .d.ts */
1766
- fileExtension: string;
1767
- /** content of the file */
1768
- fileContent: string;
1769
- };
1770
-
1771
- interface GenerateApiOutput {
1772
- configuration: GenerateApiConfiguration;
1773
- files: FileInfo[];
1774
- createFile: (params: {
1775
- path: string;
1776
- fileName: string;
1777
- content: string;
1778
- withPrefix: boolean;
1779
- }) => void;
1780
- renderTemplate: (
1781
- templateContent: string,
1782
- data: Record<string, unknown>,
1783
- etaOptions?: Partial<eta.EtaConfig>,
1784
- ) => Promise<string> | string;
1785
- getTemplate: (params: {
1786
- fileName?: string;
1787
- name?: string;
1788
- path?: string;
1789
- }) => string;
1790
- formatTSContent: (content: string) => Promise<string>;
1791
- }
1792
-
1793
- declare function generateApi(
1794
- params: GenerateApiParams,
1795
- ): Promise<GenerateApiOutput>;
1796
-
1797
- interface GenerateTemplatesParams {
1798
- cleanOutput?: boolean;
1799
- output?: string;
1800
- httpClientType?: HttpClientType;
1801
- modular?: boolean;
1802
- silent?: boolean;
1803
- }
1804
-
1805
- interface GenerateTemplatesOutput
1806
- extends Pick<GenerateApiOutput, "files" | "createFile"> {}
1807
-
1808
- declare function generateTemplates(
1809
- params: GenerateTemplatesParams,
1810
- ): Promise<GenerateTemplatesOutput>;
1811
-
1812
- export { type GenerateApiConfiguration, type GenerateApiOutput, type GenerateApiParams, type GenerateTemplatesOutput, type GenerateTemplatesParams, type Hooks, type ModelType, type ParsedRoute, type ParsedSchema, type PathArgInfo, type RawRouteInfo, RequestContentKind, type RequestResponseInfo, type RouteNameInfo, type RouteNameRouteInfo, SCHEMA_TYPES, type SchemaComponent, type SchemaTypeEnumContent, type SchemaTypeObjectContent, type SchemaTypePrimitiveContent, generateApi, generateTemplates };