@accelbyte/codegen 2.1.0 → 2.3.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.
package/.eslintrc.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "plugins": ["unused-imports"],
3
+ "rules": {
4
+ "unused-imports/no-unused-imports": "error"
5
+ }
6
+ }
@@ -114,7 +114,7 @@ ${generateImports(body, importStatements, makeNewImportVarMap$1(), getImportable
114
114
 
115
115
  export class ${className} {
116
116
  // @ts-ignore
117
- constructor(private axiosInstance: AxiosInstance, private namespace: string, private cache = false) {}
117
+ constructor(private axiosInstance: AxiosInstance, private namespace: string, private cache = false, private isValidationEnabled = true) {}
118
118
  ${body}
119
119
  }
120
120
  `;
@@ -139,6 +139,7 @@ export function ${className}(sdk: AccelbyteSDK, args?: ApiArgs) {
139
139
  const namespace = args?.namespace ? args?.namespace : sdkAssembly.namespace
140
140
  const cache = args?.cache ? args?.cache : sdkAssembly.cache
141
141
  const requestConfig = ApiUtils.mergedConfigs(sdkAssembly.config, args)
142
+ const isValidationEnabled = args?.isValidationEnabled !== false
142
143
  ${body}
143
144
 
144
145
  return {
@@ -940,7 +941,7 @@ const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
940
941
  let imports = "";
941
942
  let returnStatement = "";
942
943
  for (const cl of apiList) {
943
- const dir = cl.toLowerCase().includes("admin") ? "generated-admin" : "generated-public";
944
+ const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
944
945
  imports += `
945
946
  import { ${cl} } from './${dir}/${cl}.js'`;
946
947
  returnStatement += `
@@ -1020,7 +1021,8 @@ const Endpoint = zod.z.object({
1020
1021
  schema: Schema.nullish()
1021
1022
  })
1022
1023
  }).nullish()
1023
- }).nullish()
1024
+ }).nullish(),
1025
+ "x-security": zod.z.any().nullish()
1024
1026
  });
