@moccona/apicodegen 0.0.11 → 0.1.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/vite-plugin/index.ts"],"mappings":";;;KAiBY,uBAAA;2DAEX,IAAA,UAFkC;EAIlC,IAAA,WAJkC;EAMlC,MAAA,WAFA;EAIA,OAAA;EAEA,OAAA,WAEA;EAAA,kBAAA,WAIA;EAFA,OAAA,YAES;EAAT,SAAA;AAAA;;;;;;;AAgJc;;;;;;;;;;;;;;;;iBAFC,gBAAA,CACf,OAAA,EAAS,uBAAA,KACP,YAAY"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/vite-plugin/index.ts"],"mappings":";;;KAiBY,uBAAA;2DAEX,IAAA,UAFkC;EAIlC,IAAA,WAJkC;EAMlC,MAAA,WAFA;EAIA,OAAA;EAEA,OAAA,WAEA;EAAA,kBAAA,WAIA;EAFA,OAAA,YAES;EAAT,SAAA;AAAA;;;;;;;AA8Mc;;;;;;;;;;;;;;;;iBAFC,gBAAA,CACf,OAAA,EAAS,uBAAA,KACP,YAAY"}
@@ -526,6 +526,7 @@ const typescriptKeywords = new Set([
526
526
  //#region src/core/interface.ts
527
527
  let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
528
528
  MediaTypes["JSON"] = "application/json";
529
+ MediaTypes["EVENT_STREAM"] = "text/event-stream";
529
530
  MediaTypes["TEXT"] = "text";
530
531
  MediaTypes["IMAGE"] = "image";
531
532
  MediaTypes["AUDIO"] = "audio";
@@ -1006,13 +1007,14 @@ var Generator = class Generator {
1006
1007
  static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
1007
1008
  const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(requestBody.type);
1008
1009
  const shouldParseResponseToJSON = "application/json" === response?.type;
1010
+ const isEventStream = response?.type === "text/event-stream";
1009
1011
  const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
1010
1012
  const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
1011
1013
  const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
1012
1014
  const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
1013
1015
  const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
1014
1016
  const shouldPutParametersOrBodyInFormData = !!isFormDataRequest && (isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0);
1015
- return factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON)]);
1017
+ return factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON, isEventStream)]);
1016
1018
  }
1017
1019
  static schemaToStatemets(parsedDoc, adaptor, options) {
1018
1020
  const statements = [];
@@ -1089,13 +1091,19 @@ var AxiosAdapter = class extends Adapter {
1089
1091
  */
1090
1092
  name = "axios";
1091
1093
  /**
1092
- * Method that should generate and return the client-specific configuration statements.
1093
- *
1094
- * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
1095
- *
1096
- * @throws {Error} Indicates that the method is not yet implemented and needs to be filled in.
1094
+ * Generates client code for making API requests using Axios.
1095
+ * @param uri - The API endpoint URI
1096
+ * @param method - The HTTP method (GET, POST, etc.)
1097
+ * @param parameters - Array of parameters to include in the request
1098
+ * @param requestBody - The request body media type definition
1099
+ * @param response - The response media type definition
1100
+ * @param adapter - The adapter instance
1101
+ * @param shouldUseFormData - Flag to use FormData for the request body
1102
+ * @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
1103
+ * @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
1104
+ * @return - An array of generated TypeScript statements
1097
1105
  */
1098
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData) {
1106
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, _shouldUseJSONResponse, isEventStream) {
1099
1107
  const statements = [];
1100
1108
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1101
1109
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1104,9 +1112,13 @@ var AxiosAdapter = class extends Adapter {
1104
1112
  * including method, headers, and body.
1105
1113
  * @returns - The constructed fetch options object
1106
1114
  */
1107
- const toLiterlExpression = () => {
1108
- return factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(inHeader.map((p) => factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? factory.createIdentifier("req") : factory.createIdentifier("req")) : []), true);
1115
+ const toLiterlExpression = (extraProperties = []) => {
1116
+ return factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(inHeader.map((p) => factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? factory.createIdentifier("req") : factory.createIdentifier("req")) : []).concat(extraProperties), true);
1109
1117
  };
1118
+ if (isEventStream) {
1119
+ statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression([factory.createPropertyAssignment(factory.createIdentifier("adapter"), factory.createStringLiteral("fetch")), factory.createPropertyAssignment(factory.createIdentifier("responseType"), factory.createStringLiteral("stream"))])])));
1120
+ return statements;
1121
+ }
1110
1122
  statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1111
