swagger-typescript-api 13.0.9 → 13.0.11

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.
Files changed (69) hide show
  1. package/README.md +3 -3
  2. package/dist/chunk-3OGOYA5P.cjs +104 -0
  3. package/dist/chunk-3OGOYA5P.cjs.map +1 -0
  4. package/dist/chunk-R4CYI34W.js +65 -0
  5. package/dist/chunk-R4CYI34W.js.map +1 -0
  6. package/dist/cli.cjs +43 -0
  7. package/dist/cli.cjs.map +1 -0
  8. package/dist/cli.js +36 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/lib.cjs +21 -0
  11. package/dist/lib.cjs.map +1 -0
  12. package/dist/lib.js +4 -0
  13. package/dist/lib.js.map +1 -0
  14. package/index.d.ts +1 -1
  15. package/package.json +25 -14
  16. package/templates/base/http-clients/axios-http-client.ejs +3 -0
  17. package/templates/base/http-clients/fetch-http-client.ejs +3 -3
  18. package/cli/constants.js +0 -6
  19. package/cli/execute.js +0 -180
  20. package/cli/index.js +0 -94
  21. package/cli/operations/display-help.js +0 -177
  22. package/cli/operations/display-version.js +0 -5
  23. package/cli/parse-args.js +0 -24
  24. package/cli/process-option.js +0 -75
  25. package/index.js +0 -344
  26. package/src/code-formatter.js +0 -114
  27. package/src/code-gen-process.js +0 -569
  28. package/src/commands/generate-templates/configuration.js +0 -31
  29. package/src/commands/generate-templates/index.js +0 -10
  30. package/src/commands/generate-templates/templates-gen-process.js +0 -205
  31. package/src/component-type-name-resolver.js +0 -42
  32. package/src/configuration.js +0 -445
  33. package/src/constants.js +0 -77
  34. package/src/index.js +0 -16
  35. package/src/schema-components-map.js +0 -76
  36. package/src/schema-parser/base-schema-parsers/array.js +0 -41
  37. package/src/schema-parser/base-schema-parsers/complex.js +0 -49
  38. package/src/schema-parser/base-schema-parsers/discriminator.js +0 -305
  39. package/src/schema-parser/base-schema-parsers/enum.js +0 -156
  40. package/src/schema-parser/base-schema-parsers/object.js +0 -103
  41. package/src/schema-parser/base-schema-parsers/primitive.js +0 -61
  42. package/src/schema-parser/complex-schema-parsers/all-of.js +0 -26
  43. package/src/schema-parser/complex-schema-parsers/any-of.js +0 -27
  44. package/src/schema-parser/complex-schema-parsers/not.js +0 -9
  45. package/src/schema-parser/complex-schema-parsers/one-of.js +0 -27
  46. package/src/schema-parser/mono-schema-parser.js +0 -46
  47. package/src/schema-parser/schema-formatters.js +0 -164
  48. package/src/schema-parser/schema-parser-fabric.js +0 -130
  49. package/src/schema-parser/schema-parser.js +0 -295
  50. package/src/schema-parser/schema-utils.js +0 -319
  51. package/src/schema-parser/util/enum-key-resolver.js +0 -24
  52. package/src/schema-routes/schema-routes.js +0 -1208
  53. package/src/schema-routes/util/specific-arg-name-resolver.js +0 -24
  54. package/src/schema-walker.js +0 -91
  55. package/src/swagger-schema-resolver.js +0 -195
  56. package/src/templates-worker.js +0 -243
  57. package/src/translators/javascript.js +0 -81
  58. package/src/translators/translator.js +0 -33
  59. package/src/type-name-formatter.js +0 -111
  60. package/src/util/file-system.js +0 -95
  61. package/src/util/id.js +0 -7
  62. package/src/util/internal-case.js +0 -7
  63. package/src/util/logger.js +0 -142
  64. package/src/util/name-resolver.js +0 -103
  65. package/src/util/object-assign.js +0 -17
  66. package/src/util/pascal-case.js +0 -7
  67. package/src/util/random.js +0 -11
  68. package/src/util/request.js +0 -63
  69. package/src/util/sort-by-property.js +0 -15
