@accelbyte/codegen 1.0.0-beta.12 → 1.0.0-beta.16

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.
@@ -88,9 +88,9 @@ const makeNewImportVarMap$1 = () => ({
88
88
  axios: ["AxiosInstance"],
89
89
  "@accelbyte/sdk": ["SDKRequestConfig"]
90
90
  });
91
- const generateImports$1 = (body, importStatements) => {
92
- const usedImportVarMap = makeNewImportVarMap$1();
93
- const importableVarMap = getImportableVarMap$1();
91
+ const generateImports = (body, importStatements, makeNewImportVarMap2, getImportableVarMap2) => {
92
+ const usedImportVarMap = makeNewImportVarMap2;
93
+ const importableVarMap = getImportableVarMap2;
94
94
  for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
95
95
  for (const importableVar of importableVars) {
96
96
  const importVarRegex = new RegExp(`(?<![\\d\\w_])${importableVar}(?![\\d\\w_])`);
@@ -107,7 +107,7 @@ const templateClass = (className, body, importStatements) => {
107
107
  return `/**
108
108
  * AUTO GENERATED
109
109
  */
110
- ${generateImports$1(body, importStatements)}
110
+ ${generateImports(body, importStatements, makeNewImportVarMap$1(), getImportableVarMap$1())}
111
111
 
112
112
  export class ${className} {
113
113
  // @ts-ignore
@@ -123,27 +123,12 @@ const getImportableVarMap = () => ({
123
123
  const makeNewImportVarMap = () => ({
124
124
  "@accelbyte/sdk": ["AccelbyteSDK", "ApiArgs", "ApiUtils"]
125
125
  });
126
- const generateImports = (body, importStatements) => {
127
- const usedImportVarMap = makeNewImportVarMap();
128
- const importableVarMap = getImportableVarMap();
129
- for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
130
- for (const importableVar of importableVars) {
131
- const importVarRegex = new RegExp(`(?<![\\d\\w_])${importableVar}(?![\\d\\w_])`);
132
- if (body.match(importVarRegex)) {
133
- usedImportVarMap[moduleSource] = [...usedImportVarMap[moduleSource] || [], importableVar];
134
- }
135
- }
136
- }
137
- const generatedImports = Object.keys(usedImportVarMap).sort().map((moduleSource) => `import { ${usedImportVarMap[moduleSource].sort().join(", ")} } from '${moduleSource}'`).join("\n");
138
- return `${generatedImports}
139
- ${importStatements.sort().join("\n")}`;
140
- };
141
126
  const templateApiClass = (className, body, importStatements, returnMethods) => {
142
127
  return `/**
143
128
  * AUTO GENERATED
144
129
  */
145
130
  /* eslint-disable camelcase */
146
- ${generateImports(body, importStatements)}
131
+ ${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
147
132
 
148
133
  export function ${className}(sdk: AccelbyteSDK, args?: ApiArgs) {
149
134
  const sdkAssembly = sdk.assembly()
@@ -193,12 +178,18 @@ class ParserUtils {
193
178
  return `${attrName}: ${defaultValue}`;
194
179
  };
195
180
  static parseType = (pathParam) => {
196
- if (pathParam.type === "int" || pathParam.type === "integer" || pathParam?.schema?.type === "integer")
181
+ if (isSwaggerIntegerType(pathParam.type || pathParam?.schema?.type))
197
182
  return "number";
198
- if (pathParam.type === "array")
183
+ if (pathParam.type === "array") {
184
+ if (isSwaggerIntegerType(pathParam.items.type))
185
+ return "number[]";
199
186
  return `${pathParam.items.type ?? "any"}[]`;
200
- if (pathParam?.schema?.type === "array")
187
+ }
188
+ if (pathParam?.schema?.type === "array") {
189
+ if (isSwaggerIntegerType(pathParam.schema.items.type))
190
+ return "number[]";
201
191
  return `${pathParam.schema.items.type ?? "any"}[]`;
192
+ }
202
193
  if (pathParam?.schema?.type)
203
194
  return pathParam.schema.type;
204
195
  return pathParam.type;
@@ -289,6 +280,8 @@ class ParserUtils {
289
280
  return retBodyParams;
290
281
  }
291
282
  if (bodyParam?.schema?.type === "array" && !bodyParam?.schema?.items?.$ref) {
283
+ if (isSwaggerIntegerType(bodyParam.schema.items.type))
284
+ return "number[]";
292
285
  return `${bodyParam.schema.items.type ?? "any"}[]`;
293
286
  }
294
287
  if (bodyParam?.schema?.type === "array" && bodyParam?.schema?.items?.$ref) {
@@ -600,6 +593,9 @@ const testConflict = (path2, generatedMethod, existingMethods) => {
600
593
  existingMethods: ${JSON.stringify(existingMethods, null, 2)}`);
601
594
  }
602
595
  };
596
+ const isSwaggerIntegerType = (type) => {
597
+ return type === "integer" || type === "int";
598
+ };
603
599
 
604
600
  const Schema = zod.z.object({
605
601
  $ref: zod.z.string().nullish(),
@@ -706,8 +702,6 @@ const templateMethod = ({
706
702
  let methodParamsNoTypes = "";
707
703
  let newPath = `'${path}'`;
708
704
  let importStatements = [];
709
- let snippetString = "";
710
- let snippetMethodSignature = "";
711
705
  for (const pathParam of pathParams) {
712
706
  const type = ParserUtils.parseType(pathParam);
713
707
  if (pathParam.name !== "namespace") {
@@ -729,13 +723,6 @@ const templateMethod = ({
729
723
  importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
730
724
  methodParams += dataType ? `data: ${dataType},` : "";
731
725
  methodParamsNoTypes += dataType ? `data,` : "";
732
- const snippetParams = bodyParams?.map((ob) => {
733
- return ` <span class='sn-purple'>${ob.name}</span>`;
734
- });
735
- snippetMethodSignature += snippetParams ? `data: { ${snippetParams} }` : "";
736
- bodyParams?.map((ob) => {
737
- return ` <span class='sn-purple'>"${ob.name}": ""</span>`;
738
- });
739
726
  }
740
727
  const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
741
728
  const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
@@ -772,8 +759,6 @@ const templateMethod = ({
772
759
  const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
773
760
  const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
774
761
  const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
775
- const generateSnippetMethodName = () => `${methodName}(${snippetMethodSignature})`;
776
- snippetString += `${generateSnippetMethodName()}`;
777
762
  const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
778
763
  methodImpl = `${descriptionText}
779
764
  ${generateMethodName()} {
@@ -804,8 +789,7 @@ ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resu
804
789
  methodImpl,
805
790
  methodParams,
806
791
  methodParamsNoTypes,
807
- importStatements,
808
- snippetString
792
+ importStatements
809
793
  };
810
794
  return res;
811
795
  };
@@ -1069,7 +1053,6 @@ const templateApiMethod = ({
1069
1053
  path,
1070
1054
  pathParams,
1071
1055
  bodyParams,
1072
- queryParams,
1073
1056
  responseClass,
1074
1057
  classGenName,
1075
1058
  methodParams,
@@ -1077,7 +1060,6 @@ const templateApiMethod = ({
1077
1060
  }) => {
1078
1061
  let methodSignature = "";
1079
1062
  let newPath = `'${path}'`;
1080
- let dependencies = [];
1081
1063
  let snippetSdk = "";
1082
1064
  let snippetShell = "";
1083
1065
  for (const pathParam of pathParams) {
@@ -1094,30 +1076,24 @@ const templateApiMethod = ({
1094
1076
  }
1095
1077
  }
1096
1078
  }
1097
- snippetShell = `<span class='sn-blue'>curl</span> --location --request <span class='sn-blue'>${httpMethod}</span> '<span class='sn-green'>__DOMAIN__${path}</span>' --header 'accept: application/json'`;
1098
- let dataType = null;
1079
+ snippetShell = `curl --location --request \\
1080
+ ${httpMethod} '__DOMAIN__${path}' \\
1081
+ --header 'accept: application/json'`;
1099
1082
  if (httpMethod !== "get") {
1100
- dataType = ParserUtils.parseBodyParamsType(bodyParams);
1101
- dependencies = ParserUtils.parseBodyParamsImports(bodyParams);
1102
- methodSignature += dataType ? `data: ${dataType},` : "";
1103
- bodyParams?.map((ob) => {
1104
- return ` <span class='sn-purple'>${ob.name}</span>`;
1105
- });
1106
1083
  const curlParams = bodyParams?.map((ob) => {
1107
- return ` <span class='sn-purple'>"${ob.name}": ""</span>`;
1084
+ return ` "${ob.name}": ""`;
1108
1085
  });
1109
- snippetShell += ` --data-raw { ${curlParams}}`;
1086
+ snippetShell += ` \\
1087
+ --data-raw '{ ${curlParams}}'`;
1110
1088
  }
1111
- const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
1112
- queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
1113
- queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
1114
- description ? `
1089
+ const descriptionText = description ? `
1115
1090
  /**
1116
1091
  * ${description.replace(/\n/g, "\n * ")}
1117
1092
  */` : "";
1118
1093
  const resolvedResponseClass = responseClass || "unknown";
1119
1094
  const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1120
1095
  const methodImpl = `
1096
+ ${descriptionText}
1121
1097
  async function ${classMethod}(${methodParams}): Promise<${responseType}> {
1122
1098
  const $ = new ${classGenName}(Network.create(requestConfig), namespace, cache)
1123
1099
  const resp = await $.${classMethod}(${methodParamsNoTypes})
@@ -1125,8 +1101,10 @@ const templateApiMethod = ({
1125
1101
  return resp.response.data
1126
1102
  }
1127
1103
  `;
1128
- snippetSdk += `${classMethod}(${methodParams}) // return Promise<${responseType}>`;
1129
- return [methodImpl, dependencies, snippetSdk, snippetShell];
1104
+ const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
1105
+ snippetSdk += `${classMethod}(${methodParams})
1106
+ // return ${snippetPromiseString}`;
1107
+ return [methodImpl, snippetSdk, snippetShell];
1130
1108
  };
1131
1109
 
1132
1110
  const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
@@ -1152,26 +1130,44 @@ export const ${ParserUtils.convertDashesToTitleCase(serviceNameTitle)} = apis
1152
1130
  };
1153
1131
 
1154
1132
  const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1155
- const sdkSnippet = `
1156
- import { Accelbyte } from '@accelbyte/sdk'
1133
+ const methodArr = methodSnippet.split("//");
1134
+ let normMethod = normalizeMethodSnippet(methodArr[0].trim(), "data:");
1135
+ normMethod = normalizeMethodSnippet(normMethod, "queryParams:");
1136
+ normMethod = normalizeMethodSnippet(normMethod, "queryParams?:");
1137
+ normMethod += "\n\n//" + methodArr[1];
1138
+ const sdkSnippet = `import { Accelbyte } from '@accelbyte/sdk'
1157
1139
  import { ${serviceNameTitle} } from '@accelbyte/sdk-${serviceNameTitle.toLowerCase()}'
1158
1140
 
1159
- const SDK_CONFIG = {
1141
+ const sdk = Accelbyte.SDK({
1160
1142
  baseURL: 'https://demo.accelbyte.io',
1161
1143
  clientId: '77f88506b6174c3ea4d925f5b4096ce8',
1162
1144
  namespace: 'accelbyte',
1163
1145
  redirectURI: 'http://localhost:3030'
1164
- }
1165
-
1166
- const sdk = Accelbyte.SDK({
1167
- options: SDK_CONFIG
1168
1146
  })
1169
1147
 
1170
- ${serviceNameTitle}.${apiName}(sdk).${methodSnippet}
1171
- `;
1148
+ ${serviceNameTitle}.${apiName}(sdk)
1149
+ .${normMethod}`;
1172
1150
  return sdkSnippet;
1173
1151
  };
1152
+ const normalizeMethodSnippet = (methodInput, splitWord) => {
1153
+ const split1 = methodInput.split(splitWord);
1154
+ if (!split1[1]) {
1155
+ return methodInput;
1156
+ }
1157
+ let split2 = split1[1].trim();
1158
+ split2 = ParserUtils.replaceAll(split2, "{", "");
1159
+ split2 = ParserUtils.replaceAll(split2, "})", "");
1160
+ split2 = split2.split(",");
1161
+ let params = "";
1162
+ split2.forEach((p) => {
1163
+ params += "\n " + ParserUtils.replaceAll(p.trim(), ")", "") + ",";
1164
+ });
1165
+ params = params.slice(0, -1);
1166
+ const result = split1[0] + splitWord + " {" + params + "\n })";
1167
+ return result;
1168
+ };
1174
1169
 
1170
+ const GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
1175
1171
  class CodeGenerator {
1176
1172
  static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
1177
1173
  static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
@@ -1254,7 +1250,7 @@ class CodeGenerator {
1254
1250
  }
1255
1251
  ];
1256
1252
  }
1257
- const { methodImpl, methodParams, methodParamsNoTypes, importStatements, snippetString } = templateMethod({
1253
+ const { methodImpl, methodParams, methodParamsNoTypes, importStatements } = templateMethod({
1258
1254
  classMethod,
1259
1255
  description,
1260
1256
  httpMethod,
@@ -1266,14 +1262,13 @@ class CodeGenerator {
1266
1262
  responseClass
1267
1263
  });
1268
1264
  classBufferByTag[tag] = (classBufferByTag[tag] || "") + methodImpl;
1269
- const [generatedMethodString1, importStatements1, snippetMethod, snippetShell] = templateApiMethod({
1265
+ const [generatedMethodString1, snippetMethod, snippetShell] = templateApiMethod({
1270
1266
  classMethod,
1271
1267
  description,
1272
1268
  httpMethod,
1273
1269
  path: pathWithBase,
1274
1270
  pathParams,
1275
1271
  bodyParams,
1276
- queryParams,
1277
1272
  responseClass,
1278
1273
  classGenName,
1279
1274
  methodParams,
@@ -1284,12 +1279,10 @@ class CodeGenerator {
1284
1279
  dependenciesByTag[tag] = dependenciesByTag[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...dependenciesByTag[tag]])] : [...new Set(importStatements)];
1285
1280
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1286
1281
  const { apiGenName } = ParserUtils.generateApiName(tag);
1287
- let resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1288
- resultSnippet = ParserUtils.replaceAll(resultSnippet, "<", "&lt;");
1289
- resultSnippet = ParserUtils.replaceAll(resultSnippet, ">", "&gt;");
1290
- resultSnippet = ParserUtils.replaceAll(resultSnippet, "\n", "<br/>");
1282
+ const resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1291
1283
  snippetMap[path2][httpMethod] = {
1292
1284
  web: resultSnippet,
1285
+ webGit: GIT_URL + `/sdk-${serviceName}/src/generated-public/${serviceName}/${apiGenName}.ts`,
1293
1286
  shell: snippetShell
1294
1287
  };
1295
1288
  }
@@ -1392,6 +1385,22 @@ class SwaggerDownloader {
1392
1385
  fs__namespace.writeFileSync(destFile, "");
1393
1386
  return destFile;
1394
1387
  };
1388
+ static postSanitizeDownloadedFile = (filePath) => {
1389
+ const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
1390
+ fs__namespace.readFile(filePath, "utf8", (err, data) => {
1391
+ if (err)
1392
+ throw err;
1393
+ let result = data;
1394
+ searchStr.forEach((s) => {
1395
+ result = result.replace(new RegExp(s, "g"), " ");
1396
+ });
1397
+ fs__namespace.writeFile(filePath, result, "utf8", (err2) => {
1398
+ if (err2)
1399
+ throw err2;
1400
+ console.log("File updated successfully.");
1401
+ });
1402
+ });
1403
+ };
1395
1404
  static downloadFile = (targetFileName, url) => {
1396
1405
  const destFile = SwaggerDownloader.getDestFile(targetFileName);
1397
1406
  const file = fs__namespace.createWriteStream(destFile);
@@ -1399,6 +1408,7 @@ class SwaggerDownloader {
1399
1408
  response.pipe(file);
1400
1409
  file.on("finish", () => {
1401
1410
  file.close();
1411
+ SwaggerDownloader.postSanitizeDownloadedFile(destFile);
1402
1412
  console.log(`SwaggerDownload ${url} completed`);
1403
1413
  });
1404
1414
  });