1123
  return statements;
1112
1124
  }
@@ -1133,9 +1145,10 @@ var FetchAdapter = class extends Adapter {
1133
1145
  * @param adapter - The adapter instance
1134
1146
  * @param shouldUseFormData - Flag to use FormData for the request body
1135
1147
  * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1148
+ * @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
1136
1149
  * @return - An array of generated TypeScript statements
1137
1150
  */
1138
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse) {
1151
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse, isEventStream) {
1139
1152
  const statements = [];
1140
1153
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1141
1154
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1147,6 +1160,10 @@ var FetchAdapter = class extends Adapter {
1147
1160
  const toLiterlExpression = () => {
1148
1161
  return factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(inHeader.map((p) => factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [requestBody ? factory.createIdentifier("req") : factory.createObjectLiteralExpression(inBody.map((b) => factory.createShorthandPropertyAssignment(factory.createIdentifier(b.name))), true)]) : factory.createIdentifier("req")) : []), true);
1149
1162
  };
1163
+ if (isEventStream) {
1164
+ statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1165
+ return statements;
1166
+ }
1150
1167
  statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), response?.schema ? factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword)) : factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))))]) : factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1151
1168
  return statements;
1152
1169
  }
@@ -1721,15 +1738,57 @@ async function codeGen(initOptions) {
1721
1738
  const PLUGIN_NAME = "api-code-gen";
1722
1739
  const pluginLogger = createScopedLogger("api-code-gen");
1723
1740
  /**
1741
+ * Find the nearest tsconfig.json or jsconfig.json by searching upward.
1742
+ * Bounded by process.cwd() — the Vite project root — to avoid picking up
1743
+ * unrelated configs outside the project.
1744
+ */
1745
+ async function findNearestTsConfig(filePath) {
1746
+ let dir = path.dirname(path.resolve(filePath));
1747
+ const rootDir = process.cwd();
1748
+ const fsRoot = path.parse(dir).root;
1749
+ while (true) {
1750
+ for (const name of ["tsconfig.json", "jsconfig.json"]) {
1751
+ const configPath = path.join(dir, name);
1752
+ if (await fs.pathExists(configPath)) return configPath;
1753
+ }
1754
+ if (dir === rootDir || dir === fsRoot) break;
1755
+ dir = path.dirname(dir);
1756
+ }
1757
+ return null;
1758
+ }
1759
+ /**
1724
1760
  * Run TypeScript type checking on generated file
1725
1761
  */
1726
1762
  async function runTypeCheck(filePath) {
1727
1763
  const { execaCommand } = await import("execa");
1728
1764
  const errors = [];
1765
+ const resolvedPath = path.resolve(filePath);
1766
+ const tsconfigPath = await findNearestTsConfig(resolvedPath);
1767
+ if (!tsconfigPath) {
1768
+ try {
1769
+ await execaCommand(`npx tsc ${resolvedPath} --noEmit`, { shell: true });
1770
+ } catch (error) {
1771
+ if (error instanceof Error) errors.push(error.message);
1772
+ }
1773
+ return errors;
1774
+ }
1775
+ const outputDir = path.dirname(resolvedPath);
1776
+ const tempConfigName = `.${path.basename(resolvedPath).replace(/\.ts$/i, "")}.${Date.now()}.apicodegen.json`;
1777
+ const tempConfigPath = path.join(outputDir, tempConfigName);
1778
+ const tempConfig = {
1779
+ extends: path.relative(outputDir, tsconfigPath),
1780
+ compilerOptions: { noEmit: true },
1781
+ include: [path.basename(resolvedPath)]
1782
+ };
1729
1783
  try {
1730
- await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
1784
+ await fs.writeJson(tempConfigPath, tempConfig);
1785
+ await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
1731
1786
  } catch (error) {
1732
1787
  if (error instanceof Error) errors.push(error.message);
1788
+ } finally {
1789
+ try {
1790
+ await fs.remove(tempConfigPath);
1791
+ } catch {}
1733
1792
  }
1734
1793
  return errors;
1735
1794
  }