@moccona/apicodegen 0.0.2 → 0.0.3

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.
@@ -23,7 +23,7 @@ type apiCodeGenPluginOptions = ProviderInitOptions & {
23
23
  name: string;
24
24
  proxy?: ServerOptions["proxy"];
25
25
  };
26
- declare const tsc: () => Promise<void>;
26
+ declare const tsc: (path: string) => Promise<void>;
27
27
  declare function apiCodeGenPlugin(options: apiCodeGenPluginOptions[]): PluginOption;
28
28
 
29
29
  export { apiCodeGenPlugin, type apiCodeGenPluginOptions, tsc };
package/npm/vite/index.js CHANGED
@@ -189,19 +189,24 @@ var Base = class _Base {
189
189
  */
190
190
  static async fetchDoc(url, requestInit = {}) {
191
191
  const agent = new Agent({
192
- connect: {
193
- rejectUnauthorized: false
194
- }
192
+ connect: { rejectUnauthorized: false }
193
+ });
194
+ const { body, statusCode } = await request(url, {
195
+ method: "GET",
196
+ dispatcher: agent,
197
+ ...requestInit
195
198
  });
199
+ if (statusCode >= 400) {
200
+ throw new Error(
201
+ `Failed to fetch OpenAPI documentation from ${url}: HTTP ${statusCode}`
202
+ );
203
+ }
196
204
  try {
197
- const { body } = await request(url, {
198
- method: "GET",
199
- dispatcher: agent,
200
- ...requestInit
201
- });
202
205
  return body.json();
203
206
  } catch (error) {
204
- throw error;
207
+ throw new Error(
208
+ `Failed to parse JSON response from ${url}: ${error instanceof Error ? error.message : String(error)}`
209
+ );
205
210
  }
206
211
  }
207
212
  /**
@@ -210,12 +215,11 @@ var Base = class _Base {
210
215
  * @returns - The matched MediaTypes or null.
211
216
  */
212
217
  static getMediaType(mediaType) {
213
- for (const type in Object.values(MediaTypes)) {
214
- if (new RegExp(type).test(mediaType)) {
215
- return type;
216
- }
217
- }
218
- return;
218
+ const mediaTypeValues = Object.values(MediaTypes);
219
+ const found = mediaTypeValues.find(
220
+ (type) => mediaType.includes(type)
221
+ );
222
+ return found;
219
223
  }
220
224
  /**
221
225
  * Checks if a schema is a valid enum type that isn't boolean.
@@ -250,17 +254,21 @@ var Base = class _Base {
250
254
  * @returns - Array of unique enum schemas.
251
255
  */
252
256
  static uniqueEnums(enums) {
253
- const uniqueEnums_ = [];
254
- for (const enumObject of enums) {
255
- if (uniqueEnums_.length === 0) {
256
- uniqueEnums_.push(enumObject);
257
- } else {
258
- if (!uniqueEnums_.some((a) => this.isSameEnum(a, enumObject))) {
259
- uniqueEnums_.push(enumObject);
257
+ const enumMap = /* @__PURE__ */ new Map();
258
+ for (const e of enums) {
259
+ const existing = enumMap.get(e.name);
260
+ if (existing) {
261
+ for (const value of e.enum) {
262
+ existing.add(value);
260
263
  }
264
+ } else {
265
+ enumMap.set(e.name, new Set(e.enum));
261
266
  }
262
267
  }
263
- return uniqueEnums_;
268
+ return Array.from(enumMap.entries()).map(([name, values]) => ({
269
+ name,
270
+ enum: Array.from(values)
271
+ }));
264
272
  }
265
273
  /**
266
274
  * Finds the first occurrence of a matching enum schema in an array.
@@ -277,7 +285,7 @@ var Base = class _Base {
277
285
  * @returns - True if the object is a reference.
278
286
  */
279
287
  static isRef(schema) {
280
- return "$ref" in schema && typeof schema.$ref === "string";
288
+ return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
281
289
  }
282
290
  };
283
291
 
@@ -547,24 +555,24 @@ var Generator = class _Generator {
547
555
  }
548
556
  return t.createToken(SyntaxKind.UnknownKeyword);
549
557
  }
550
- static toDeclarationNode(parameters) {
558
+ static toDeclarationNodes(parameters) {
551
559
  const objectElements = [];
552
560
  const typeObjectElements = [];
561
+ const refParameters = [];
553
562
  for (const parameter of parameters) {
554
563
  if (parameter.ref) {
555
- t.createParameterDeclaration(
556
- void 0,
557
- void 0,
558
- t.createIdentifier(
559
- Base.camelCase(Base.normalize(Base.ref2name(parameter.ref)))
560
- ),
561
- void 0,
562
- t.createTypeReferenceNode(
563
- t.createIdentifier(
564
- Base.upperCamelCase(Base.normalize(Base.ref2name(parameter.ref)))
565
- )
566
- ),
567
- void 0
564
+ const refName = Base.ref2name(parameter.ref);
565
+ refParameters.push(
566
+ t.createParameterDeclaration(
567
+ void 0,
568
+ void 0,
569
+ t.createIdentifier(Base.camelCase(Base.normalize(refName))),
570
+ void 0,
571
+ t.createTypeReferenceNode(
572
+ t.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))
573
+ ),
574
+ void 0
575
+ )
568
576
  );
569
577
  } else {
570
578
  const { name, schema, required } = parameter;
@@ -585,14 +593,18 @@ var Generator = class _Generator {
585
593
  );
586
594
  }
587
595
  }
588
- return t.createParameterDeclaration(
589
- void 0,
590
- void 0,
591
- t.createObjectBindingPattern(objectElements),
592
- void 0,
593
- t.createTypeLiteralNode(typeObjectElements),
594
- void 0
595
- );
596
+ if (objectElements.length > 0) {
597
+ const objectParam = t.createParameterDeclaration(
598
+ void 0,
599
+ void 0,
600
+ t.createObjectBindingPattern(objectElements),
601
+ void 0,
602
+ t.createTypeLiteralNode(typeObjectElements),
603
+ void 0
604
+ );
605
+ return [objectParam, ...refParameters];
606
+ }
607
+ return refParameters;
596
608
  }
597
609
  static toFormDataStatement(parameters, requestBody) {
598
610
  const statements = [];
@@ -846,8 +858,8 @@ var Generator = class _Generator {
846
858
  Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.capitalize(req.type.split("/")[1]) : ""),
847
859
  void 0,
848
860
  [
849
- parameters.length > 0 ? _Generator.toDeclarationNode(parameters) : void 0,
850
- req?.schema ? _Generator.toRequestBodyTypeNode(req.schema) : void 0
861
+ ...parameters.length > 0 ? _Generator.toDeclarationNodes(parameters) : [],
862
+ ...req?.schema ? [_Generator.toRequestBodyTypeNode(req.schema)] : []
851
863
  ].filter(Boolean),
852
864
  void 0,
853
865
  this.bodyBlock(
@@ -967,7 +979,6 @@ var AxiosAdapter = class extends Adapter {
967
979
  )
968
980
  ) : []
969
981
  ).concat(
970
- // Add body if needed
971
982
  shouldUseFormData || inBody.length > 0 || requestBody?.schema ? t2.createPropertyAssignment(
972
983
  t2.createIdentifier(adapter.bodyFieldName),
973
984
  shouldUseFormData ? t2.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? t2.createIdentifier("req") : t2.createIdentifier("req")
@@ -1053,7 +1064,6 @@ var FetchAdapter = class extends Adapter {
1053
1064
  )
1054
1065
  ) : []
1055
1066
  ).concat(
1056
- // Add body if needed
1057
1067
  shouldUseFormData || inBody.length > 0 || requestBody?.schema ? t3.createPropertyAssignment(
1058
1068
  t3.createIdentifier(adapter.bodyFieldName),
1059
1069
  shouldUseFormData ? t3.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? t3.createCallExpression(
@@ -1507,7 +1517,11 @@ var V3 = class {
1507
1517
  type: upLevelSchemaKey + refName
1508
1518
  };
1509
1519
  }
1510
- schema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1520
+ const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1521
+ if (!resolvedSchema) {
1522
+ return { type: "unknown" };
1523
+ }
1524
+ schema = resolvedSchema;
1511
1525
  }
1512
1526
  return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1513
1527
  }
@@ -1516,7 +1530,14 @@ var V3 = class {
1516
1530
  */
1517
1531
  getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1518
1532
  if (Base.isRef(schema)) {
1519
- schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1533
+ const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1534
+ if (!resolvedSchema) {
1535
+ return {
1536
+ name: "unknown",
1537
+ in: "query"
1538
+ };
1539
+ }
1540
+ schema = resolvedSchema;
1520
1541
  }
1521
1542
  const {
1522
1543
  name,
@@ -1565,7 +1586,11 @@ var V3 = class {
1565
1586
  */
1566
1587
  getResponseByRef(schema) {
1567
1588
  if (Base.isRef(schema)) {
1568
- schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1589
+ const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1590
+ if (!resolvedSchema) {
1591
+ return [];
1592
+ }
1593
+ schema = resolvedSchema;
1569
1594
  }
1570
1595
  const { content = {} } = schema;
1571
1596
  return Object.keys(content).map((c) => ({
@@ -1578,7 +1603,11 @@ var V3 = class {
1578
1603
  */
1579
1604
  getRequestBodyByRef(schema, enums = []) {
1580
1605
  if (Base.isRef(schema)) {
1581
- schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1606
+ const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1607
+ if (!resolvedSchema) {
1608
+ return [];
1609
+ }
1610
+ schema = resolvedSchema;
1582
1611
  }
1583
1612
  const { content = {} } = schema;
1584
1613
  return Object.keys(content).map((c) => ({
@@ -2195,8 +2224,8 @@ import { execaCommand } from "execa";
2195
2224
  import fs from "fs-extra";
2196
2225
  var PLUGIN_NAME = "apiCodeGen";
2197
2226
  var logger2 = createScopedLogger2("api-codegen-vite-plugin");
2198
- var tsc = async () => {
2199
- await execaCommand("npx tsc -b");
2227
+ var tsc = async (path) => {
2228
+ await execaCommand(`npx tsc ${path} --noEmit`);
2200
2229
  };
2201
2230
  function apiCodeGenPlugin(options) {
2202
2231
  let firstRun = true;
@@ -2214,9 +2243,13 @@ function apiCodeGenPlugin(options) {
2214
2243
  const code = await codeGen(codeGenInitOptions);
2215
2244
  await fs.createFile(codeGenInitOptions.output);
2216
2245
  await fs.writeFile(codeGenInitOptions.output, code);
2246
+ try {
2247
+ await tsc(codeGenInitOptions.output);
2248
+ } catch (error) {
2249
+ logger2.error(error);
2250
+ }
2217
2251
  } catch (error) {
2218
- logger2.error(`Failed to generate api ${name}`);
2219
- console.error(error);
2252
+ logger2.error(`Failed to generate api ${name}: ${error}`);
2220
2253
  }
2221
2254
  return {
2222
2255
  ...proxies_,
@@ -2226,11 +2259,6 @@ function apiCodeGenPlugin(options) {
2226
2259
  Promise.resolve({})
2227
2260
  );
2228
2261
  logger2.info("-------> api codegen finished <--------");
2229
- try {
2230
- await tsc();
2231
- } catch (error) {
2232
- logger2.error(error);
2233
- }
2234
2262
  return {
2235
2263
  ...config,
2236
2264
  server: {