@@ -1,205 +0,0 @@
1
- import path from "node:path";
2
- import url from "node:url";
3
- import { FileSystem } from "../../util/file-system.js";
4
- import { Logger } from "../../util/logger.js";
5
- import { TemplatesGenConfig } from "./configuration.js";
6
-
7
- const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
8
-
9
- class TemplatesGenProcess {
10
- /**
11
- * @type {TemplatesGenConfig}
12
- */
13
- config;
14
- /**
15
- * @type {FileSystem}
16
- */
17
- fileSystem;
18
- /**
19
- * @type {Logger}
20
- */
21
- logger;
22
-
23
- rootDir = path.resolve(__dirname, "../../../");
24
-
25
- paths = {
26
- baseTemplates: "templates/base",
27
- httpClientTemplates: "templates/base/http-clients",
28
- moduleApiTemplates: "templates/modular",
29
- defaultApiTemplates: "templates/default",
30
- };
31
-
32
- importTemplatePrefixes = ["@base", "@modular", "@default"];
33
-
34
- constructor(config) {
35
- this.config = new TemplatesGenConfig(config);
36
- this.logger = new Logger(this);
37
- this.fileSystem = new FileSystem(this);
38
- }
39
-
40
- /**
41
- * @return {Promise<GenerateTemplatesOutput>}
42
- */
43
- async start() {
44
- this.logger.event(
45
- 'start generating source templates ".ejs" for code generator',
46
- );
47
-
48
- const templates = this.getTemplates();
49
-
50
- if (this.config.output) {
51
- this.logger.log("preparing output directory for source templates");
52
- const outputPath = path.resolve(process.cwd(), this.config.output);
53
-
54
- if (this.fileSystem.pathIsExist(outputPath)) {
55
- if (this.config.cleanOutput) {
56
- this.fileSystem.cleanDir(outputPath);
57
- }
58
- } else {
59
- this.fileSystem.createDir(outputPath);
60
- }
61
-
62
- templates.forEach((template) => {
63
- const templateName = this.fileSystem.cropExtension(template.name);
64
- const templateEjsPath = path.resolve(outputPath, `${templateName}.ejs`);
65
- const templateEtaPath = path.resolve(outputPath, `${templateName}.eta`);
66
- const templateEjsPathExist =
67
- this.fileSystem.pathIsExist(templateEjsPath);
68
- const templateEtaPathExist =
69
- this.fileSystem.pathIsExist(templateEtaPath);
70
-
71
- const templateNotExist = !templateEjsPathExist && !templateEtaPathExist;
72
-
73
- if (templateNotExist) {
74
- this.fileSystem.createFile({
75
- path: outputPath,
76
- fileName: template.name,
77
- content: template.content,
78
- withPrefix: false,
79
- });
80
- } else if (this.config.rewrite) {
81
- if (templateEjsPathExist) {
82
- this.fileSystem.createFile({
83
- path: outputPath,
84
- fileName: `${templateName}.ejs`,
85
- content: template.content,
86
- withPrefix: false,
87
- });
88
- } else if (templateEtaPathExist) {
89
- this.fileSystem.createFile({
90
- path: outputPath,
91
- fileName: `${templateName}.eta`,
92
- content: template.content,
93
- withPrefix: false,
94
- });
95
- }
96
- }
97
- });
98
-
99
- this.logger.success(
100
- `source templates has been successfully created in "${outputPath}"`,
101
- );
102
- }
103
-
104
- return {
105
- files: templates,
106
- configuration: this.config,
107
- createFile: this.fileSystem.createFile,
108
- };
109
- }
110
-
111
- getTemplates = () => {
112
- const outputFiles = [];
113
- const baseTemplates = this.getTemplateNamesFromDir(
114
- this.paths.baseTemplates,
115
- );
116
- const httpClientTemplates = this.getTemplateNamesFromDir(
117
- this.paths.httpClientTemplates,
118
- );
119
- const apiTemplatesPath = this.config.modular
120
- ? this.paths.moduleApiTemplates
121
- : this.paths.defaultApiTemplates;
122
- const apiTemplates = this.getTemplateNamesFromDir(apiTemplatesPath);
123
-
124
- const usingHttpClientTemplate = httpClientTemplates.find((template) =>
125
- template.startsWith(`${this.config.httpClientType}-`),
126
- );
127
-
128
- let httpClientTemplateContent = "";
129
-
130
- if (usingHttpClientTemplate) {
131
- httpClientTemplateContent = this.fixTemplateContent(
132
- this.getTemplateContent(
133
- `${this.paths.httpClientTemplates}/${usingHttpClientTemplate}`,
134
- ),
135
- );
136
- }
137
-
138
- for (const fileName of baseTemplates) {
139
- const templateContent =
140
- (fileName === "http-client.ejs" && httpClientTemplateContent) ||
141
- this.fixTemplateContent(
142
- this.getTemplateContent(`${this.paths.baseTemplates}/${fileName}`),
143
- );
144
-
145
- outputFiles.push({
146
- name: fileName,
147
- content: templateContent,
148
- });
149
- }
150
-
151
- for (const fileName of apiTemplates) {
152
- outputFiles.push({
153
- name: fileName,
154
- content: this.fixTemplateContent(
155
- this.getTemplateContent(`${apiTemplatesPath}/${fileName}`),
156
- ),
157
- });
158
- }
159
-
160
- return outputFiles;
161
- };
162
-
163
- fixTemplateContent = (content) => {
164
- // includeFile("@base/
165
- const importsRegExp1 = new RegExp(
166
- `includeFile\\("(${this.importTemplatePrefixes
167
- .map((v) => `(${v})`)
168
- .join("|")})/`,
169
- "g",
170
- );
171
- // includeFile(`@base/
172
- const importsRegExp2 = new RegExp(
173
- `includeFile\\(\`(${this.importTemplatePrefixes
174
- .map((v) => `(${v})`)
175
- .join("|")})/`,
176
- "g",
177
- );
178
- // includeFile('@base/
179
- const importsRegExp3 = new RegExp(
180
- `includeFile\\('(${this.importTemplatePrefixes
181
- .map((v) => `(${v})`)
182
- .join("|")})/`,
183
- "g",
184
- );
185
-
186
- return content
187
- .replace(importsRegExp1, 'includeFile("./')
188
- .replace(importsRegExp2, "includeFile(`./")
189
- .replace(importsRegExp3, "includeFile('./");
190
- };
191
-
192
- getTemplateNamesFromDir = (dir) => {
193
- return this.fileSystem
194
- .readDir(path.resolve(this.rootDir, dir))
195
- .filter((file) => file.endsWith(".ejs"));
196
- };
197
-
198
- getTemplateContent = (pathToFile) => {
199
- return this.fileSystem.getFileContent(
200
- path.resolve(this.rootDir, pathToFile),
201
- );
202
- };
203
- }
204
-
205
- export { TemplatesGenProcess };
@@ -1,42 +0,0 @@
1
- import { NameResolver } from "./util/name-resolver.js";
2
- import { getRandomInt } from "./util/random.js";
3
-
4
- class ComponentTypeNameResolver extends NameResolver {
5
- counter = 1;
6
- fallbackNameCounter = 1;
7
- countersByVariant = new Map();
8
-
9
- /**
10
- * @param {CodeGenConfig} config;
11
- * @param {Logger} logger;
12
- * @param {string[]} reservedNames
13
- */
14
- constructor(config, logger, reservedNames) {
15
- super(config, logger, reservedNames, (variants) => {
16
- const randomVariant = variants[getRandomInt(0, variants.length - 1)];
17
- if (randomVariant) {
18
- if (!this.countersByVariant.has(randomVariant)) {
19
- this.countersByVariant.set(randomVariant, 0);
20
- }
21
- const variantCounter = this.countersByVariant.get(randomVariant) + 1;
22
- this.countersByVariant.set(randomVariant, variantCounter);
23
- const dirtyResolvedName = `${randomVariant}${variantCounter}`;
24
- this.logger.debug(
25
- "generated dirty resolved type name for component - ",
26
- dirtyResolvedName,
27
- );
28
- return dirtyResolvedName;
29
- }
30
-
31
- const fallbackName = `${this.config.componentTypeNameResolver}${this
32
- .fallbackNameCounter++}`;
33
- this.logger.debug(
34
- "generated fallback type name for component - ",
35
- fallbackName,
36
- );
37
- return fallbackName;
38
- });
39
- }
40
- }
41
-
42
- export { ComponentTypeNameResolver };
@@ -1,445 +0,0 @@
1
- import { cosmiconfigSync } from "cosmiconfig";
2
- import _ from "lodash";
3
- import ts from "typescript";
4
- import { ComponentTypeNameResolver } from "./component-type-name-resolver.js";
5
- import * as CONSTANTS from "./constants.js";
6
- import { objectAssign } from "./util/object-assign.js";
7
-
8
- const TsKeyword = {
9
- Number: "number",
10
- String: "string",
11
- Boolean: "boolean",
12
- Any: "any",
13
- Void: "void",
14
- Unknown: "unknown",
15
- Null: "null",
16
- Undefined: "undefined",
17
- Object: "object",
18
- File: "File",
19
- Date: "Date",
20
- Type: "type",
21
- Enum: "enum",
22
- Interface: "interface",
23
- Array: "Array",
24
- Record: "Record",
25
- Intersection: "&",
26
- Union: "|",
27
- };
28
-
29
- const TsCodeGenKeyword = {
30
- UtilRequiredKeys: "UtilRequiredKeys",
31
- };
32
-
33
- /**
34
- * @type {GenerateApiConfiguration["config"]}}
35
- */
36
- class CodeGenConfig {
37
- version = CONSTANTS.PROJECT_VERSION;
38
- /** CLI flag */
39
- templates = "";
40
- /** CLI flag */
41
- generateResponses = false;
42
- /** CLI flag */
43
- defaultResponseAsSuccess = false;
44
- /** CLI flag */
45
- generateRouteTypes = false;
46
- /** CLI flag */
47
- generateClient = true;
48
- /** CLI flag */
49
- generateUnionEnums = false;
50
- /** CLI flag */
51
- addReadonly = false;
52
- enumNamesAsValues = false;
53
- /** parsed swagger schema from getSwaggerObject() */
54
-
55
- /** parsed swagger schema ref */
56
- swaggerSchema = null;
57
- /** original (converted to json) swagger schema ref */
58
- originalSchema = null;
59
-
60
- /** { "#/components/schemas/Foo": @TypeInfo, ... } */
61
- componentsMap = {};
62
- /** flag for catching conversion from swagger 2.0 */
63
- convertedFromSwagger2 = false;
64
-
65
- /** url index from paths used for merging into modules */
66
- moduleNameIndex = 0;
67
-
68
- /** use the first tag for the module name */
69
- moduleNameFirstTag = false;
70
- disableStrictSSL = false;
71
- disableProxy = false;
72
- extractRequestParams = false;
73
- extractRequestBody = false;
74
- extractResponseBody = false;
75
- extractResponseError = false;
76
- extractResponses = false;
77
- extractEnums = false;
78
- fileNames = {
79
- dataContracts: "data-contracts",
80
- routeTypes: "route-types",
81
- httpClient: "http-client",
82
- outOfModuleApi: "Common",
83
- };
84
- routeNameDuplicatesMap = new Map();
85
- prettierOptions = { ...CONSTANTS.PRETTIER_OPTIONS };
86
- hooks = {
87
- onPreBuildRoutePath: (routePath) => void 0,
88
- onBuildRoutePath: (routeData) => void 0,
89
- onInsertPathParam: (pathParam) => void 0,
90
- onCreateComponent: (schema) => schema,
91
- onPreParseSchema: (originalSchema, typeName, schemaType) => void 0,
92
- onParseSchema: (originalSchema, parsedSchema) => parsedSchema,
93
- onCreateRoute: (routeData) => routeData,
94
- onInit: (config, codeGenProcess) => config,
95
- onPrepareConfig: (apiConfig) => apiConfig,
96
- onCreateRequestParams: (rawType) => {},
97
- onCreateRouteName: () => {},
98
- onFormatTypeName: (typeName, rawTypeName, schemaType) => {},
99
- onFormatRouteName: (routeInfo, templateRouteName) => {},
100
- };
101
- defaultResponseType;
102
- singleHttpClient = false;
103
- httpClientType = CONSTANTS.HTTP_CLIENT.FETCH;
104
- unwrapResponseData = false;
105
- disableThrowOnError = false;
106
- sortTypes = false;
107
- sortRoutes = false;
108
- templatePaths = {
109
- /** `templates/base` */
110
- base: "",
111
- /** `templates/default` */
112
- default: "",
113
- /** `templates/modular` */
114
- modular: "",
115
- /** usage path if `--templates` option is not set */
116
- original: "",
117
- /** custom path to templates (`--templates`) */
118
- custom: "",
119
- };
120
- /** Record<templateName, templateContent> */
121
- templatesToRender = {
122
- api: "",
123
- dataContracts: "",
124
- dataContractJsDoc: "",
125
- interfaceDataContract: "",
126
- typeDataContract: "",
127
- enumDataContract: "",
128
- objectFieldJsDoc: "",
129
- httpClient: "",
130
- routeTypes: "",
131
- routeName: "",
132
- };
133
- /**
134
- * @type {Record<string, (...args: any[]) => MonoSchemaParser>}
135
- */
136
- schemaParsers = {};
137
- toJS = false;
138
- silent = false;
139
- typePrefix = "";
140
- typeSuffix = "";
141
- enumKeyPrefix = "";
142
- enumKeySuffix = "";
143
- patch = false;
144
- /** @type {ComponentTypeNameResolver} */
145
- componentTypeNameResolver;
146
- /** name of the main exported class */
147
- apiClassName = "Api";
148
- debug = false;
149
- anotherArrayType = false;
150
- internalTemplateOptions = {
151
- addUtilRequiredKeysType: false,
152
- };
153
- extraTemplates = [];
154
- input = "";
155
- modular = false;
156
- output = "";
157
- url = "";
158
- cleanOutput = false;
159
- spec = null;
160
- fileName = "Api.ts";
161
- authorizationToken = void 0;
162
- requestOptions = null;
163
-
164
- jsPrimitiveTypes = [];
165
- jsEmptyTypes = [];
166
- fixInvalidTypeNamePrefix = "Type";
167
- fixInvalidEnumKeyPrefix = "Value";
168
-
169
- enumKeyResolverName = "Value";
170
- typeNameResolverName = "ComponentType";
171
- specificArgNameResolverName = "arg";
172
-
173
- successResponseStatusRange = [200, 299];
174
-
175
- /** @type {ExtractingOptions} */
176
- extractingOptions = {
177
- requestBodySuffix: ["Payload", "Body", "Input"],
178
- requestParamsSuffix: ["Params"],
179
- responseBodySuffix: ["Data", "Result", "Output"],
180
- responseErrorSuffix: [
181
- "Error",
182
- "Fail",
183
- "Fails",
184
- "ErrorData",
185
- "HttpError",
186
- "BadResponse",
187
- ],
188
- enumSuffix: ["Enum"],
189
- discriminatorMappingSuffix: ["Mapping", "Mapper", "MapType"],
190
- discriminatorAbstractPrefix: [
191
- "Base",
192
- "Abstract",
193
- "Discriminator",
194
- "Internal",
195
- "Polymorph",
196
- ],
197
- };
198
-
199
- compilerTsConfig = {
200
- module: ts.ModuleKind.ESNext,
201
- noImplicitReturns: true,
202
- alwaysStrict: true,
203
- target: ts.ScriptTarget.ESNext,
204
- declaration: true,
205
- noImplicitAny: false,
206
- sourceMap: false,
207
- removeComments: false,
208
- disableSizeLimit: true,
209
- esModuleInterop: true,
210
- emitDecoratorMetadata: true,
211
- skipLibCheck: true,
212
- };
213
- customTranslator;
214
-
215
- Ts = {
216
- Keyword: _.cloneDeep(TsKeyword),
217
- CodeGenKeyword: _.cloneDeep(TsCodeGenKeyword),
218
- /**
219
- * $A[] or Array<$A>
220
- */
221
- ArrayType: (content) => {
222
- if (this.anotherArrayType) {
223
- return this.Ts.TypeWithGeneric(this.Ts.Keyword.Array, [content]);
224
- }
225
-
226
- return `${this.Ts.ExpressionGroup(content)}[]`;
227
- },
228
- /**
229
- * "$A"
230
- */
231
- StringValue: (content) => `"${content}"`,
232
- /**
233
- * $A
234
- */
235
- BooleanValue: (content) => `${content}`,
236
- /**
237
- * $A
238
- */
239
- NumberValue: (content) => `${content}`,
240
- /**
241
- * $A
242
- */
243
- NullValue: (content) => "null",
244
- /**
245
- * $A1 | $A2
246
- */
247
- UnionType: (contents) =>
248
- _.join(_.uniq(contents), ` ${this.Ts.Keyword.Union} `),
249
- /**
250
- * ($A1)
251
- */
252
- ExpressionGroup: (content) => (content ? `(${content})` : ""),
253
- /**
254
- * $A1 & $A2
255
- */
256
- IntersectionType: (contents) =>
257
- _.join(_.uniq(contents), ` ${this.Ts.Keyword.Intersection} `),
258
- /**
259
- * Record<$A1, $A2>
260
- */
261
- RecordType: (key, value) =>
262
- this.Ts.TypeWithGeneric(this.Ts.Keyword.Record, [key, value]),
263
- /**
264
- * readonly $key?:$value
265
- */
266
- TypeField: ({ readonly, key, optional, value }) =>
267
- _.compact([
268
- readonly && "readonly ",
269
- key,
270
- optional && "?",
271
- ": ",
272
- value,
273
- ]).join(""),
274
- /**
275
- * [key: $A1]: $A2
276
- */
277
- InterfaceDynamicField: (key, value) => `[key: ${key}]: ${value}`,
278
-
279
- /**
280
- * EnumName.EnumKey
281
- */
282
- EnumUsageKey: (enumStruct, key) => `${enumStruct}.${key}`,
283
- /**
284
- * $A1 = $A2
285
- */
286
- EnumField: (key, value) => `${key} = ${value}`,
287
- /**
288
- * $A0.key = $A0.value,
289
- * $A1.key = $A1.value,
290
- * $AN.key = $AN.value,
291
- */
292
- EnumFieldsWrapper: (contents) =>
293
- _.map(
294
- contents,
295
- ({ key, value }) => ` ${this.Ts.EnumField(key, value)}`,
296
- ).join(",\n"),
297
- /**
298
- * {\n $A \n}
299
- */
300
- ObjectWrapper: (content) => `{\n${content}\n}`,
301
- /**
302
- * /** $A *\/
303
- */
304
- MultilineComment: (contents, formatFn) =>
305
- [
306
- ...(contents.length === 1
307
- ? [`/** ${contents[0]} */`]
308
- : ["/**", ...contents.map((content) => ` * ${content}`), " */"]),
309
- ].map((part) => `${formatFn ? formatFn(part) : part}\n`),
310
- /**
311
- * $A1<...$A2.join(,)>
312
- */
313
- TypeWithGeneric: (typeName, genericArgs) => {
314
- return `${typeName}${
315
- genericArgs.length ? `<${genericArgs.join(",")}>` : ""
316
- }`;
317
- },
318
- /**
319
- * [$A1, $A2, ...$AN]
320
- */
321
- Tuple: (values) => {
322
- return `[${values.join(", ")}]`;
323
- },
324
- };
325
-
326
- /**
327
- * swagger schema type -> typescript type
328
- * https://json-schema.org/understanding-json-schema/reference/string.html#dates-and-times
329
- * @type {Record<string, string | ((schema: any, parser: SchemaParser) => string) | ({ $default: string } & Record<string, string | ((schema: any, parser: SchemaParser) => string)>)>}
330
- */
331
- primitiveTypes = {
332
- integer: () => this.Ts.Keyword.Number,
333
- number: () => this.Ts.Keyword.Number,
334
- boolean: () => this.Ts.Keyword.Boolean,
335
- object: () => this.Ts.Keyword.Object,
336
- file: () => this.Ts.Keyword.File,
337
- string: {
338
- $default: () => this.Ts.Keyword.String,
339
-
340
- /** formats */
341
- binary: () => this.Ts.Keyword.File,
342
- file: () => this.Ts.Keyword.File,
343
- "date-time": () => this.Ts.Keyword.String,
344
- time: () => this.Ts.Keyword.String,
345
- date: () => this.Ts.Keyword.String,
346
- duration: () => this.Ts.Keyword.String,
347
- email: () => this.Ts.Keyword.String,
348
- "idn-email": () => this.Ts.Keyword.String,
349
- "idn-hostname": () => this.Ts.Keyword.String,
350
- ipv4: () => this.Ts.Keyword.String,
351
- ipv6: () => this.Ts.Keyword.String,
352
- uuid: () => this.Ts.Keyword.String,
353
- uri: () => this.Ts.Keyword.String,
354
- "uri-reference": () => this.Ts.Keyword.String,
355
- "uri-template": () => this.Ts.Keyword.String,
356
- "json-pointer": () => this.Ts.Keyword.String,
357
- "relative-json-pointer": () => this.Ts.Keyword.String,
358
- regex: () => this.Ts.Keyword.String,
359
- },
360
- };
361
-
362
- templateInfos = [
363
- { name: "api", fileName: "api" },
364
- { name: "dataContracts", fileName: "data-contracts" },
365
- { name: "dataContractJsDoc", fileName: "data-contract-jsdoc" },
366
- { name: "interfaceDataContract", fileName: "interface-data-contract" },
367
- { name: "typeDataContract", fileName: "type-data-contract" },
368
- { name: "enumDataContract", fileName: "enum-data-contract" },
369
- { name: "objectFieldJsDoc", fileName: "object-field-jsdoc" },
370
- { name: "httpClient", fileName: "http-client" },
371
- { name: "routeTypes", fileName: "route-types" },
372
- { name: "routeName", fileName: "route-name" },
373
- ];
374
-
375
- templateExtensions = [".eta", ".ejs"];
376
-
377
- /**
378
- * @param config {Partial<GenerateApiConfiguration['config']>}
379
- */
380
- constructor({
381
- prettierOptions = getDefaultPrettierOptions(),
382
- codeGenConstructs,
383
- primitiveTypeConstructs,
384
- constants,
385
- templateInfos,
386
- hooks,
387
- ...otherConfig
388
- }) {
389
- objectAssign(this.Ts, codeGenConstructs);
390
- objectAssign(this.primitiveTypes, primitiveTypeConstructs);
391
-
392
- this.defaultResponseType = this.Ts.Keyword.Void;
393
-
394
- this.update({
395
- ...otherConfig,
396
- prettierOptions:
397
- prettierOptions === undefined
398
- ? getDefaultPrettierOptions()
399
- : prettierOptions,
400
- hooks: _.merge(this.hooks, hooks || {}),
401
- constants: {
402
- ...CONSTANTS,
403
- ...constants,
404
- },
405
- templateInfos: templateInfos || this.templateInfos,
406
- });
407
-
408
- this.jsPrimitiveTypes = [
409
- this.Ts.Keyword.Number,
410
- this.Ts.Keyword.String,
411
- this.Ts.Keyword.Boolean,
412
- ];
413
- this.jsEmptyTypes = [this.Ts.Keyword.Null, this.Ts.Keyword.Undefined];
414
- this.componentTypeNameResolver = new ComponentTypeNameResolver(
415
- this,
416
- null,
417
- [],
418
- );
419
- }
420
-
421
- /**
422
- *
423
- * @param update {Partial<GenerateApiConfiguration["config"]>}
424
- */
425
- update = (update) => {
426
- objectAssign(this, update);
427
- };
428
- }
429
-
430
- const getDefaultPrettierOptions = () => {
431
- const prettier = cosmiconfigSync("prettier", {
432
- searchStrategy: "global",
433
- }).search();
434
-
435
- if (prettier) {
436
- return {
437
- ...prettier.config,
438
- parser: "typescript",
439
- };
440
- }
441
-
442
- return { ...CONSTANTS.PRETTIER_OPTIONS };
443
- };
444
-
445
- export { CodeGenConfig };