@accelbyte/codegen 2.0.0-beta.5 → 2.0.0-beta.6

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.
@@ -238,14 +238,14 @@ class ParserUtils {
238
238
  static replaceAll = (string, search, replace) => {
239
239
  return string.split(search).join(replace);
240
240
  };
241
- static generateClassName = (tag) => {
241
+ static generateClassName = (tag, isAdmin) => {
242
242
  const className = _.upperFirst(_.camelCase(tag));
243
- const classGenName = CliParser.isAdmin() ? className + "Admin$" : className + "$";
243
+ const classGenName = isAdmin ? className + "Admin$" : className + "$";
244
244
  return { className, classGenName };
245
245
  };
246
- static generateApiName = (tag) => {
246
+ static generateApiName = (tag, isAdmin) => {
247
247
  const apiName = _.upperFirst(_.camelCase(tag));
248
- const apiGenName = CliParser.isAdmin() ? apiName + "AdminApi" : apiName + "Api";
248
+ const apiGenName = isAdmin ? apiName + "AdminApi" : apiName + "Api";
249
249
  return { apiName, apiGenName };
250
250
  };
251
251
  static parseQueryParamAttributeDefault = (definition) => {
@@ -617,9 +617,7 @@ class ParserUtils {
617
617
  ${content}`;
618
618
  };
619
619
  static sortPathParamsByPath = (pathParams, path2) => {
620
- const params = path2.match(/{\w*}/g) || [];
621
- const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
622
- return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
620
+ return pathParams.sort((a, b) => path2.indexOf(a.name) - path2.indexOf(b.name));
623
621
  };
624
622
  }
625
623
  const mappedMethod = (httpMethod, isForm) => {
@@ -687,205 +685,6 @@ const isSwaggerIntegerType = (type) => {
687
685
  return type === "integer" || type === "int";
688
686
  };
689
687
 
690
- const Schema = zod.z.object({
691
- $ref: zod.z.string().nullish(),
692
- type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
693
- items: zod.z.object({
694
- $ref: zod.z.string().nullish(),
695
- type: zod.z.string().nullish()
696
- }).nullish(),
697
- properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
698
- description: zod.z.string().nullish(),
699
- additionalProperties: zod.z.object({
700
- type: zod.z.string().nullish()
701
- }).nullish()
702
- });
703
- const Definition = zod.z.object({
704
- required: zod.z.array(zod.z.string()).nullish(),
705
- properties: zod.z.record(zod.z.object({
706
- type: zod.z.string()
707
- })).nullish()
708
- });
709
- const Definitions = zod.z.record(Definition);
710
- const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
711
- const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
712
- const EndpointParameters = zod.z.object({
713
- type: EndpointParametersType.nullish(),
714
- description: zod.z.string().nullish(),
715
- name: zod.z.string(),
716
- in: EndpointParametersIn,
717
- required: zod.z.boolean().nullish(),
718
- schema: Schema.nullish(),
719
- default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
720
- enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
721
- items: zod.z.object({
722
- type: zod.z.string(),
723
- enum: zod.z.array(zod.z.any()).nullish()
724
- }).nullish()
725
- });
726
- const Endpoint = zod.z.object({
727
- description: zod.z.string().nullish(),
728
- consumes: zod.z.array(zod.z.string()).nullish(),
729
- produces: zod.z.array(zod.z.string()).nullish(),
730
- tags: zod.z.array(zod.z.string()).nullish(),
731
- summary: zod.z.string().nullish(),
732
- operationId: zod.z.string(),
733
- deprecated: zod.z.boolean().nullish(),
734
- responses: zod.z.record(zod.z.object({
735
- description: zod.z.string().nullish(),
736
- schema: Schema.nullish(),
737
- content: zod.z.object({
738
- "application/json": zod.z.object({
739
- schema: Schema.nullish()
740
- })
741
- }).nullish()
742
- })),
743
- parameters: zod.z.array(EndpointParameters).nullish(),
744
- requestBody: zod.z.object({
745
- required: zod.z.boolean(),
746
- content: zod.z.object({
747
- "application/json": zod.z.object({
748
- schema: Schema.nullish()
749
- })
750
- }).nullish()
751
- }).nullish()
752
- });
753
- const Operation = zod.z.object({
754
- get: Endpoint.nullish(),
755
- post: Endpoint.nullish(),
756
- patch: Endpoint.nullish(),
757
- delete: Endpoint.nullish(),
758
- put: Endpoint.nullish()
759
- });
760
- const Paths = zod.z.record(Operation);
761
- zod.z.object({
762
- paths: Paths,
763
- definitions: Definitions,
764
- basePath: zod.z.string(),
765
- info: zod.z.object({
766
- description: zod.z.string(),
767
- title: zod.z.string(),
768
- contact: zod.z.object({
769
- name: zod.z.string(),
770
- url: zod.z.string(),
771
- email: zod.z.string()
772
- }),
773
- version: zod.z.string()
774
- }),
775
- schemes: zod.z.array(zod.z.string()).nullish(),
776
- components: zod.z.object({
777
- schemas: Definitions
778
- }).nullish()
779
- });
780
-
781
- const templateMethod = ({
782
- classMethod,
783
- description,
784
- httpMethod,
785
- path,
786
- pathParams,
787
- bodyParams,
788
- queryParams,
789
- isFormUrlEncoded,
790
- responseClass
791
- }) => {
792
- let methodParams = "";
793
- let methodParamsNoTypes = "";
794
- let newPath = `'${path}'`;
795
- let importStatements = [];
796
- const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
797
- for (const pathParam of sortedPathParams) {
798
- const type = ParserUtils.parseType(pathParam);
799
- if (pathParam.name !== "namespace") {
800
- methodParams += pathParam.name + `:${type}, `;
801
- methodParamsNoTypes += pathParam.name + ", ";
802
- }
803
- const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
804
- if (path.match(`{${pathParam.name}}`)) {
805
- if (type === "string") {
806
- newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
807
- } else {
808
- newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
809
- }
810
- }
811
- }
812
- let dataType = null;
813
- if (httpMethod !== "get") {
814
- dataType = ParserUtils.parseBodyParamsType(bodyParams);
815
- importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
816
- methodParams += dataType ? `data: ${dataType},` : "";
817
- methodParamsNoTypes += dataType ? `data,` : "";
818
- }
819
- const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
820
- const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
821
- const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
822
- const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
823
- const isDelete = ["delete"].includes(httpMethod);
824
- let dataPayload = "{params}";
825
- const descriptionText = description ? `
826
- /**
827
- * ${description.replace(/\n/g, "\n * ")}
828
- */` : "";
829
- let formPayloadString = "";
830
- if (isFormUrlEncoded) {
831
- formPayloadString = ``;
832
- const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
833
- dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
834
- } else if (isPostPutPatch) {
835
- dataPayload = dataType ? `data, {params}` : "null, {params}";
836
- } else if (isDelete) {
837
- dataPayload = dataType ? `{data, params}` : "{params}";
838
- }
839
- const isFileUpload = methodParams.indexOf("data: {file") > -1;
840
- const resolvedResponseClass = responseClass || "unknown";
841
- const resolvedResponseClassValidated = responseClass || "z.unknown()";
842
- methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
843
- methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
844
- let methodImpl = "";
845
- const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
846
- const cachedFetchMethod = classMethod;
847
- const deprecateTag = isCacheFetch ? `/**
848
- * @deprecated Use "${classMethod}()" instead.
849
- */` : "";
850
- const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
851
- const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
852
- const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
853
- const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
854
- const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
855
- methodImpl = `${descriptionText}
856
- ${generateMethodName()} {
857
- ${queryParamsDefault}
858
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
859
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
860
-
861
- ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')
862
-
863
- if (!this.cache) {
864
- return SdkCache.withoutCache(res)
865
- }
866
- const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
867
- return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')` : ""}
868
- }
869
- `;
870
- if (!isGuardInvoked) {
871
- methodImpl = `${descriptionText}
872
- ${deprecateTag}
873
- TODO_${classMethod}(${methodParams}): Promise<AxiosResponse<${resolvedResponseClass}>> {
874
- ${queryParamsDefault}
875
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
876
- return this.axiosInstance.${httpMethod}(url, ${dataPayload})
877
- }
878
- `;
879
- }
880
- const res = {
881
- methodImpl,
882
- methodParams,
883
- methodParamsNoTypes,
884
- importStatements
885
- };
886
- return res;
887
- };
888
-
889
688
  class TemplateZod {
890
689
  duplicates;
891
690
  duplicateFound = false;
@@ -1138,6 +937,227 @@ const extractEnumObject = (type, isRequired, enumArr) => {
1138
937
  };
1139
938
  };
1140
939
 
940
+ const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
941
+ let imports = "";
942
+ let returnStatement = "";
943
+ for (const cl of apiList) {
944
+ imports += `
945
+ import { ${cl} } from './${serviceName}/${cl}.js'`;
946
+ returnStatement += `
947
+ ${cl}, `;
948
+ }
949
+ return `/**
950
+ * AUTO GENERATED
951
+ */
952
+ ${imports}
953
+
954
+ const apis = {
955
+ ${returnStatement}
956
+ }
957
+
958
+ export const ${ParserUtils.convertDashesToTitleCase(serviceNameTitle)} = apis
959
+ `;
960
+ };
961
+
962
+ const Schema = zod.z.object({
963
+ $ref: zod.z.string().nullish(),
964
+ type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
965
+ items: zod.z.object({
966
+ $ref: zod.z.string().nullish(),
967
+ type: zod.z.string().nullish()
968
+ }).nullish(),
969
+ properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
970
+ description: zod.z.string().nullish(),
971
+ additionalProperties: zod.z.object({
972
+ type: zod.z.string().nullish()
973
+ }).nullish()
974
+ });
975
+ const Definition = zod.z.object({
976
+ required: zod.z.array(zod.z.string()).nullish(),
977
+ properties: zod.z.record(zod.z.object({
978
+ type: zod.z.string()
979
+ })).nullish()
980
+ });
981
+ const Definitions = zod.z.record(Definition);
982
+ const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
983
+ const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
984
+ const EndpointParameters = zod.z.object({
985
+ type: EndpointParametersType.nullish(),
986
+ description: zod.z.string().nullish(),
987
+ name: zod.z.string(),
988
+ in: EndpointParametersIn,
989
+ required: zod.z.boolean().nullish(),
990
+ schema: Schema.nullish(),
991
+ default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
992
+ enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
993
+ items: zod.z.object({
994
+ type: zod.z.string(),
995
+ enum: zod.z.array(zod.z.any()).nullish()
996
+ }).nullish()
997
+ });
998
+ const Endpoint = zod.z.object({
999
+ description: zod.z.string().nullish(),
1000
+ consumes: zod.z.array(zod.z.string()).nullish(),
1001
+ produces: zod.z.array(zod.z.string()).nullish(),
1002
+ tags: zod.z.array(zod.z.string()).nullish(),
1003
+ summary: zod.z.string().nullish(),
1004
+ operationId: zod.z.string(),
1005
+ deprecated: zod.z.boolean().nullish(),
1006
+ responses: zod.z.record(zod.z.object({
1007
+ description: zod.z.string().nullish(),
1008
+ schema: Schema.nullish(),
1009
+ content: zod.z.object({
1010
+ "application/json": zod.z.object({
1011
+ schema: Schema.nullish()
1012
+ })
1013
+ }).nullish()
1014
+ })),
1015
+ parameters: zod.z.array(EndpointParameters).nullish(),
1016
+ requestBody: zod.z.object({
1017
+ required: zod.z.boolean(),
1018
+ content: zod.z.object({
1019
+ "application/json": zod.z.object({
1020
+ schema: Schema.nullish()
1021
+ })
1022
+ }).nullish()
1023
+ }).nullish()
1024
+ });
1025
+ const Operation = zod.z.object({
1026
+ get: Endpoint.nullish(),
1027
+ post: Endpoint.nullish(),
1028
+ patch: Endpoint.nullish(),
1029
+ delete: Endpoint.nullish(),
1030
+ put: Endpoint.nullish()
1031
+ });
1032
+ const Paths = zod.z.record(Operation);
1033
+ zod.z.object({
1034
+ paths: Paths,
1035
+ definitions: Definitions,
1036
+ basePath: zod.z.string(),
1037
+ info: zod.z.object({
1038
+ description: zod.z.string(),
1039
+ title: zod.z.string(),
1040
+ contact: zod.z.object({
1041
+ name: zod.z.string(),
1042
+ url: zod.z.string(),
1043
+ email: zod.z.string()
1044
+ }),
1045
+ version: zod.z.string()
1046
+ }),
1047
+ schemes: zod.z.array(zod.z.string()).nullish(),
1048
+ components: zod.z.object({
1049
+ schemas: Definitions
1050
+ }).nullish()
1051
+ });
1052
+
1053
+ const templateMethod = ({
1054
+ classMethod,
1055
+ description,
1056
+ httpMethod,
1057
+ path,
1058
+ pathParams,
1059
+ bodyParams,
1060
+ queryParams,
1061
+ isFormUrlEncoded,
1062
+ responseClass
1063
+ }) => {
1064
+ let methodParams = "";
1065
+ let methodParamsNoTypes = "";
1066
+ let newPath = `'${path}'`;
1067
+ let importStatements = [];
1068
+ const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
1069
+ for (const pathParam of sortedPathParams) {
1070
+ const type = ParserUtils.parseType(pathParam);
1071
+ if (pathParam.name !== "namespace") {
1072
+ methodParams += pathParam.name + `:${type}, `;
1073
+ methodParamsNoTypes += pathParam.name + ", ";
1074
+ }
1075
+ const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1076
+ if (path.match(`{${pathParam.name}}`)) {
1077
+ if (type === "string") {
1078
+ newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1079
+ } else {
1080
+ newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
1081
+ }
1082
+ }
1083
+ }
1084
+ let dataType = null;
1085
+ if (httpMethod !== "get") {
1086
+ dataType = ParserUtils.parseBodyParamsType(bodyParams);
1087
+ importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
1088
+ methodParams += dataType ? `data: ${dataType},` : "";
1089
+ methodParamsNoTypes += dataType ? `data,` : "";
1090
+ }
1091
+ const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
1092
+ const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
1093
+ const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
1094
+ const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
1095
+ const isDelete = ["delete"].includes(httpMethod);
1096
+ let dataPayload = "{params}";
1097
+ const descriptionText = description ? `
1098
+ /**
1099
+ * ${description.replace(/\n/g, "\n * ")}
1100
+ */` : "";
1101
+ let formPayloadString = "";
1102
+ if (isFormUrlEncoded) {
1103
+ formPayloadString = ``;
1104
+ const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
1105
+ dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
1106
+ } else if (isPostPutPatch) {
1107
+ dataPayload = dataType ? `data, {params}` : "null, {params}";
1108
+ } else if (isDelete) {
1109
+ dataPayload = dataType ? `{data, params}` : "{params}";
1110
+ }
1111
+ const isFileUpload = methodParams.indexOf("data: {file") > -1;
1112
+ const resolvedResponseClass = responseClass || "unknown";
1113
+ const resolvedResponseClassValidated = responseClass || "z.unknown()";
1114
+ methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
1115
+ methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
1116
+ let methodImpl = "";
1117
+ const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
1118
+ const cachedFetchMethod = classMethod;
1119
+ const deprecateTag = isCacheFetch ? `/**
1120
+ * @deprecated Use "${classMethod}()" instead.
1121
+ */` : "";
1122
+ const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
1123
+ const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
1124
+ const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1125
+ const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
1126
+ const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
1127
+ methodImpl = `${descriptionText}
1128
+ ${generateMethodName()} {
1129
+ ${queryParamsDefault}
1130
+ const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1131
+ const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
1132
+
1133
+ ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')
1134
+
1135
+ if (!this.cache) {
1136
+ return SdkCache.withoutCache(res)
1137
+ }
1138
+ 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}')` : ""}
1140
+ }
1141
+ `;
1142
+ if (!isGuardInvoked) {
1143
+ methodImpl = `${descriptionText}
1144
+ ${deprecateTag}
1145
+ TODO_${classMethod}(${methodParams}): Promise<AxiosResponse<${resolvedResponseClass}>> {
1146
+ ${queryParamsDefault}
1147
+ const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1148
+ return this.axiosInstance.${httpMethod}(url, ${dataPayload})
1149
+ }
1150
+ `;
1151
+ }
1152
+ const res = {
1153
+ methodImpl,
1154
+ methodParams,
1155
+ methodParamsNoTypes,
1156
+ importStatements
1157
+ };
1158
+ return res;
1159
+ };
1160
+
1141
1161
  const templateApiMethod = ({
1142
1162
  classMethod,
1143
1163
  description,
@@ -1199,28 +1219,6 @@ const templateApiMethod = ({
1199
1219
  return [methodImpl, snippetSdk, snippetShell];
1200
1220
  };
1201
1221
 
1202
- const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
1203
- let imports = "";
1204
- let returnStatement = "";
1205
- for (const cl of apiList) {
1206
- imports += `
1207
- import { ${cl} } from './${serviceName}/${cl}.js'`;
1208
- returnStatement += `
1209
- ${cl}, `;
1210
- }
1211
- return `/**
1212
- * AUTO GENERATED
1213
- */
1214
- ${imports}
1215
-
1216
- const apis = {
1217
- ${returnStatement}
1218
- }
1219
-
1220
- export const ${ParserUtils.convertDashesToTitleCase(serviceNameTitle)} = apis
1221
- `;
1222
- };
1223
-
1224
1222
  const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1225
1223
  const methodArr = methodSnippet.split("//");
1226
1224
  let normMethod = normalizeMethodSnippet(methodArr[0].trim(), "data:");
@@ -1260,21 +1258,33 @@ const normalizeMethodSnippet = (methodInput, splitWord) => {
1260
1258
  };
1261
1259
 
1262
1260
  const GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
1263
- class CodeGenerator {
1264
- static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
1265
- static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
1266
- static getGeneratedAdminFolder = () => `${CliParser.getOutputPath()}/generated-admin`;
1267
- static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
1261
+ class SwaggerReaderHelpers {
1268
1262
  static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1269
- static iterateApi = async (api, serviceName) => {
1270
- const apiBufferByTag = {};
1271
- const apiArgumentsByTag = {};
1272
- const classBufferByTag = {};
1273
- const dependenciesByTag = {};
1274
- const classImports = {};
1275
- let arrayDefinitions = [];
1276
- const snippetMap = {};
1277
- const mapClassMethods = {};
1263
+ static parseAllEndpoints = async ({
1264
+ api,
1265
+ sdkName,
1266
+ serviceName
1267
+ }) => {
1268
+ const result = {
1269
+ admin: {
1270
+ arrayDefinitions: [],
1271
+ snippetMap: {},
1272
+ tagToClassImportsRecord: {},
1273
+ tagToEndpointClassesRecord: {},
1274
+ tagToSdkClientRecord: {},
1275
+ tagToSdkFunctionNamesRecord: {},
1276
+ tagToSdkImportsRecord: {}
1277
+ },
1278
+ public: {
1279
+ arrayDefinitions: [],
1280
+ snippetMap: {},
1281
+ tagToClassImportsRecord: {},
1282
+ tagToEndpointClassesRecord: {},
1283
+ tagToSdkClientRecord: {},
1284
+ tagToSdkFunctionNamesRecord: {},
1285
+ tagToSdkImportsRecord: {}
1286
+ }
1287
+ };
1278
1288
  const sortedPathsByLength = new Map(Object.entries(api.paths).sort((a, b) => {
1279
1289
  if (a[0].length === b[0].length) {
1280
1290
  return a[0].localeCompare(b[0]);
@@ -1283,50 +1293,57 @@ class CodeGenerator {
1283
1293
  }
1284
1294
  }));
1285
1295
  const sortedKeys = Array.from(sortedPathsByLength.keys());
1286
- const servicePrefix = CodeGenerator.getServicePrefix(sortedKeys);
1287
- for (const [path2, operation] of sortedPathsByLength) {
1288
- const isAdminEndpoint = path2.indexOf("/admin/") > -1;
1289
- if (CliParser.isAdmin() && !isAdminEndpoint) {
1290
- continue;
1291
- } else if (!CliParser.isAdmin() && isAdminEndpoint) {
1292
- continue;
1293
- } else if (path2.indexOf("/healthz") >= 0) {
1296
+ const servicePrefix = SwaggerReaderHelpers.getServicePrefix(sortedKeys);
1297
+ const tagToClassMethodsMap = {
1298
+ admin: {},
1299
+ public: {}
1300
+ };
1301
+ for (const [path, operation] of sortedPathsByLength) {
1302
+ if (path.indexOf("/healthz") >= 0) {
1294
1303
  continue;
1295
1304
  }
1305
+ const isAdminEndpoint = path.indexOf("/admin/") > -1;
1306
+ const picked = isAdminEndpoint ? result.admin : result.public;
1307
+ const {
1308
+ arrayDefinitions,
1309
+ snippetMap,
1310
+ tagToClassImportsRecord,
1311
+ tagToEndpointClassesRecord,
1312
+ tagToSdkClientRecord,
1313
+ tagToSdkFunctionNamesRecord,
1314
+ tagToSdkImportsRecord
1315
+ } = picked;
1316
+ const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
1296
1317
  const httpMethods = Object.keys(operation);
1297
1318
  for (const httpMethod of httpMethods) {
1298
1319
  const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
1299
- console.error(JSON.stringify({ path: path2, httpMethod }, null, 2));
1320
+ console.error(JSON.stringify({ path, httpMethod }, null, 2));
1300
1321
  throw error;
1301
1322
  });
1302
- if (!endpoint.tags) {
1303
- continue;
1304
- }
1305
- if (endpoint.deprecated) {
1323
+ if (!endpoint.tags || endpoint.deprecated)
1306
1324
  continue;
1307
- }
1308
1325
  const [tag] = endpoint.tags;
1309
- const pathWithBase = `${api.basePath ?? ""}${path2}`;
1310
- mapClassMethods[tag] = mapClassMethods[tag] ? mapClassMethods[tag] : {};
1326
+ const pathWithBase = `${api.basePath ?? ""}${path}`;
1327
+ tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
1311
1328
  const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
1312
1329
  const classMethod = ParserUtils.generateNaturalLangMethod({
1313
1330
  servicePrefix,
1314
- path: path2,
1331
+ path,
1315
1332
  httpMethod,
1316
1333
  isForm,
1317
- existingMethods: mapClassMethods[tag]
1334
+ existingMethods: tagToClassMethodsMapByType[tag]
1318
1335
  });
1319
- mapClassMethods[tag][classMethod] = `${path2} ${httpMethod}`;
1320
- snippetMap[pathWithBase] = snippetMap[pathWithBase] ? snippetMap[pathWithBase] : {};
1321
- let description = endpoint.description;
1322
- description = description || "";
1323
- description = description.replace(/\s+/g, " ");
1336
+ tagToClassMethodsMapByType[tag][classMethod] = `${path} ${httpMethod}`;
1337
+ if (!snippetMap[pathWithBase]) {
1338
+ snippetMap[pathWithBase] = {};
1339
+ }
1340
+ const description = endpoint.description?.replace(/\s+/g, " ") || "";
1324
1341
  const responseClass = ParserUtils.get2xxResponse(endpoint.responses);
1325
- const { className, classGenName } = ParserUtils.generateClassName(tag);
1326
- classImports[className] = classImports[className] ? classImports[className] : {};
1342
+ const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
1343
+ tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
1327
1344
  if (responseClass) {
1328
1345
  const importTypeClass = ParserUtils.parseRefType(responseClass);
1329
- classImports[className][importTypeClass] = `import { ${importTypeClass} } from '../definitions/${importTypeClass}.js'`;
1346
+ tagToClassImportsRecord[className][importTypeClass] = `import { ${importTypeClass} } from '../definitions/${importTypeClass}.js'`;
1330
1347
  }
1331
1348
  if (responseClass && responseClass.endsWith("Array")) {
1332
1349
  arrayDefinitions.push(responseClass);
@@ -1355,8 +1372,8 @@ class CodeGenerator {
1355
1372
  isFormUrlEncoded,
1356
1373
  responseClass
1357
1374
  });
1358
- classBufferByTag[tag] = (classBufferByTag[tag] || "") + methodImpl;
1359
- const [generatedMethodString1, snippetMethod, snippetShell] = templateApiMethod({
1375
+ tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1376
+ const [generatedMethodString, snippetMethod, snippetShell] = templateApiMethod({
1360
1377
  classMethod,
1361
1378
  description,
1362
1379
  httpMethod,
@@ -1368,32 +1385,37 @@ class CodeGenerator {
1368
1385
  methodParams,
1369
1386
  methodParamsNoTypes
1370
1387
  });
1371
- apiBufferByTag[tag] = (apiBufferByTag[tag] || "") + generatedMethodString1;
1372
- apiArgumentsByTag[tag] = (apiArgumentsByTag[tag] || "") + classMethod + ",";
1373
- dependenciesByTag[tag] = dependenciesByTag[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...dependenciesByTag[tag]])] : [...new Set(importStatements)];
1388
+ tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1389
+ tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
1390
+ tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1374
1391
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1375
- const { apiGenName } = ParserUtils.generateApiName(tag);
1392
+ const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1376
1393
  const resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1377
- snippetMap[pathWithBase][httpMethod] = {
1378
- web: resultSnippet,
1379
- webGit: GIT_URL + `/sdk-${serviceName}/src/generated-public/${serviceName}/${apiGenName}.ts`,
1380
- shell: snippetShell
1381
- };
1394
+ const currentSnippetMap = {};
1395
+ 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
+ }
1400
+ currentSnippetMap.shell = snippetShell;
1382
1401
  }
1383
1402
  }
1384
- arrayDefinitions = [...new Set(arrayDefinitions)];
1385
- return {
1386
- apiArgumentsByTag,
1387
- apiBufferByTag,
1388
- classBufferByTag,
1389
- dependenciesByTag,
1390
- classImports,
1391
- arrayDefinitions,
1392
- snippetMap
1393
- };
1403
+ for (const key in result) {
1404
+ result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
1405
+ }
1406
+ return result;
1394
1407
  };
1408
+ }
1409
+
1410
+ class CodeGenerator {
1411
+ static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
1412
+ static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
1413
+ static getGeneratedAdminFolder = () => `${CliParser.getOutputPath()}/generated-admin`;
1414
+ static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
1415
+ static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1395
1416
  static main = async (nameArray) => {
1396
1417
  const serviceName = nameArray[0];
1418
+ const sdkName = nameArray[1];
1397
1419
  const swaggerFile = nameArray[2];
1398
1420
  const parser = new SwaggerParser();
1399
1421
  const generatedFolder = CliParser.isAdmin() ? CodeGenerator.getGeneratedAdminFolder() : CodeGenerator.getGeneratedPublicFolder();
@@ -1409,26 +1431,38 @@ class CodeGenerator {
1409
1431
  ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
1410
1432
  ParserUtils.mkdirIfNotExist(DIST_ENDPOINTS_DIR);
1411
1433
  ParserUtils.syncPackageVersion(apiInfo, CliParser.skipVersionSync(), process.env.PRERELEASE_ID);
1412
- const { apiArgumentsByTag, apiBufferByTag, classBufferByTag, dependenciesByTag, classImports, arrayDefinitions, snippetMap } = await CodeGenerator.iterateApi(api, serviceName);
1434
+ const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
1435
+ const parsedInformationByType = CliParser.isAdmin() ? parsedInformation.admin : parsedInformation.public;
1436
+ const {
1437
+ arrayDefinitions,
1438
+ tagToClassImportsRecord,
1439
+ tagToEndpointClassesRecord,
1440
+ tagToSdkClientRecord,
1441
+ tagToSdkFunctionNamesRecord,
1442
+ tagToSdkImportsRecord
1443
+ } = parsedInformationByType;
1413
1444
  if (CliParser.getSnippetOutputPath()) {
1414
1445
  try {
1415
- ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify(snippetMap, null, 2));
1446
+ ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify({
1447
+ ...parsedInformation.public.snippetMap,
1448
+ ...parsedInformation.admin.snippetMap
1449
+ }, null, 2));
1416
1450
  } catch (err) {
1417
1451
  console.log("Generating snippets", err);
1418
1452
  }
1419
1453
  }
1420
1454
  const targetSrcFolder = `${CliParser.getOutputPath()}/`;
1421
1455
  const apiList = [];
1422
- for (const tag in classBufferByTag) {
1423
- const { className, classGenName } = ParserUtils.generateClassName(tag);
1424
- const classBuffer = classBufferByTag[tag];
1425
- const imports = [.../* @__PURE__ */ new Set([...dependenciesByTag[tag], ...Object.values(classImports[className])])];
1426
- const apiImports = [.../* @__PURE__ */ new Set([...dependenciesByTag[tag], ...Object.values(classImports[className])])];
1456
+ for (const tag in tagToEndpointClassesRecord) {
1457
+ const { className, classGenName } = ParserUtils.generateClassName(tag, CliParser.isAdmin());
1458
+ const classBuffer = tagToEndpointClassesRecord[tag];
1459
+ const imports = [.../* @__PURE__ */ new Set([...tagToSdkImportsRecord[tag], ...Object.values(tagToClassImportsRecord[className])])];
1460
+ const apiImports = [.../* @__PURE__ */ new Set([...tagToSdkImportsRecord[tag], ...Object.values(tagToClassImportsRecord[className])])];
1427
1461
  apiImports.push(`import { ${classGenName} } from './endpoints/${classGenName}.js'`);
1428
1462
  ParserUtils.writeClassFile(DIST_ENDPOINTS_DIR, classGenName, classBuffer, imports);
1429
- const apiBuffer = apiBufferByTag[tag];
1430
- const { apiGenName } = ParserUtils.generateApiName(tag);
1431
- ParserUtils.writeApiFile(DIST_DIR, apiGenName, apiBuffer, apiImports, apiArgumentsByTag[tag]);
1463
+ const apiBuffer = tagToSdkClientRecord[tag];
1464
+ const { apiGenName } = ParserUtils.generateApiName(tag, CliParser.isAdmin());
1465
+ ParserUtils.writeApiFile(DIST_DIR, apiGenName, apiBuffer, apiImports, tagToSdkFunctionNamesRecord[tag]);
1432
1466
  apiList.push(apiGenName);
1433
1467
  indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_ENDPOINTS_DIR, `${classGenName}`), targetSrcFolder));
1434
1468
  indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR, `${apiGenName}`), targetSrcFolder));