1025
1027
  const Operation = zod.z.object({
1026
1028
  get: Endpoint.nullish(),
@@ -1059,7 +1061,8 @@ const templateMethod = ({
1059
1061
  bodyParams,
1060
1062
  queryParams,
1061
1063
  isFormUrlEncoded,
1062
- responseClass
1064
+ responseClass,
1065
+ deprecated
1063
1066
  }) => {
1064
1067
  let methodParams = "";
1065
1068
  let methodParamsNoTypes = "";
@@ -1095,7 +1098,7 @@ const templateMethod = ({
1095
1098
  const isDelete = ["delete"].includes(httpMethod);
1096
1099
  let dataPayload = "{params}";
1097
1100
  const descriptionText = description ? `
1098
- /**
1101
+ /**${deprecated ? "\n * @deprecated" : ""}
1099
1102
  * ${description.replace(/\n/g, "\n * ")}
1100
1103
  */` : "";
1101
1104
  let formPayloadString = "";
@@ -1130,13 +1133,13 @@ const templateMethod = ({
1130
1133
  const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1131
1134
  const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
1132
1135
 
1133
- ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')
1136
+ ${httpMethod === "get" ? ` const res = () => this.isValidationEnabled ? Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}') : Validate.unsafeResponse(() => resultPromise)
1134
1137
 
1135
1138
  if (!this.cache) {
1136
1139
  return SdkCache.withoutCache(res)
1137
1140
  }
1138
1141
  const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
1139
- return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')` : ""}
1142
+ return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return this.isValidationEnabled ? Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}') : Validate.unsafeResponse(() => resultPromise)` : ""}
1140
1143
  }
1141
1144
  `;
1142
1145
  if (!isGuardInvoked) {
@@ -1168,17 +1171,14 @@ const templateApiMethod = ({
1168
1171
  responseClass,
1169
1172
  classGenName,
1170
1173
  methodParams,
1171
- methodParamsNoTypes
1174
+ methodParamsNoTypes,
1175
+ deprecated,
1176
+ xSecurity
1172
1177
  }) => {
1173
- let methodSignature = "";
1174
1178
  let newPath = `'${path}'`;
1175
- let snippetSdk = "";
1176
- let snippetShell = "";
1179
+ let snippetMethod = "";
1177
1180
  for (const pathParam of pathParams) {
1178
1181
  const type = ParserUtils.parseType(pathParam);
1179
- if (pathParam.name !== "namespace") {
1180
- methodSignature += pathParam.name + `:${type}, `;
1181
- }
1182
1182
  const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1183
1183
  if (path.match(`{${pathParam.name}}`)) {
1184
1184
  if (type === "string") {
@@ -1188,18 +1188,23 @@ const templateApiMethod = ({
1188
1188
  }
1189
1189
  }
1190
1190
  }
1191
- snippetShell = `curl --location --request \\
1192
- ${httpMethod} '__DOMAIN__${path}' \\
1193
- --header 'accept: application/json'`;
1191
+ const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path}'`, "--header 'accept: application/json'"];
1192
+ const snippetApiArgs = [];
1193
+ if (xSecurity !== void 0 || path.includes("/admin")) {
1194
+ snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
1195
+ snippetApiArgs.push("{ config: { headers: { Authorization: 'Bearer {access_token}' } }}".trim());
1196
+ }
1194
1197
  if (httpMethod !== "get") {
1195
1198
  const curlParams = bodyParams?.map((ob) => {
1196
1199
  return ` "${ob.name}": ""`;
1197
1200
  });
1198
- snippetShell += ` \\
1199
- --data-raw '{ ${curlParams}}'`;
1201
+ if (curlParams.length > 0) {
1202
+ snippetShellArgs.push(`--data-raw '{ ${curlParams}}'`);
1203
+ }
1200
1204
  }
1205
+ const snippetShell = `curl ${snippetShellArgs.join(" \\\n ")}`;
1201
1206
  const descriptionText = description ? `
1202
- /**
1207
+ /**${deprecated ? "\n * @deprecated" : ""}
1203
1208
  * ${description.replace(/\n/g, "\n * ")}
1204
1209
  */` : "";
1205
1210
  const resolvedResponseClass = responseClass || "unknown";
@@ -1207,20 +1212,31 @@ const templateApiMethod = ({
1207
1212
  const methodImpl = `
1208
1213
  ${descriptionText}
1209
1214
  async function ${classMethod}(${methodParams}): Promise<${responseType}> {
1210
- const $ = new ${classGenName}(Network.create(requestConfig), namespace, cache)
1215
+ const $ = new ${classGenName}(Network.create(requestConfig), namespace, cache, isValidationEnabled)
1211
1216
  const resp = await $.${classMethod}(${methodParamsNoTypes})
1212
1217
  if (resp.error) throw resp.error
1213
1218
  return resp.response.data
1214
1219
  }
1215
1220
  `;
1216
1221
  const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
1217
- snippetSdk += `${classMethod}(${methodParams})
1222
+ snippetMethod += `${classMethod}(${methodParams})
1218
1223
  // return ${snippetPromiseString}`;
1219
- return [methodImpl, snippetSdk, snippetShell];
1224
+ return {
1225
+ generatedMethodString: methodImpl,
1226
+ snippetApiArgs,
1227
+ snippetMethod,
1228
+ snippetShell
1229
+ };
1220
1230
  };
1221
1231
 
1222
- const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1223
- const methodArr = methodSnippet.split("//");
1232
+ const templateSdkSnippet = ({
1233
+ serviceNameTitle,
1234
+ apiName,
1235
+ snippetMethod,
1236
+ snippetApiArgs: snippetApiArgsParam
1237
+ }) => {
1238
+ const methodArr = snippetMethod.split("//");
1239
+ const snippetApiArgs = ["sdk", ...snippetApiArgsParam];
1224
1240
  let normMethod = normalizeMethodSnippet(methodArr[0].trim(), "data:");
1225
1241
  normMethod = normalizeMethodSnippet(normMethod, "queryParams:");
1226
1242
  normMethod = normalizeMethodSnippet(normMethod, "queryParams?:");
@@ -1229,14 +1245,16 @@ const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1229
1245
  import { ${serviceNameTitle} } from '@accelbyte/sdk-${serviceNameTitle.toLowerCase()}'
1230
1246
 
1231
1247
  const sdk = Accelbyte.SDK({
1248
+ options: {
1232
1249
  baseURL: 'https://demo.accelbyte.io',
1233
1250
  clientId: '77f88506b6174c3ea4d925f5b4096ce8',
1234
1251
  namespace: 'accelbyte',
1235
1252
  redirectURI: 'http://localhost:3030'
1253
+ }
1236
1254
  })
1237
1255
 
1238
- ${serviceNameTitle}.${apiName}(sdk)
1239
- .${normMethod}`;
1256
+ ${serviceNameTitle}.${apiName}(${snippetApiArgs.join(", ")})
1257
+ .${normMethod}`;
1240
1258
  return sdkSnippet;
1241
1259
  };
1242
1260
  const normalizeMethodSnippet = (methodInput, splitWord) => {
@@ -1320,7 +1338,7 @@ class SwaggerReaderHelpers {
1320
1338
  console.error(JSON.stringify({ path, httpMethod }, null, 2));
1321
1339
  throw error;
1322
1340
  });
1323
- if (!endpoint.tags || endpoint.deprecated)
1341
+ if (!endpoint.tags)
1324
1342
  continue;
1325
1343
  const [tag] = endpoint.tags;
1326
1344
  const pathWithBase = `${api.basePath ?? ""}${path}`;
@@ -1352,6 +1370,7 @@ class SwaggerReaderHelpers {
1352
1370
  const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
1353
1371
  const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
1354
1372
  let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
1373
+ const deprecated = !!endpoint.deprecated;
1355
1374
  if (endpoint.requestBody) {
1356
1375
  bodyParams = [
1357
1376
  {
@@ -1370,10 +1389,11 @@ class SwaggerReaderHelpers {
1370
1389
  bodyParams,
1371
1390
  queryParams,
1372
1391
  isFormUrlEncoded,
1373
- responseClass
1392
+ responseClass,
1393
+ deprecated
1374
1394
  });
1375
1395
  tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1376
- const [generatedMethodString, snippetMethod, snippetShell] = templateApiMethod({
1396
+ const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
1377
1397
  classMethod,
1378
1398
  description,
1379
1399
  httpMethod,
@@ -1383,20 +1403,21 @@ class SwaggerReaderHelpers {
1383
1403
  responseClass,
1384
1404
  classGenName,
1385
1405
  methodParams,
1386
- methodParamsNoTypes
1406
+ methodParamsNoTypes,
1407
+ deprecated,
1408
+ xSecurity: endpoint["x-security"]
1387
1409
  });
1388
1410
  tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1389
1411
  tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
1390
1412
  tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1391
1413
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1392
1414
  const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1393
- const resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1415
+ const resultSnippet = templateSdkSnippet({ serviceNameTitle, apiName: apiGenName, snippetMethod, snippetApiArgs });
1394
1416
  const currentSnippetMap = {};
1395
1417
  snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
1396
- if (!isAdminEndpoint) {
1397
- currentSnippetMap.web = !isAdminEndpoint ? resultSnippet : "";
1398
- currentSnippetMap.webGit = !isAdminEndpoint ? GIT_URL + `/sdk-${sdkName}/src/generated-public/${serviceName}/${apiGenName}.ts` : "";
1399
- }
1418
+ currentSnippetMap.web = resultSnippet;
1419
+ const generatedDirName = isAdminEndpoint ? "generated-admin" : "generated-public";
1420
+ currentSnippetMap.webGit = GIT_URL + `/sdk-${sdkName}/src/${generatedDirName}/${apiGenName}.ts`;
1400
1421
  currentSnippetMap.shell = snippetShell;
1401
1422
  }
1402
1423
  }