@moccona/apicodegen 0.0.10 → 0.1.0
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/README.md +7 -0
- package/bin/cli.cjs +4 -4
- package/npm/index.cjs +76 -17
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +17 -8
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +17 -8
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +76 -17
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +76 -17
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +1 -1
package/npm/vite/index.d.mts.map
CHANGED
|
@@ -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;;;;;;;
|
|
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"}
|
package/npm/vite/index.mjs
CHANGED
|
@@ -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";
|
|
@@ -830,7 +831,7 @@ var Generator = class Generator {
|
|
|
830
831
|
static toUrlTemplate(path, parameters, basePath = "") {
|
|
831
832
|
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
832
833
|
if (queryParameters.length > 0) {
|
|
833
|
-
const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.
|
|
834
|
+
const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.normalize(qp.name)}}`).join("");
|
|
834
835
|
path += queryString;
|
|
835
836
|
}
|
|
836
837
|
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
@@ -839,7 +840,7 @@ var Generator = class Generator {
|
|
|
839
840
|
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
840
841
|
const isLastSegment = index === pathSegments.length - 2;
|
|
841
842
|
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
842
|
-
return factory.createTemplateSpan(factory.createIdentifier(match[1]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
843
|
+
return factory.createTemplateSpan(factory.createIdentifier(Base.normalize(match[1])), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
843
844
|
}));
|
|
844
845
|
}
|
|
845
846
|
/**
|
|
@@ -891,7 +892,7 @@ var Generator = class Generator {
|
|
|
891
892
|
static generateParamTags(parameters, requestBody) {
|
|
892
893
|
const tags = [];
|
|
893
894
|
for (const p of parameters) {
|
|
894
|
-
const paramName = Base.
|
|
895
|
+
const paramName = Base.normalize(p.name);
|
|
895
896
|
let paramType = "unknown";
|
|
896
897
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
897
898
|
const isOptional = p.required === false;
|
|
@@ -975,11 +976,11 @@ var Generator = class Generator {
|
|
|
975
976
|
const refParameters = [];
|
|
976
977
|
for (const parameter of parameters) if (parameter.ref) {
|
|
977
978
|
const refName = Base.ref2name(parameter.ref);
|
|
978
|
-
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.
|
|
979
|
+
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.normalize(refName)), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
979
980
|
} else {
|
|
980
981
|
const { name, schema, required } = parameter;
|
|
981
|
-
objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.
|
|
982
|
-
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.
|
|
982
|
+
objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.normalize(name))));
|
|
983
|
+
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.normalize(name)), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
983
984
|
}
|
|
984
985
|
if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
985
986
|
return refParameters;
|
|
@@ -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
|
-
*
|
|
1093
|
-
*
|
|
1094
|
-
* @
|
|
1095
|
-
*
|
|
1096
|
-
* @
|
|
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");
|
|
@@ -1105,8 +1113,12 @@ var AxiosAdapter = class extends Adapter {
|
|
|
1105
1113
|
* @returns - The constructed fetch options object
|
|
1106
1114
|
*/
|
|
1107
1115
|
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.
|
|
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")) : []), true);
|
|
1109
1117
|
};
|
|
1118
|
+
if (isEventStream) {
|
|
1119
|
+
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
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");
|
|
@@ -1145,8 +1158,12 @@ var FetchAdapter = class extends Adapter {
|
|
|
1145
1158
|
* @returns - The constructed fetch options object
|
|
1146
1159
|
*/
|
|
1147
1160
|
const toLiterlExpression = () => {
|
|
1148
|
-
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.
|
|
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
|
|
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
|
}
|