@accelbyte/codegen 1.0.0-alpha.3 → 1.0.0-alpha.7

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.
@@ -11,10 +11,7 @@ var _ = require('lodash');
11
11
  var fastJsonPatch = require('fast-json-patch');
12
12
  var https = require('https');
13
13
 
14
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
-
16
- function _interopNamespace(e) {
17
- if (e && e.__esModule) return e;
14
+ function _interopNamespaceDefault(e) {
18
15
  var n = Object.create(null);
19
16
  if (e) {
20
17
  Object.keys(e).forEach(function (k) {
@@ -22,25 +19,18 @@ function _interopNamespace(e) {
22
19
  var d = Object.getOwnPropertyDescriptor(e, k);
23
20
  Object.defineProperty(n, k, d.get ? d : {
24
21
  enumerable: true,
25
- get: function () {
26
- return e[k];
27
- }
22
+ get: function () { return e[k]; }
28
23
  });
29
24
  }
30
25
  });
31
26
  }
32
- n['default'] = e;
27
+ n.default = e;
33
28
  return Object.freeze(n);
34
29
  }
35
30
 
36
- var yargs__default = /*#__PURE__*/_interopDefaultLegacy(yargs);
37
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
38
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
39
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
40
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
41
- var SwaggerParser__default = /*#__PURE__*/_interopDefaultLegacy(SwaggerParser);
42
- var ___default = /*#__PURE__*/_interopDefaultLegacy(_);
43
- var https__namespace = /*#__PURE__*/_interopNamespace(https);
31
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
32
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
33
+ var https__namespace = /*#__PURE__*/_interopNamespaceDefault(https);
44
34
 
45
35
  const SwaggersConfig = zod.z.array(zod.z.array(zod.z.string()));
46
36
  class CliParser {
@@ -66,7 +56,7 @@ class CliParser {
66
56
  const configPath = CliParser.getConfigPath();
67
57
  if (!configPath)
68
58
  throw new Error("Missing config file");
69
- const config = JSON.parse(fs__default['default'].readFileSync(configPath, "utf8"));
59
+ const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
70
60
  if (!SwaggersConfig.safeParse(config).success) {
71
61
  throw new Error("Wrong config file format");
72
62
  }
@@ -131,44 +121,30 @@ ${body}
131
121
  `.replace(/, \)/g, ")").trim();
132
122
 
133
123
  class ParserUtils {
134
- static parseQueryParamAttributeDefault = (name, definition) => {
135
- const attrName = name.slice(name.lastIndexOf(".") + 1);
124
+ static parseQueryParamAttributeDefault = (definition) => {
125
+ const attrName = definition.name.slice(definition.name.lastIndexOf(".") + 1);
136
126
  const defaultValue = definition.type === "string" ? `'${definition.default}'` : definition.default;
137
127
  return `${attrName}: ${defaultValue}`;
138
128
  };
139
- static parseType = (type) => {
140
- if (type === "integer")
129
+ static parseType = (pathParam) => {
130
+ if (pathParam.type === "int" || pathParam.type === "integer")
141
131
  return "number";
142
- if (type === "array")
143
- return "any[]";
144
- return type;
132
+ if (pathParam.type === "array")
133
+ return `${pathParam.items.type ?? "any"}[]`;
134
+ return pathParam.type;
145
135
  };
146
136
  static parseQueryParamsType = (queryParams) => {
147
- return queryParams.map((p) => ParserUtils.parseAttributeType(p.name, p)).join(",");
137
+ return queryParams.map((queryParam) => ParserUtils.parseAttributeType(queryParam)).join(",");
148
138
  };
149
139
  static isAnyQueryParamRequired = (queryParams) => {
150
- queryParams.forEach((p) => {
151
- if (p.required) {
152
- return true;
153
- }
154
- });
155
- return false;
140
+ return queryParams.some((queryParam) => queryParam.required);
156
141
  };
157
142
  static parseQueryParamsDefault = (queryParams) => {
158
- const result = queryParams.filter((p) => !!p.default).map((p) => ParserUtils.parseQueryParamAttributeDefault(p.name, p)).join(",");
143
+ const result = queryParams.filter((queryParam) => !!queryParam.default && !queryParam.required).map(ParserUtils.parseQueryParamAttributeDefault).join(",");
159
144
  return result ? `${result},` : "";
160
145
  };
161
146
  static parseBodyParamsImports = (bodyParams) => {
162
- const ret = bodyParams.map((p) => {
163
- if (p?.schema?.$ref)
164
- return ParserUtils.parseRefImport(p.schema.$ref, p);
165
- if (p?.schema?.items?.$ref)
166
- return ParserUtils.parseRefImport(p.schema.items.$ref, p);
167
- if (p?.$ref)
168
- return ParserUtils.parseRefImport(p.$ref, p);
169
- return null;
170
- }).filter((p) => !!p);
171
- return ret;
147
+ return bodyParams.map(ParserUtils.parseRefImport).filter(Boolean);
172
148
  };
173
149
  static parseImportDir = ($ref) => {
174
150
  let ref = $ref.replace(".", "/");
@@ -181,7 +157,11 @@ class ParserUtils {
181
157
  return ref.slice(0, ref.lastIndexOf("/")).replace("#", ".");
182
158
  }
183
159
  };
184
- static parseRefImport = ($ref, p) => {
160
+ static parseRefImport = (bodyParam) => {
161
+ const $ref = bodyParam?.schema?.$ref || bodyParam?.schema?.items?.$ref;
162
+ if (!$ref) {
163
+ return null;
164
+ }
185
165
  const type = ParserUtils.parseRefType($ref);
186
166
  return `import { ${type} } from './definitions/${type}'`;
187
167
  };
@@ -191,60 +171,72 @@ class ParserUtils {
191
171
  ref = ref.slice(0, -1);
192
172
  }
193
173
  const val = ref.slice(ref.lastIndexOf("/") + 1);
194
- return ___default['default'].upperFirst(___default['default'].camelCase(val));
174
+ return _.upperFirst(_.camelCase(val)).replace(/( \w)/g, (group) => group.replace(" ", "").toUpperCase());
195
175
  };
196
- static parseAttributeType = (name, definition) => {
176
+ static parseAttributeType = (definition) => {
197
177
  const required = definition.required ? "" : "?";
198
- const attrName = name.slice(name.lastIndexOf(".") + 1);
199
- if (definition.enums) {
200
- const enums = definition.enums.map((enm) => definition.type === "string" ? `'${enm}'` : enm).join(" | ");
178
+ const attrName = definition.name.slice(definition.name.lastIndexOf(".") + 1);
179
+ if (definition.enum) {
180
+ const enums = definition.enum.map((enm) => definition.type === "string" ? `'${enm}'` : enm).join(" | ");
201
181
  return `${attrName}${required}: ${enums}`;
202
182
  }
203
- if (definition.type && definition.type === "integer") {
183
+ if (definition.type && ParserUtils.parseType(definition) === "number") {
184
+ return `${attrName}${required}: number`;
185
+ }
186
+ if (definition?.schema?.type && ParserUtils.parseType(definition.schema) === "number") {
204
187
  return `${attrName}${required}: number`;
205
188
  }
206
189
  if (definition.type && definition.type === "array") {
207
190
  return `${attrName}${required}: ${definition.items.type ?? "any"}[]`;
208
191
  }
192
+ if (definition?.schema?.type && definition.schema.type === "array") {
193
+ return `${attrName}${required}: ${definition.schema.items.type ?? "any"}[]`;
194
+ }
209
195
  if (definition.type && definition.type) {
210
196
  return `${attrName}${required}: ${definition.type} | null`;
211
197
  }
198
+ if (definition?.schema?.type && definition.schema.type) {
199
+ return `${attrName}${required}: ${definition.schema.type} | null`;
200
+ }
212
201
  return `${attrName}${required}: any`;
213
202
  };
214
203
  static parseBodyParamsType = (bodyParams) => {
215
- const [p] = bodyParams;
216
- if (!p)
204
+ const [bodyParam] = bodyParams;
205
+ if (!bodyParam)
217
206
  return null;
218
- if (bodyParams.length > 0 && p?.name !== "body" && !p?.schema) {
219
- let retBodyParams = `{${bodyParams.map((p2) => ParserUtils.parseAttributeType(p2.name, p2)).join(",")}}`;
207
+ if (bodyParams.length > 0 && bodyParam?.name !== "body" && !bodyParam?.schema) {
208
+ let retBodyParams = `{${bodyParams.map((bodyParam2) => ParserUtils.parseAttributeType(bodyParam2)).join(",")}}`;
220
209
  retBodyParams = retBodyParams.replace("file?: file", "file?: File");
221
210
  return retBodyParams;
222
211
  }
223
- if (p?.schema?.type === "array" && !p?.schema?.items?.$ref) {
224
- return `${p.schema.items.type ?? "any"}[]`;
212
+ if (bodyParam?.schema?.type === "array" && !bodyParam?.schema?.items?.$ref) {
213
+ return `${bodyParam.schema.items.type ?? "any"}[]`;
225
214
  }
226
- if (p?.schema?.type === "array" && p?.schema?.items?.$ref) {
227
- return `${ParserUtils.parseRefType(p.schema.items.$ref)}[]`;
215
+ if (bodyParam?.schema?.type === "array" && bodyParam?.schema?.items?.$ref) {
216
+ return `${ParserUtils.parseRefType(bodyParam.schema.items.$ref)}[]`;
228
217
  }
229
- if (p?.schema.$ref) {
230
- return ParserUtils.parseRefType(p.schema.$ref);
218
+ if (bodyParam?.schema.$ref) {
219
+ return ParserUtils.parseRefType(bodyParam.schema.$ref);
231
220
  }
232
- if (p?.schema?.additionalProperties?.type === "object") {
221
+ if (bodyParam?.schema?.additionalProperties?.type === "object") {
233
222
  return "any";
234
223
  }
235
224
  return null;
236
225
  };
237
- static get2xxResponse(methodEntity, path2) {
226
+ static get2xxResponse(methodEntity) {
238
227
  const keys = Object.keys(methodEntity);
239
228
  let responseClass = null;
240
229
  keys.forEach((key) => {
241
230
  if (String(key).startsWith("2")) {
242
231
  const sch = methodEntity[key].schema;
232
+ const schV3 = methodEntity[key].content && methodEntity[key].content["application/json"].schema;
243
233
  if (sch?.$ref) {
244
234
  responseClass = ParserUtils.parseRefType(sch.$ref);
245
235
  } else if (sch?.type === "array" && sch.items?.$ref) {
246
236
  responseClass = ParserUtils.parseRefType(sch.items.$ref);
247
237
  responseClass = `${responseClass}Array`;
238
+ } else if (schV3?.$ref) {
239
+ responseClass = ParserUtils.parseRefType(schV3.$ref);
248
240
  } else ;
249
241
  }
250
242
  });
@@ -259,31 +251,30 @@ class ParserUtils {
259
251
  }
260
252
  return contentTypes.includes("application/x-www-form-urlencoded");
261
253
  }
262
- static getPathParams(parametersArray) {
263
- if (!parametersArray) {
254
+ static filterPathParams(parameters) {
255
+ if (!parameters) {
264
256
  return [];
265
257
  }
266
- const res = [];
267
- for (const p of parametersArray) {
268
- if (p.in === "path") {
269
- res.push(p);
270
- }
271
- }
272
- return res;
258
+ return parameters.filter((parameter) => parameter.in === "path");
273
259
  }
274
- static generateClassMethod(path2, parametersArray, httpMethod, className) {
260
+ static generateClassMethod({
261
+ path: path2,
262
+ endpoint,
263
+ httpMethod,
264
+ className
265
+ }) {
275
266
  let replacedIdsPath = path2;
276
- if (parametersArray) {
277
- for (const p of parametersArray) {
278
- if (p.in === "path") {
279
- replacedIdsPath = replacedIdsPath.replace("{" + p.name + "}", "By" + ParserUtils.toTitleCaseWord(p.name));
267
+ if (endpoint.parameters) {
268
+ for (const parameter of endpoint.parameters) {
269
+ if (parameter.in === "path") {
270
+ replacedIdsPath = replacedIdsPath.replace("{" + parameter.name + "}", "By" + ParserUtils.toTitleCaseWord(parameter.name));
280
271
  replacedIdsPath = replacedIdsPath.replace("/iam", "");
281
272
  replacedIdsPath = replacedIdsPath.replace("/odin-config", "");
282
273
  }
283
274
  }
284
275
  }
285
276
  let classMethod = httpMethod + "/" + replacedIdsPath;
286
- classMethod = ___default['default'].camelCase(classMethod);
277
+ classMethod = _.camelCase(classMethod);
287
278
  classMethod = classMethod.replace("PublicNamespacesByNamespace", "");
288
279
  classMethod = classMethod.replace("AdminNamespacesByNamespace", "Admin");
289
280
  const searchWord = "NamespacesByNamespace";
@@ -294,45 +285,38 @@ class ParserUtils {
294
285
  }
295
286
  return classMethod;
296
287
  }
297
- static getBodyParams(parametersArray) {
298
- if (!parametersArray)
299
- return [];
300
- if (!___default['default'].isArray(parametersArray) && parametersArray)
301
- return [parametersArray].filter((p) => p.in === "body" || p.in === "formData");
302
- return parametersArray.filter((p) => p.in === "body" || p.in === "formData");
288
+ static filterBodyParams(parameters) {
289
+ if (Array.isArray(parameters) && parameters.length > 0) {
290
+ return parameters.filter((parameter) => parameter.in === "body" || parameter.in === "formData");
291
+ }
292
+ return [];
303
293
  }
304
- static getQueryParameters(parametersArray) {
305
- if (!parametersArray) {
294
+ static filterQueryParameters(parameters) {
295
+ if (!parameters) {
306
296
  return [];
307
297
  }
308
- const res = [];
309
- for (const p of parametersArray) {
310
- if (p.in === "query") {
311
- res.push(p);
312
- }
313
- }
314
- return res;
298
+ return parameters.filter((parameter) => parameter.in === "query");
315
299
  }
316
300
  static mkdirIfNotExist(dirToCreate) {
317
- if (!fs__default['default'].existsSync(dirToCreate)) {
318
- fs__default['default'].mkdirSync(dirToCreate, { recursive: true });
301
+ if (!fs.existsSync(dirToCreate)) {
302
+ fs.mkdirSync(dirToCreate, { recursive: true });
319
303
  }
320
304
  }
321
305
  static writeClassFile(distDir, apiName, apiBuffer, imports) {
322
306
  const fileContent = templateClass(apiName, apiBuffer, imports);
323
- fs__default['default'].writeFileSync(`${distDir}/${apiName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
307
+ fs.writeFileSync(`${distDir}/${apiName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
324
308
  }
325
309
  static writeJsdocFile(distDir, nameArray, apiBuffer) {
326
310
  const jsdocFile = templateJsdocFile(nameArray[0], apiBuffer);
327
- fs__default['default'].writeFileSync(`${distDir}/docs/${nameArray[0]}.md`, jsdocFile);
311
+ fs.writeFileSync(`${distDir}/docs/${nameArray[0]}.md`, jsdocFile);
328
312
  }
329
313
  static writeDefinitionFile(distDir, name, buffer) {
330
314
  ParserUtils.mkdirIfNotExist(distDir);
331
- fs__default['default'].writeFileSync(path__default['default'].join(distDir, `${name}.ts`), ParserUtils.prependCopyrightHeader(buffer));
315
+ fs.writeFileSync(path.join(distDir, `${name}.ts`), ParserUtils.prependCopyrightHeader(buffer));
332
316
  }
333
317
  static writeAllImportsFile(distDir, buffer, isAdminWebSdk) {
334
318
  ParserUtils.mkdirIfNotExist(distDir);
335
- fs__default['default'].writeFileSync(path__default['default'].join(distDir, `all-${isAdminWebSdk ? "admin" : "public"}-imports.ts`), ParserUtils.prependCopyrightHeader(buffer));
319
+ fs.writeFileSync(path.join(distDir, `all-${isAdminWebSdk ? "admin" : "public"}-imports.ts`), ParserUtils.prependCopyrightHeader(buffer));
336
320
  }
337
321
  static toCamelCase(str) {
338
322
  return str.split("/").map(function(word, index) {
@@ -358,24 +342,17 @@ class ParserUtils {
358
342
  });
359
343
  }
360
344
  static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
361
- if (!fs__default['default'].existsSync(swaggerPatchedDir)) {
362
- fs__default['default'].mkdirSync(swaggerPatchedDir, { recursive: true });
345
+ if (!fs.existsSync(swaggerPatchedDir)) {
346
+ fs.mkdirSync(swaggerPatchedDir, { recursive: true });
363
347
  }
364
- if (!fs__default['default'].existsSync(possibleSwaggerPatchFilePath)) {
365
- fs__default['default'].copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
348
+ if (!fs.existsSync(possibleSwaggerPatchFilePath)) {
349
+ fs.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
366
350
  return;
367
351
  }
368
- const swaggerContent = JSON.parse(fs__default['default'].readFileSync(swaggerFilePath, "utf8"));
369
- const swaggerPatchFileContent = JSON.parse(fs__default['default'].readFileSync(possibleSwaggerPatchFilePath, "utf8"));
352
+ const swaggerContent = JSON.parse(fs.readFileSync(swaggerFilePath, "utf8"));
353
+ const swaggerPatchFileContent = JSON.parse(fs.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
370
354
  const { newDocument } = fastJsonPatch.applyPatch(swaggerContent, swaggerPatchFileContent);
371
- fs__default['default'].writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
372
- }
373
- static mapKeys(map_) {
374
- const methods_ = [];
375
- for (const m in map_) {
376
- methods_.push(m);
377
- }
378
- return methods_;
355
+ fs.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
379
356
  }
380
357
  static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
381
358
  const replaced = srcFolder.replace(/\\/g, "/");
@@ -392,7 +369,96 @@ ${content}`;
392
369
  };
393
370
  }
394
371
 
395
- const templateJsdocMethod = (classMethod, httpMethod, path, pathParams, bodyParams, queryParams) => {
372
+ const Schema = zod.z.object({
373
+ $ref: zod.z.string().nullish(),
374
+ type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
375
+ items: zod.z.object({
376
+ $ref: zod.z.string().nullish(),
377
+ type: zod.z.string().nullish()
378
+ }).nullish(),
379
+ properties: zod.z.array(zod.z.string()).nullish(),
380
+ description: zod.z.string().nullish(),
381
+ additionalProperties: zod.z.object({
382
+ type: zod.z.string().nullish()
383
+ }).nullish()
384
+ });
385
+ const Definition = zod.z.object({
386
+ required: zod.z.array(zod.z.string()).nullish(),
387
+ properties: zod.z.record(zod.z.object({
388
+ type: zod.z.string()
389
+ })).nullish()
390
+ });
391
+ const Definitions = zod.z.record(Definition);
392
+ const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
393
+ const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
394
+ const EndpointParameters = zod.z.object({
395
+ type: EndpointParametersType.nullish(),
396
+ description: zod.z.string().nullish(),
397
+ name: zod.z.string(),
398
+ in: EndpointParametersIn,
399
+ required: zod.z.boolean().nullish(),
400
+ schema: Schema.nullish(),
401
+ default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()]).nullish(),
402
+ enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
403
+ items: zod.z.object({
404
+ type: zod.z.string()
405
+ }).nullish()
406
+ });
407
+ const Endpoint = zod.z.object({
408
+ description: zod.z.string().nullish(),
409
+ consumes: zod.z.array(zod.z.string()).nullish(),
410
+ produces: zod.z.array(zod.z.string()).nullish(),
411
+ tags: zod.z.array(zod.z.string()).nullish(),
412
+ summary: zod.z.string().nullish(),
413
+ operationId: zod.z.string(),
414
+ deprecated: zod.z.boolean().nullish(),
415
+ responses: zod.z.record(zod.z.object({
416
+ description: zod.z.string().nullish(),
417
+ schema: Schema.nullish(),
418
+ content: zod.z.object({
419
+ "application/json": zod.z.object({
420
+ schema: Schema.nullish()
421
+ })
422
+ }).nullish()
423
+ })),
424
+ parameters: zod.z.array(EndpointParameters).nullish()
425
+ });
426
+ const Operation = zod.z.object({
427
+ get: Endpoint.nullish(),
428
+ post: Endpoint.nullish(),
429
+ patch: Endpoint.nullish(),
430
+ delete: Endpoint.nullish(),
431
+ put: Endpoint.nullish()
432
+ });
433
+ const Paths = zod.z.record(Operation);
434
+ zod.z.object({
435
+ paths: Paths,
436
+ definitions: Definitions,
437
+ basePath: zod.z.string(),
438
+ info: zod.z.object({
439
+ description: zod.z.string(),
440
+ title: zod.z.string(),
441
+ contact: zod.z.object({
442
+ name: zod.z.string(),
443
+ url: zod.z.string(),
444
+ email: zod.z.string()
445
+ }),
446
+ version: zod.z.string()
447
+ }),
448
+ schemes: zod.z.array(zod.z.string()).nullish(),
449
+ components: zod.z.object({
450
+ schemas: Definitions
451
+ }).nullish()
452
+ });
453
+
454
+ const templateJsdocMethod = ({
455
+ classMethod,
456
+ httpMethod,
457
+ path,
458
+ pathParams,
459
+ bodyParams,
460
+ queryParams
461
+ }) => {
396
462
  let jsdoc = "";
397
463
  let methodSignature = "";
398
464
  let newPath = path;
@@ -429,21 +495,31 @@ const templateJsdocMethod = (classMethod, httpMethod, path, pathParams, bodyPara
429
495
  `;
430
496
  };
431
497
 
432
- const templateMethod = (classMethod, description, httpMethod, path, pathParams, bodyParams, queryParams, isFormUrlEncoded, responseClass) => {
498
+ const templateMethod = ({
499
+ classMethod,
500
+ description,
501
+ httpMethod,
502
+ path,
503
+ pathParams,
504
+ bodyParams,
505
+ queryParams,
506
+ isFormUrlEncoded,
507
+ responseClass
508
+ }) => {
433
509
  let methodSignature = "";
434
510
  let newPath = `'${path}'`;
435
511
  let dependencies = [];
436
- for (const p of pathParams) {
437
- const type = ParserUtils.parseType(p.type);
438
- if (p.name !== "namespace") {
439
- methodSignature += p.name + `:${type}, `;
512
+ for (const pathParam of pathParams) {
513
+ const type = ParserUtils.parseType(pathParam);
514
+ if (pathParam.name !== "namespace") {
515
+ methodSignature += pathParam.name + `:${type}, `;
440
516
  }
441
- const pName = p.name === "namespace" ? "this.namespace" : p.name;
442
- if (path.match(`{${p.name}}`)) {
517
+ const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
518
+ if (path.match(`{${pathParam.name}}`)) {
443
519
  if (type === "string") {
444
- newPath = `${newPath}.replace('{${p.name}}', ${pName})`;
520
+ newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
445
521
  } else {
446
- newPath = `${newPath}.replace('{${p.name}}', String(${pName}))`;
522
+ newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
447
523
  }
448
524
  }
449
525
  }
@@ -453,8 +529,8 @@ const templateMethod = (classMethod, description, httpMethod, path, pathParams,
453
529
  dependencies = ParserUtils.parseBodyParamsImports(bodyParams);
454
530
  methodSignature += dataType ? `data: ${dataType},` : "";
455
531
  }
456
- ParserUtils.isAnyQueryParamRequired(queryParams);
457
- const queryParamsType = queryParams.length ? `queryParams${"?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
532
+ const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
533
+ const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
458
534
  const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
459
535
  const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
460
536
  const isDelete = ["delete"].includes(httpMethod);
@@ -479,74 +555,30 @@ const templateMethod = (classMethod, description, httpMethod, path, pathParams,
479
555
  const parameters = (queryParamsType ? `${methodSignature} ${queryParamsType}` : methodSignature).replace(/,\s*$/, "");
480
556
  let methodImpl = "";
481
557
  const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
482
- const isCacheFetchUnknown = ["get"].includes(httpMethod) && resolvedResponseClass === "unknown";
483
558
  const cachedFetchMethod = classMethod.replace("get", "fetch");
484
559
  const deprecateTag = isCacheFetch ? `/**
485
560
  * @deprecated Use "${cachedFetchMethod}()" instead.
486
561
  */` : "";
487
- let isGuardInvoked = false;
488
- if (isCacheFetch) {
489
- methodImpl = `${descriptionText}
490
- ${cachedFetchMethod}<T = ${resolvedResponseClass}>(${parameters}): Promise<IResponseWithSync<T>> {
562
+ const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
563
+ const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
564
+ const methodGenerics = resolvedResponseClass !== "unknown" ? `<T = ${resolvedResponseClass}>` : "";
565
+ const responseType = resolvedResponseClass !== "unknown" ? `T` : "unknown";
566
+ const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
567
+ methodImpl = `${descriptionText}
568
+ ${methodName}${methodGenerics}(${parameters}): Promise<${responseSyncType}<${responseType}>> {
491
569
  ${queryParamsDefault}
492
570
  const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
493
571
  const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
494
-
495
- const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated})
496
572
 
497
- if (!this.cache) {
498
- return SdkCache.withoutCache(res)
499
- }
500
- const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
501
- return SdkCache.withCache(cacheKey, res)
502
- }
503
- `;
504
- isGuardInvoked = true;
505
- }
506
- if (isCacheFetchUnknown) {
507
- methodImpl = `${descriptionText}
508
- ${cachedFetchMethod}(${parameters}): Promise<IResponseWithSync<unknown>> {
509
- ${queryParamsDefault}
510
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
511
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
512
-
513
- const res = () => Validate.responseType(() => resultPromise, z.unknown())
573
+ ${httpMethod === "get" ? `const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated})
514
574
 
515
575
  if (!this.cache) {
516
576
  return SdkCache.withoutCache(res)
517
577
  }
518
578
  const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
519
- return SdkCache.withCache(cacheKey, res)
579
+ return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? `return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated})` : ""}
520
580
  }
521
581
  `;
522
- isGuardInvoked = true;
523
- }
524
- const withTypeGuard = ["post", "put", "patch", "delete"].includes(httpMethod) && resolvedResponseClass !== "unknown";
525
- if (withTypeGuard) {
526
- methodImpl = `${descriptionText}
527
- ${classMethod}<T = ${resolvedResponseClass}>(${parameters}): Promise<IResponse<T>> {
528
- ${queryParamsDefault}
529
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
530
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
531
-
532
- return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated})
533
- }
534
- `;
535
- isGuardInvoked = true;
536
- }
537
- const withTypeGuardUnknown = ["post", "put", "patch", "delete"].includes(httpMethod) && resolvedResponseClass === "unknown";
538
- if (withTypeGuardUnknown) {
539
- methodImpl = `${descriptionText}
540
- ${classMethod}(${parameters}): Promise<IResponse<unknown>> {
541
- ${queryParamsDefault}
542
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
543
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
544
-
545
- return Validate.responseType(() => resultPromise, z.unknown())
546
- }
547
- `;
548
- isGuardInvoked = true;
549
- }
550
582
  if (!isGuardInvoked) {
551
583
  methodImpl = `${descriptionText}
552
584
  ${deprecateTag}
@@ -564,12 +596,12 @@ class TemplateZod {
564
596
  duplicates;
565
597
  duplicateFound = false;
566
598
  importClasses = /* @__PURE__ */ new Set();
567
- render = (name, definition, duplicates) => {
599
+ render = (fileName, definition, duplicates) => {
568
600
  this.duplicates = duplicates;
569
601
  const content = this.parseToZodSchema(definition, definition.required || []);
570
- const containsRecursiveType = this.importClasses.has(name);
602
+ const containsRecursiveType = this.importClasses.has(fileName);
571
603
  if (containsRecursiveType) {
572
- this.importClasses.delete(name);
604
+ this.importClasses.delete(fileName);
573
605
  }
574
606
  let imports = "";
575
607
  for (const cl of Array.from(this.importClasses).sort()) {
@@ -580,18 +612,18 @@ class TemplateZod {
580
612
  let exportedTypeString;
581
613
  if (containsRecursiveType) {
582
614
  exportedVariableString = `
583
- export const ${name}: z.ZodType<${name}> = z.lazy(() =>
615
+ export const ${fileName}: z.ZodType<${fileName}> = z.lazy(() =>
584
616
  ${content.schemaString}
585
617
  )
586
618
  `;
587
619
  exportedTypeString = `
588
- export type ${name} = {
620
+ export type ${fileName} = {
589
621
  ${content.typeString}
590
622
  }
591
623
  `;
592
624
  } else {
593
- exportedVariableString = `export const ${name} = ${content.schemaString}`;
594
- exportedTypeString = `export type ${name} = z.TypeOf<typeof ${name}>`;
625
+ exportedVariableString = `export const ${fileName} = ${content.schemaString}`;
626
+ exportedTypeString = `export type ${fileName} = z.TypeOf<typeof ${fileName}>`;
595
627
  }
596
628
  const template = `import { z } from 'zod'
597
629
  ${imports}
@@ -662,7 +694,8 @@ class TemplateZod {
662
694
  };
663
695
  }
664
696
  if (type === "array") {
665
- const ref2 = definition.items?.$ref;
697
+ const items = definition.items;
698
+ const ref2 = items?.$ref;
666
699
  let model2;
667
700
  if (ref2) {
668
701
  const refType = ParserUtils.parseRefType(ref2);
@@ -671,9 +704,13 @@ class TemplateZod {
671
704
  schemaString: refType,
672
705
  typeString: refType
673
706
  };
674
- } else {
675
- const items = definition.items;
707
+ } else if (items) {
676
708
  model2 = this.parseEnumItems(items);
709
+ } else {
710
+ return {
711
+ schemaString: `${schemaAttribute} z.array(z.unknown())${schemaRequired}`,
712
+ typeString: `${typeAttribute} z.unknown()[]${typeNullishability}`
713
+ };
677
714
  }
678
715
  return {
679
716
  schemaString: `${schemaAttribute} z.array(${model2.schemaString})${schemaRequired}`,
@@ -780,10 +817,10 @@ const extractEnumObject = (type, isRequired, enumArr) => {
780
817
  };
781
818
 
782
819
  class CodeGenerator {
783
- static getPatchedDir = () => path__default['default'].join(CliParser.getSwaggersOutputPath(), "patched");
820
+ static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
784
821
  static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
785
822
  static getGeneratedAdminFolder = () => `${CliParser.getOutputPath()}/generated-admin`;
786
- static iterateApi = (api) => {
823
+ static iterateApi = async (api) => {
787
824
  const apiBufferByTag = {};
788
825
  const jsDocApiBufferByTag = {};
789
826
  const dependenciesByTag = {};
@@ -796,15 +833,21 @@ class CodeGenerator {
796
833
  } else if (!CliParser.isAdmin() && isAdminEndpoint) {
797
834
  continue;
798
835
  }
799
- const entity = api.paths[path2];
800
- const methods = ParserUtils.mapKeys(entity);
801
- for (const httpMethod of methods) {
802
- const e = entity[httpMethod];
803
- const [tag] = e.tags;
804
- const description = e.description;
805
- const isDeprecated = e.deprecated;
806
- const responseClass = ParserUtils.get2xxResponse(e.responses, path2);
807
- const className = ___default['default'].upperFirst(___default['default'].camelCase(tag));
836
+ const operation = api.paths[path2];
837
+ const httpMethods = Object.keys(operation);
838
+ for (const httpMethod of httpMethods) {
839
+ const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
840
+ console.error(JSON.stringify({ path: path2, httpMethod }, null, 2));
841
+ throw error;
842
+ });
843
+ if (!endpoint.tags) {
844
+ continue;
845
+ }
846
+ const [tag] = endpoint.tags;
847
+ const description = endpoint.description;
848
+ const isDeprecated = endpoint.deprecated;
849
+ const responseClass = ParserUtils.get2xxResponse(endpoint.responses);
850
+ const className = _.upperFirst(_.camelCase(tag));
808
851
  classImports[className] = classImports[className] ? classImports[className] : {};
809
852
  if (!isDeprecated) {
810
853
  if (responseClass) {
@@ -814,15 +857,30 @@ class CodeGenerator {
814
857
  if (responseClass && responseClass.endsWith("Array")) {
815
858
  arrayDefinitions.push(responseClass);
816
859
  }
817
- const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, e.consumes);
818
- const queryParams = ParserUtils.getQueryParameters(e.parameters);
819
- const pathParams = ParserUtils.getPathParams(e.parameters);
820
- const bodyParams = ParserUtils.getBodyParams(e.parameters);
821
- const classMethod = ParserUtils.generateClassMethod(path2, e.parameters, httpMethod, className);
822
- const baseAndPath = `${api.basePath ?? ""}${path2}`;
823
- const [generatedMethodString, importStatements] = templateMethod(classMethod, description, httpMethod, baseAndPath, pathParams, bodyParams, queryParams, isFormUrlEncoded, responseClass);
860
+ const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
861
+ const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
862
+ const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
863
+ const bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
864
+ const classMethod = ParserUtils.generateClassMethod({
865
+ path: path2,
866
+ endpoint,
867
+ httpMethod,
868
+ className
869
+ });
870
+ const pathWithBase = `${api.basePath ?? ""}${path2}`;
871
+ const [generatedMethodString, importStatements] = templateMethod({
872
+ classMethod,
873
+ description,
874
+ httpMethod,
875
+ path: pathWithBase,
876
+ pathParams,
877
+ bodyParams,
878
+ queryParams,
879
+ isFormUrlEncoded,
880
+ responseClass
881
+ });
824
882
  apiBufferByTag[tag] = (apiBufferByTag[tag] || "") + generatedMethodString;
825
- jsDocApiBufferByTag[tag] = (jsDocApiBufferByTag[tag] || "") + templateJsdocMethod(classMethod, httpMethod, path2, pathParams, bodyParams, queryParams);
883
+ jsDocApiBufferByTag[tag] = (jsDocApiBufferByTag[tag] || "") + templateJsdocMethod({ classMethod, httpMethod, path: path2, pathParams, bodyParams, queryParams });
826
884
  dependenciesByTag[tag] = dependenciesByTag[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...dependenciesByTag[tag]])] : [...new Set(importStatements)];
827
885
  }
828
886
  }
@@ -833,11 +891,11 @@ class CodeGenerator {
833
891
  static main = async (nameArray) => {
834
892
  const serviceName = nameArray[0];
835
893
  const swaggerFile = nameArray[2];
836
- const parser = new SwaggerParser__default['default']();
894
+ const parser = new SwaggerParser();
837
895
  const generatedFolder = CliParser.isAdmin() ? CodeGenerator.getGeneratedAdminFolder() : CodeGenerator.getGeneratedPublicFolder();
838
896
  const DIST_DIR = `${generatedFolder}/${serviceName}`;
839
- const DIST_DOCS_DIR = path__default['default'].join(DIST_DIR, "docs");
840
- const DIST_DEFINITION_DIR = path__default['default'].join(DIST_DIR, "definitions");
897
+ const DIST_DOCS_DIR = path.join(DIST_DIR, "docs");
898
+ const DIST_DEFINITION_DIR = path.join(DIST_DIR, "definitions");
841
899
  const swaggerFilePath = `${CliParser.getSwaggersOutputPath()}/${swaggerFile}`;
842
900
  const swaggerPatchedFilePath = `${CodeGenerator.getPatchedDir()}/${swaggerFile}`;
843
901
  const swaggerPatchFilePath = `${swaggerFilePath}patch`;
@@ -848,42 +906,43 @@ class CodeGenerator {
848
906
  ParserUtils.mkdirIfNotExist(DIST_DIR);
849
907
  ParserUtils.mkdirIfNotExist(DIST_DOCS_DIR);
850
908
  ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
851
- const { apiBufferByTag, dependenciesByTag, classImports, arrayDefinitions } = CodeGenerator.iterateApi(api);
909
+ const { apiBufferByTag, dependenciesByTag, classImports, arrayDefinitions } = await CodeGenerator.iterateApi(api);
852
910
  const targetSrcFolder = `${CliParser.getOutputPath()}/`;
853
911
  for (const tag in apiBufferByTag) {
854
- const className = ___default['default'].upperFirst(___default['default'].camelCase(tag));
912
+ const className = _.upperFirst(_.camelCase(tag));
855
913
  const apiBuffer = apiBufferByTag[tag];
856
914
  const imports = [.../* @__PURE__ */ new Set([...dependenciesByTag[tag], ...Object.values(classImports[className])])];
857
915
  const classGenName = CliParser.isAdmin() ? className + "Admin$" : className + "$";
858
916
  ParserUtils.writeClassFile(DIST_DIR, classGenName, apiBuffer, imports);
859
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path__default['default'].join(DIST_DIR, `${classGenName}`), targetSrcFolder));
917
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR, `${classGenName}`), targetSrcFolder));
860
918
  }
861
919
  const duplicates = /* @__PURE__ */ new Map();
862
- for (const ref in api.definitions) {
863
- const definition = api.definitions[ref];
920
+ const definitions = api?.components?.schemas || api.definitions;
921
+ for (const ref in definitions) {
922
+ const definition = definitions[ref];
864
923
  let fileName = ParserUtils.parseRefType(ref);
865
- const fileExist = fs__default['default'].existsSync(path__default['default'].join(DIST_DEFINITION_DIR, `${fileName}.ts`));
924
+ const fileExist = fs.existsSync(path.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
866
925
  if (fileExist) {
867
926
  fileName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
868
927
  duplicates.set(ref, fileName);
869
928
  }
870
929
  const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
871
930
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
872
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path__default['default'].join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
931
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
873
932
  }
874
- for (const ref in api.definitions) {
875
- const definition = api.definitions[ref];
933
+ for (const ref in definitions) {
934
+ const definition = definitions[ref];
876
935
  const fileName = ParserUtils.parseRefType(ref);
877
936
  const { buffer, duplicateFound } = new TemplateZod().render(fileName, definition, duplicates);
878
937
  if (duplicateFound) {
879
938
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
880
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path__default['default'].join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
939
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
881
940
  }
882
941
  }
883
942
  for (const arrayClass of arrayDefinitions) {
884
943
  const buffer = new TemplateZodArray().render(arrayClass);
885
944
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
886
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path__default['default'].join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
945
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
887
946
  }
888
947
  console.log("\n----------\nCOMPLETED.\n----------\n\n");
889
948
  return indexImportsSet;
@@ -926,7 +985,7 @@ class SwaggerDownloader {
926
985
  };
927
986
  }
928
987
 
929
- yargs__default['default'].command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
988
+ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
930
989
  CliParser.createInstance(yargs2);
931
990
  SwaggerDownloader.main();
932
991
  }).command("generate-code", "Generate code based on downloaded swagger files", async (yargs2) => {
@@ -942,7 +1001,7 @@ yargs__default['default'].command("download-swaggers", "Download swaggers JSON f
942
1001
  const filenamesSet = /* @__PURE__ */ new Set();
943
1002
  for (const set of arrayOfSets) {
944
1003
  set.forEach((value) => {
945
- const fileName = path__default['default'].basename(value);
1004
+ const fileName = path.basename(value);
946
1005
  if (!filenamesSet.has(fileName)) {
947
1006
  indexImportsSet.add(value);
948
1007
  filenamesSet.add(fileName);