@povio/openapi-codegen-cli 2.0.8-rc.3 → 2.0.8-rc.31

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.
Files changed (193) hide show
  1. package/README.md +70 -0
  2. package/dist/acl.d.mts +59 -0
  3. package/dist/acl.mjs +73 -7
  4. package/dist/auth.context-Bu5KW2sI.mjs +59 -0
  5. package/dist/config-KffSntOs.d.mts +6 -0
  6. package/dist/error-handling-CXeVTk1T.d.mts +38 -0
  7. package/dist/error-handling-DkPY7Asf.mjs +187 -0
  8. package/dist/generate.runner-CXsHkwM7.mjs +87 -0
  9. package/dist/generateCodeFromOpenAPIDoc-DkNqNy-S.mjs +4627 -0
  10. package/dist/generator.d.mts +65 -0
  11. package/dist/generator.mjs +144 -0
  12. package/dist/index.d.mts +230 -0
  13. package/dist/index.mjs +251 -24
  14. package/dist/options-D9TC-n26.d.mts +94 -0
  15. package/dist/sh.d.mts +1 -0
  16. package/dist/sh.mjs +448 -0
  17. package/dist/vite.d.mts +11 -0
  18. package/dist/vite.mjs +51 -0
  19. package/dist/zod.d.mts +20 -0
  20. package/dist/zod.mjs +33 -0
  21. package/package.json +54 -47
  22. package/dist/acl.d.ts +0 -4
  23. package/dist/assets/useCrossTabQueryInvalidation.mjs +0 -23
  24. package/dist/assets/useMutationEffects.mjs +0 -56
  25. package/dist/commands/check.command.d.ts +0 -2
  26. package/dist/commands/check.d.ts +0 -7
  27. package/dist/commands/generate.command.d.ts +0 -2
  28. package/dist/commands/generate.d.ts +0 -8
  29. package/dist/generator.d.ts +0 -3
  30. package/dist/generator.js +0 -77
  31. package/dist/generators/checkOpenAPIDoc.d.ts +0 -3
  32. package/dist/generators/const/acl.const.d.ts +0 -13
  33. package/dist/generators/const/buildConfigs.const.d.ts +0 -1
  34. package/dist/generators/const/deps.const.d.ts +0 -38
  35. package/dist/generators/const/endpoints.const.d.ts +0 -11
  36. package/dist/generators/const/js.const.d.ts +0 -1
  37. package/dist/generators/const/openapi.const.d.ts +0 -7
  38. package/dist/generators/const/options.const.d.ts +0 -2
  39. package/dist/generators/const/package.const.d.ts +0 -2
  40. package/dist/generators/const/queries.const.d.ts +0 -8
  41. package/dist/generators/const/validation.const.d.ts +0 -53
  42. package/dist/generators/const/zod.const.d.ts +0 -19
  43. package/dist/generators/core/SchemaResolver.class.d.ts +0 -71
  44. package/dist/generators/core/endpoints/getEndpointAcl.d.ts +0 -8
  45. package/dist/generators/core/endpoints/getEndpointBody.d.ts +0 -13
  46. package/dist/generators/core/endpoints/getEndpointParameter.d.ts +0 -11
  47. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.d.ts +0 -3
  48. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.test.d.ts +0 -1
  49. package/dist/generators/core/getDataFromOpenAPIDoc.d.ts +0 -8
  50. package/dist/generators/core/getMetadataFromOpenAPIDoc.d.ts +0 -4
  51. package/dist/generators/core/getMetadataFromOpenAPIDoc.test.d.ts +0 -1
  52. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.d.ts +0 -2
  53. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.test.d.ts +0 -1
  54. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.d.ts +0 -6
  55. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.test.d.ts +0 -1
  56. package/dist/generators/core/openapi/getSchemaRefObjs.d.ts +0 -4
  57. package/dist/generators/core/openapi/iterateSchema.d.ts +0 -22
  58. package/dist/generators/core/resolveConfig.d.ts +0 -7
  59. package/dist/generators/core/zod/ZodSchema.class.d.ts +0 -26
  60. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.d.ts +0 -2
  61. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.d.ts +0 -2
  62. package/dist/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.d.ts +0 -17
  63. package/dist/generators/core/zod/getZodChain.d.ts +0 -8
  64. package/dist/generators/core/zod/getZodSchema.d.ts +0 -17
  65. package/dist/generators/core/zod/getZodSchema.test.d.ts +0 -1
  66. package/dist/generators/core/zod/getZodSchemaRefs.d.ts +0 -6
  67. package/dist/generators/core/zod/getZodSchemasFromOpenAPIDoc.d.ts +0 -6
  68. package/dist/generators/core/zod/resolveZodSchemaName.d.ts +0 -10
  69. package/dist/generators/core/zod/sortZodSchemasByTopology.d.ts +0 -4
  70. package/dist/generators/generate/generateAcl.d.ts +0 -3
  71. package/dist/generators/generate/generateAclCheck.d.ts +0 -2
  72. package/dist/generators/generate/generateAppRestClient.d.ts +0 -2
  73. package/dist/generators/generate/generateConfigs.d.ts +0 -2
  74. package/dist/generators/generate/generateEndpoints.d.ts +0 -2
  75. package/dist/generators/generate/generateModels.d.ts +0 -2
  76. package/dist/generators/generate/generateQueries.d.ts +0 -2
  77. package/dist/generators/generate/generateQueryModules.d.ts +0 -2
  78. package/dist/generators/generate/generateZodExtended.d.ts +0 -2
  79. package/dist/generators/generateCodeFromOpenAPIDoc.d.ts +0 -4
  80. package/dist/generators/types/builder-config.d.ts +0 -48
  81. package/dist/generators/types/common.d.ts +0 -27
  82. package/dist/generators/types/config.d.ts +0 -2
  83. package/dist/generators/types/endpoint.d.ts +0 -50
  84. package/dist/generators/types/generate.d.ts +0 -39
  85. package/dist/generators/types/metadata.d.ts +0 -51
  86. package/dist/generators/types/openapi.d.ts +0 -22
  87. package/dist/generators/types/options.d.ts +0 -66
  88. package/dist/generators/types/validation.d.ts +0 -5
  89. package/dist/generators/utils/array.utils.d.ts +0 -1
  90. package/dist/generators/utils/endpoint.utils.d.ts +0 -12
  91. package/dist/generators/utils/endpoint.utils.test.d.ts +0 -1
  92. package/dist/generators/utils/file.utils.d.ts +0 -8
  93. package/dist/generators/utils/generate/generate.acl.utils.d.ts +0 -23
  94. package/dist/generators/utils/generate/generate.configs.utils.d.ts +0 -15
  95. package/dist/generators/utils/generate/generate.endpoints.utils.d.ts +0 -39
  96. package/dist/generators/utils/generate/generate.imports.utils.d.ts +0 -39
  97. package/dist/generators/utils/generate/generate.imports.utils.test.d.ts +0 -1
  98. package/dist/generators/utils/generate/generate.openapi.utils.d.ts +0 -2
  99. package/dist/generators/utils/generate/generate.query.utils.d.ts +0 -6
  100. package/dist/generators/utils/generate/generate.utils.d.ts +0 -18
  101. package/dist/generators/utils/generate/generate.zod.utils.d.ts +0 -13
  102. package/dist/generators/utils/generate-files.utils.d.ts +0 -6
  103. package/dist/generators/utils/hbs/hbs-template.utils.d.ts +0 -3
  104. package/dist/generators/utils/hbs/hbs.acl.utils.d.ts +0 -2
  105. package/dist/generators/utils/hbs/hbs.common.utils.d.ts +0 -1
  106. package/dist/generators/utils/hbs/hbs.endpoints.utils.d.ts +0 -2
  107. package/dist/generators/utils/hbs/hbs.imports.utils.d.ts +0 -1
  108. package/dist/generators/utils/hbs/hbs.partials.utils.d.ts +0 -2
  109. package/dist/generators/utils/hbs/hbs.query.utils.d.ts +0 -2
  110. package/dist/generators/utils/hbs/hbs.zod.utils.d.ts +0 -2
  111. package/dist/generators/utils/js.utils.d.ts +0 -2
  112. package/dist/generators/utils/js.utils.test.d.ts +0 -1
  113. package/dist/generators/utils/math.utils.d.ts +0 -1
  114. package/dist/generators/utils/namespace.utils.d.ts +0 -7
  115. package/dist/generators/utils/object.utils.d.ts +0 -13
  116. package/dist/generators/utils/object.utils.test.d.ts +0 -1
  117. package/dist/generators/utils/openapi-schema.utils.d.ts +0 -15
  118. package/dist/generators/utils/openapi.utils.d.ts +0 -23
  119. package/dist/generators/utils/openapi.utils.test.d.ts +0 -1
  120. package/dist/generators/utils/operation.utils.d.ts +0 -22
  121. package/dist/generators/utils/operation.utils.test.d.ts +0 -1
  122. package/dist/generators/utils/query.utils.d.ts +0 -7
  123. package/dist/generators/utils/sort.utils.d.ts +0 -7
  124. package/dist/generators/utils/string.utils.d.ts +0 -14
  125. package/dist/generators/utils/string.utils.test.d.ts +0 -1
  126. package/dist/generators/utils/tag.utils.d.ts +0 -7
  127. package/dist/generators/utils/ts.utils.d.ts +0 -16
  128. package/dist/generators/utils/validation.utils.d.ts +0 -17
  129. package/dist/generators/utils/zod-schema.utils.d.ts +0 -15
  130. package/dist/helpers/cli.helper.d.ts +0 -22
  131. package/dist/helpers/config.helper.d.ts +0 -3
  132. package/dist/helpers/version.helper.d.ts +0 -4
  133. package/dist/helpers/yargs.helper.d.ts +0 -10
  134. package/dist/index.d.ts +0 -16
  135. package/dist/lib/acl/AclGuard.d.ts +0 -8
  136. package/dist/lib/acl/AclGuard.mjs +0 -14
  137. package/dist/lib/acl/Can.d.ts +0 -9
  138. package/dist/lib/acl/Can.mjs +0 -11
  139. package/dist/lib/acl/ability.context.d.ts +0 -15
  140. package/dist/lib/acl/ability.context.mjs +0 -37
  141. package/dist/lib/acl/appAbility.types.d.ts +0 -3
  142. package/dist/lib/assets/locales/en/translation.json.mjs +0 -8
  143. package/dist/lib/assets/locales/sl/translation.json.mjs +0 -8
  144. package/dist/lib/auth/AuthGuard.d.ts +0 -6
  145. package/dist/lib/auth/AuthGuard.mjs +0 -26
  146. package/dist/lib/auth/auth.context.d.ts +0 -22
  147. package/dist/lib/auth/auth.context.mjs +0 -41
  148. package/dist/lib/config/i18n.d.ts +0 -32
  149. package/dist/lib/config/i18n.mjs +0 -31
  150. package/dist/lib/config/queryConfig.context.d.ts +0 -17
  151. package/dist/lib/config/queryConfig.context.mjs +0 -26
  152. package/dist/lib/config/router.context.d.ts +0 -9
  153. package/dist/lib/config/router.context.mjs +0 -20
  154. package/dist/lib/react-query.types.d.ts +0 -10
  155. package/dist/lib/rest/error-handling.d.ts +0 -30
  156. package/dist/lib/rest/error-handling.mjs +0 -132
  157. package/dist/lib/rest/rest-client.d.ts +0 -22
  158. package/dist/lib/rest/rest-client.mjs +0 -62
  159. package/dist/lib/rest/rest-client.types.d.ts +0 -23
  160. package/dist/lib/rest/rest-interceptor.d.ts +0 -8
  161. package/dist/lib/rest/rest-interceptor.mjs +0 -21
  162. package/dist/lib/rest/rest.utils.d.ts +0 -7
  163. package/dist/lib/rest/rest.utils.mjs +0 -51
  164. package/dist/sh.d.ts +0 -2
  165. package/dist/sh.js +0 -634
  166. package/src/assets/useCrossTabQueryInvalidation.ts +0 -40
  167. package/src/assets/useMutationEffects.ts +0 -89
  168. package/src/generators/templates/acl-check.hbs +0 -29
  169. package/src/generators/templates/acl.hbs +0 -19
  170. package/src/generators/templates/app-acl.hbs +0 -17
  171. package/src/generators/templates/app-rest-client.hbs +0 -7
  172. package/src/generators/templates/configs.hbs +0 -80
  173. package/src/generators/templates/endpoints.hbs +0 -44
  174. package/src/generators/templates/models.hbs +0 -23
  175. package/src/generators/templates/partials/acl-check-call.hbs +0 -1
  176. package/src/generators/templates/partials/casl-ability-function.hbs +0 -12
  177. package/src/generators/templates/partials/casl-ability-query.hbs +0 -1
  178. package/src/generators/templates/partials/casl-ability-type.hbs +0 -1
  179. package/src/generators/templates/partials/columns-config.hbs +0 -11
  180. package/src/generators/templates/partials/endpoint-config.hbs +0 -31
  181. package/src/generators/templates/partials/endpoint-param-parse.hbs +0 -1
  182. package/src/generators/templates/partials/endpoint-params.hbs +0 -1
  183. package/src/generators/templates/partials/import.hbs +0 -1
  184. package/src/generators/templates/partials/inputs-config.hbs +0 -10
  185. package/src/generators/templates/partials/model-js-docs.hbs +0 -6
  186. package/src/generators/templates/partials/query-js-docs.hbs +0 -31
  187. package/src/generators/templates/partials/query-keys.hbs +0 -11
  188. package/src/generators/templates/partials/query-use-infinite-query.hbs +0 -21
  189. package/src/generators/templates/partials/query-use-mutation.hbs +0 -54
  190. package/src/generators/templates/partials/query-use-query.hbs +0 -16
  191. package/src/generators/templates/queries.hbs +0 -54
  192. package/src/generators/templates/query-modules.hbs +0 -9
  193. package/src/generators/templates/zod-extended.hbs +0 -49
@@ -0,0 +1,4627 @@
1
+ import fs from "fs";
2
+ import { match } from "ts-pattern";
3
+ import { OpenAPIV3 } from "openapi-types";
4
+ import path from "path";
5
+
6
+ //#region src/generators/const/validation.const.ts
7
+ const HTTP_STATUS_CODES = {
8
+ "100": "Continue",
9
+ "101": "Switching Protocols",
10
+ "102": "Processing",
11
+ "103": "Early Hints",
12
+ "200": "OK",
13
+ "201": "Created",
14
+ "202": "Accepted",
15
+ "203": "Non-Authoritative Information",
16
+ "204": "No Content",
17
+ "205": "Reset Content",
18
+ "206": "Partial Content",
19
+ "300": "Ambiguous",
20
+ "301": "Moved Permanently",
21
+ "302": "Found",
22
+ "303": "See Other",
23
+ "304": "Not Modified",
24
+ "307": "Temporary Redirect",
25
+ "308": "Permanent Redirect",
26
+ "400": "Bad Request",
27
+ "401": "Unauthorized",
28
+ "402": "Payment Required",
29
+ "403": "Forbidden",
30
+ "404": "Not Found",
31
+ "405": "Method Not Allowed",
32
+ "406": "Not Acceptable",
33
+ "407": "Proxy Authentication Required",
34
+ "408": "Request Timeout",
35
+ "409": "Conflict",
36
+ "410": "Gone",
37
+ "411": "Length Required",
38
+ "412": "Precondition Failed",
39
+ "413": "Payload Too Large",
40
+ "414": "URI Too Long",
41
+ "415": "Unsupported Media Type",
42
+ "416": "Requested Range Not Satisfiable",
43
+ "417": "Expectation Failed",
44
+ "418": "I Am a Teapot",
45
+ "421": "Misdirected Request",
46
+ "422": "Unprocessable Entity",
47
+ "424": "Failed Dependency",
48
+ "428": "Precondition Required",
49
+ "429": "Too Many Requests",
50
+ "500": "Internal Server Error",
51
+ "501": "Not Implemented",
52
+ "502": "Bad Gateway",
53
+ "503": "Service Unavailable",
54
+ "504": "Gateway Timeout",
55
+ "505": "HTTP Version Not Supported"
56
+ };
57
+ const VALIDATION_ERROR_TYPE_TITLE = {
58
+ "invalid-schema": "Invalid OpenAPI Schemas",
59
+ "invalid-operation-id": "Invalid Operation IDs",
60
+ "missing-path-parameter": "Missing Path Parameters",
61
+ "not-allowed-inline-enum": "Not Allowed Inline Enums",
62
+ "not-allowed-circular-schema": "Not Allowed Circular Schemas",
63
+ "missing-acl-condition-property": "Missing x-acl Condition Properties",
64
+ "missing-status-code": "Missing HTTP Status Codes",
65
+ "invalid-status-code": "Invalid HTTP Status Codes",
66
+ "multiple-success-status-codes": "Multiple Success HTTP Status Codes"
67
+ };
68
+
69
+ //#endregion
70
+ //#region src/helpers/profile.helper.ts
71
+ function nowMs() {
72
+ return Number(process.hrtime.bigint()) / 1e6;
73
+ }
74
+ var Profiler = class {
75
+ entries = /* @__PURE__ */ new Map();
76
+ constructor(enabled) {
77
+ this.enabled = enabled;
78
+ }
79
+ add(label, elapsedMs) {
80
+ if (!this.enabled) return;
81
+ const prev = this.entries.get(label);
82
+ if (prev) {
83
+ prev.totalMs += elapsedMs;
84
+ prev.count += 1;
85
+ return;
86
+ }
87
+ this.entries.set(label, {
88
+ totalMs: elapsedMs,
89
+ count: 1
90
+ });
91
+ }
92
+ runSync(label, fn) {
93
+ if (!this.enabled) return fn();
94
+ const startMs = nowMs();
95
+ try {
96
+ return fn();
97
+ } finally {
98
+ this.add(label, nowMs() - startMs);
99
+ }
100
+ }
101
+ async runAsync(label, fn) {
102
+ if (!this.enabled) return await fn();
103
+ const startMs = nowMs();
104
+ try {
105
+ return await fn();
106
+ } finally {
107
+ this.add(label, nowMs() - startMs);
108
+ }
109
+ }
110
+ formatLines() {
111
+ if (!this.enabled) return [];
112
+ return Array.from(this.entries.entries()).sort((a, b) => b[1].totalMs - a[1].totalMs).map(([label, entry]) => {
113
+ const avgMs = entry.totalMs / entry.count;
114
+ return `${label}: ${entry.totalMs.toFixed(1)}ms (count: ${entry.count}, avg: ${avgMs.toFixed(2)}ms)`;
115
+ });
116
+ }
117
+ };
118
+
119
+ //#endregion
120
+ //#region src/generators/utils/string.utils.ts
121
+ const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
122
+ const decapitalize = (str) => str.charAt(0).toLowerCase() + str.slice(1);
123
+ const kebabToCamel = (str) => str.replace(/(-\w)/g, (group) => group[1].toUpperCase());
124
+ const snakeToCamel = (str) => str.replace(/(_\w)/g, (group) => group[1].toUpperCase());
125
+ const nonWordCharactersToCamel = (str) => str.replace(/[\W_]+(\w)?/g, (_, char) => char?.toUpperCase() ?? "");
126
+ const suffixIfNeeded = (text, suffix = "") => text.endsWith(suffix) ? text : `${text}${suffix}`;
127
+ const removeSuffix = (text, suffix) => text.replace(new RegExp(`${suffix}$`), "");
128
+ const getLongestMostCommon = (strs) => {
129
+ const counter = strs.reduce((acc, str) => ({
130
+ ...acc,
131
+ [str]: (acc[str] ?? 0) + 1
132
+ }), {});
133
+ return Object.entries(counter).toSorted((a, b) => {
134
+ if (a[1] === b[1]) return b[0].length - a[0].length;
135
+ return b[1] - a[1];
136
+ })[0]?.[0];
137
+ };
138
+ const getMostCommonAdjacentCombinationSplit = (strs) => {
139
+ return getLongestMostCommon(strs.flatMap((str) => getAdjacentStringCombinations(splitByUppercase(capitalize(str)))));
140
+ };
141
+ const splitByUppercase = (str) => {
142
+ return str.split(/(?<![A-Z])(?=[A-Z])/).filter(Boolean);
143
+ };
144
+ const camelToSpaceSeparated = (text) => splitByUppercase(text).join(" ");
145
+ const getAdjacentStringCombinations = (strs, ignoreStrs = [
146
+ "dto",
147
+ "by",
148
+ "for",
149
+ "of",
150
+ "in",
151
+ "to",
152
+ "and",
153
+ "with"
154
+ ]) => {
155
+ const combinations = [];
156
+ for (let i = 0; i < strs.length; i++) {
157
+ if (ignoreStrs.includes(strs[i].toLowerCase())) continue;
158
+ for (let j = i + 1; j <= strs.length; j++) {
159
+ if (ignoreStrs.includes(strs[j - 1]?.toLowerCase())) continue;
160
+ combinations.push(strs.slice(i, j).join(""));
161
+ }
162
+ }
163
+ return combinations;
164
+ };
165
+ const removeWord = (source, wordToRemove) => {
166
+ const singularWordToRemove = wordToRemove.replace(/es$|s$/g, "");
167
+ const pattern = new RegExp(`(${decapitalize(singularWordToRemove)}|${capitalize(singularWordToRemove)})[a-z]*(?=$|[A-Z])`, "g");
168
+ return source.replace(pattern, "");
169
+ };
170
+
171
+ //#endregion
172
+ //#region src/generators/utils/tag.utils.ts
173
+ function formatTag(tag) {
174
+ return nonWordCharactersToCamel(tag);
175
+ }
176
+ function getOperationTag(operation, options) {
177
+ const tag = operation.tags?.[0];
178
+ return formatTag(tag ?? options.defaultTag);
179
+ }
180
+ function getEndpointTag(endpoint, options) {
181
+ return formatTag((options.splitByTags ? endpoint.tags?.[0] : options.defaultTag) ?? options.defaultTag);
182
+ }
183
+ function isTagIncluded(tag, options) {
184
+ const normalizedTag = formatTag(tag).toLowerCase();
185
+ if (options.includeTags.some((includeTag) => formatTag(includeTag).toLowerCase() === normalizedTag)) return true;
186
+ if (options.excludeTags.some((excludeTag) => formatTag(excludeTag).toLowerCase() === normalizedTag)) return false;
187
+ return options.includeTags.length === 0;
188
+ }
189
+ function shouldInlineEndpointsForTag(tag, options) {
190
+ if (!options.inlineEndpoints) return false;
191
+ return !(options.inlineEndpointsExcludeModules ?? []).some((moduleName) => formatTag(moduleName).toLowerCase() === tag.toLowerCase());
192
+ }
193
+
194
+ //#endregion
195
+ //#region src/generators/const/endpoints.const.ts
196
+ const JSON_APPLICATION_FORMAT = "application/json";
197
+ const DEFAULT_HEADERS = {
198
+ "Content-Type": JSON_APPLICATION_FORMAT,
199
+ Accept: JSON_APPLICATION_FORMAT
200
+ };
201
+ const BODY_PARAMETER_NAME = "data";
202
+ const AXIOS_DEFAULT_IMPORT_NAME = "axios";
203
+ const AXIOS_REQUEST_CONFIG_NAME = "config";
204
+ const AXIOS_REQUEST_CONFIG_TYPE = "AxiosRequestConfig";
205
+ const AXIOS_IMPORT = {
206
+ defaultImport: AXIOS_DEFAULT_IMPORT_NAME,
207
+ bindings: [],
208
+ typeBindings: [AXIOS_REQUEST_CONFIG_TYPE],
209
+ from: "axios"
210
+ };
211
+
212
+ //#endregion
213
+ //#region src/generators/const/zod.const.ts
214
+ const SCHEMA_SUFFIX = "Schema";
215
+ const ENUM_SUFFIX = "Enum";
216
+ const BODY_SCHEMA_SUFFIX = "Body";
217
+ const PARAM_SCHEMA_SUFFIX = "Param";
218
+ const RESPONSE_SCHEMA_SUFFIX = "Response";
219
+ const ERROR_RESPONSE_SCHEMA_SUFFIX = "ErrorResponse";
220
+ const VOID_SCHEMA = "z.void()";
221
+ const ANY_SCHEMA = "z.any()";
222
+ const BLOB_SCHEMA = "z.instanceof(Blob)";
223
+ const ENUM_SCHEMA = "z.enum";
224
+ const INT_SCHEMA = "z.int()";
225
+ const NUMBER_SCHEMA = "z.number()";
226
+ const STRING_SCHEMA = "z.string()";
227
+ const EMAIL_SCHEMA = "z.email()";
228
+ const URL_SCHEMA = "z.url()";
229
+ const UUID_SCHEMA = "z.uuid()";
230
+ const DATETIME_SCHEMA = "z.iso.datetime({ offset: true })";
231
+ const ZOD_IMPORT = {
232
+ bindings: ["z"],
233
+ from: "zod"
234
+ };
235
+
236
+ //#endregion
237
+ //#region src/generators/utils/js.utils.ts
238
+ const isValidPropertyName = (str) => /^(?:[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+)$/.test(str);
239
+ const invalidVariableNameCharactersToCamel = (str) => str.replace(/^[^a-zA-Z_$]*/g, "").replace(/[^a-zA-Z0-9_$]+(\w)?/g, (_, char) => char?.toUpperCase() ?? "");
240
+
241
+ //#endregion
242
+ //#region src/generators/utils/openapi-schema.utils.ts
243
+ function isReferenceObject(obj) {
244
+ return obj != null && Object.prototype.hasOwnProperty.call(obj, "$ref");
245
+ }
246
+ function isSchemaObject(schema) {
247
+ return !isReferenceObject(schema);
248
+ }
249
+ function isArraySchemaObject(schema) {
250
+ return schema.type === "array";
251
+ }
252
+ function inferRequiredSchema(schema) {
253
+ if (!schema.allOf) throw new Error("Function inferRequiredSchema is specialized to handle item with required only in an allOf array.");
254
+ const [standaloneRequisites, noRequiredOnlyAllof] = schema.allOf.reduce((acc, cur) => {
255
+ if (isBrokenAllOfItem(cur)) {
256
+ const required = cur.required;
257
+ acc[0].push(...required ?? []);
258
+ } else acc[1].push(cur);
259
+ return acc;
260
+ }, [[], []]);
261
+ const composedRequiredSchema = {
262
+ properties: standaloneRequisites.reduce((acc, cur) => {
263
+ acc[cur] = {};
264
+ return acc;
265
+ }, {}),
266
+ type: "object",
267
+ required: standaloneRequisites
268
+ };
269
+ return {
270
+ noRequiredOnlyAllof,
271
+ composedRequiredSchema,
272
+ patchRequiredSchemaInLoop: (prop, getSchemaByRef) => {
273
+ if (isReferenceObject(prop)) {
274
+ const refType = getSchemaByRef(prop.$ref);
275
+ if (refType) composedRequiredSchema.required.forEach((required) => {
276
+ composedRequiredSchema.properties[required] = refType?.properties?.[required] ?? {};
277
+ });
278
+ } else {
279
+ const properties = prop["properties"] ?? {};
280
+ composedRequiredSchema.required.forEach((required) => {
281
+ if (properties[required]) composedRequiredSchema.properties[required] = properties[required] ?? {};
282
+ });
283
+ }
284
+ }
285
+ };
286
+ }
287
+ const isBrokenAllOfItem = (item) => {
288
+ return !isReferenceObject(item) && !!item.required && !item.type && !item.properties && !item?.allOf && !item?.anyOf && !item.oneOf;
289
+ };
290
+
291
+ //#endregion
292
+ //#region src/generators/const/openapi.const.ts
293
+ const COMPLEXITY_THRESHOLD = 2;
294
+ const ALLOWED_PARAM_MEDIA_TYPES = [
295
+ "application/octet-stream",
296
+ "multipart/form-data",
297
+ "application/x-www-form-urlencoded",
298
+ "*/*"
299
+ ];
300
+ const ALLOWED_PATH_IN = [
301
+ "query",
302
+ "header",
303
+ "path"
304
+ ];
305
+ const ALLOWED_METHODS = [
306
+ OpenAPIV3.HttpMethods.GET,
307
+ OpenAPIV3.HttpMethods.PUT,
308
+ OpenAPIV3.HttpMethods.POST,
309
+ OpenAPIV3.HttpMethods.DELETE,
310
+ OpenAPIV3.HttpMethods.OPTIONS,
311
+ OpenAPIV3.HttpMethods.HEAD,
312
+ OpenAPIV3.HttpMethods.PATCH,
313
+ OpenAPIV3.HttpMethods.TRACE
314
+ ];
315
+ const PRIMITIVE_TYPE_LIST = [
316
+ "string",
317
+ "number",
318
+ "integer",
319
+ "boolean"
320
+ ];
321
+ const COMPOSITE_KEYWORDS = [
322
+ "allOf",
323
+ "anyOf",
324
+ "oneOf"
325
+ ];
326
+
327
+ //#endregion
328
+ //#region src/generators/utils/openapi.utils.ts
329
+ const getSchemaRef = (schemaName) => `#/components/schemas/${schemaName}`;
330
+ const autocorrectRef = (ref) => ref[1] === "/" ? ref : "#/" + ref.slice(1);
331
+ const getSchemaNameByRef = (ref) => autocorrectRef(ref).split("/").at(-1);
332
+ function normalizeString(text) {
333
+ return snakeToCamel(prefixStringStartingWithNumberIfNeeded(text).normalize("NFKD").trim().replace(/\s+/g, "_").replace(/--+/g, "-").replace(/-+/g, "_").replace(/[^\w-]+/g, "_"));
334
+ }
335
+ function wrapWithQuotesIfNeeded(str) {
336
+ if (/^[a-zA-Z]\w*$/.test(str)) return str;
337
+ return `"${str}"`;
338
+ }
339
+ function unwrapQuotesIfNeeded(value) {
340
+ if (typeof value === "string" && value.startsWith("\"") && value.endsWith("\"")) return value.slice(1, -1);
341
+ return value;
342
+ }
343
+ function prefixStringStartingWithNumberIfNeeded(str) {
344
+ const firstAsNumber = Number(str[0]);
345
+ if (typeof firstAsNumber === "number" && !Number.isNaN(firstAsNumber)) return "_" + str;
346
+ return str;
347
+ }
348
+ function pathParamToVariableName(name) {
349
+ return snakeToCamel(name.replaceAll("_", "#").replaceAll("-", "_")).replaceAll("#", "_");
350
+ }
351
+ const isPrimitiveType = (type) => PRIMITIVE_TYPE_LIST.includes(type);
352
+ function escapeControlCharacters(str) {
353
+ return str.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/([\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF])/g, (_m, p1) => {
354
+ const dec = p1.codePointAt();
355
+ const hex = dec.toString(16);
356
+ if (dec <= 255) return `\\x${`00${hex}`.slice(-2)}`;
357
+ return `\\u${`0000${hex}`.slice(-4)}`;
358
+ }).replace(/\//g, "\\/");
359
+ }
360
+ function isParamMediaTypeAllowed(mediaType) {
361
+ return mediaType.includes("application/") && mediaType.includes("json") || ALLOWED_PARAM_MEDIA_TYPES.includes(mediaType) || mediaType.includes("text/");
362
+ }
363
+ function isMainResponseStatus(status) {
364
+ return status >= 200 && status < 300;
365
+ }
366
+ function isErrorStatus(status) {
367
+ return !(status >= 200 && status < 300);
368
+ }
369
+ function isMediaTypeAllowed(mediaType) {
370
+ return mediaType.startsWith("application/");
371
+ }
372
+ const PATH_PARAM_WITH_BRACKETS_REGEX = /({\w+})/g;
373
+ const WORD_PRECEDED_BY_NON_WORD_CHARACTER = /[^\w\-]+/g;
374
+ /** @example turns `/media-objects/{id}` into `MediaObjectsById` */
375
+ function pathToVariableName(path) {
376
+ path = capitalize(kebabToCamel(path.replaceAll("/", "-")).replaceAll("-", ""));
377
+ const pathParams = [...path.matchAll(PATH_PARAM_WITH_BRACKETS_REGEX)];
378
+ if (pathParams.length > 0) {
379
+ const lastPathParam = pathParams.toSorted((a, b) => a.index - b.index)[pathParams.length - 1][0];
380
+ path = `${path.replace(PATH_PARAM_WITH_BRACKETS_REGEX, "")}By${capitalize(lastPathParam.slice(1, -1))}`;
381
+ }
382
+ return path.replace(WORD_PRECEDED_BY_NON_WORD_CHARACTER, "_");
383
+ }
384
+ const MATCHER_REGEX = /{(\b\w+(?:-\w+)*\b)}/g;
385
+ function replaceHyphenatedPath(path) {
386
+ const matches = path.match(MATCHER_REGEX);
387
+ if (matches === null) return path.replaceAll(MATCHER_REGEX, ":$1");
388
+ matches.forEach((match) => {
389
+ const replacement = pathParamToVariableName(match.replaceAll(MATCHER_REGEX, ":$1"));
390
+ path = path.replaceAll(match, replacement);
391
+ });
392
+ return path;
393
+ }
394
+ const isSortingParameterObject = (param) => {
395
+ const enumNames = param["x-enumNames"];
396
+ const hasEnumNames = Array.isArray(enumNames) && enumNames.length > 0;
397
+ const isStringSchema = !!param.schema && isSchemaObject(param.schema) && param.schema.type === "string";
398
+ return hasEnumNames && isStringSchema;
399
+ };
400
+ const isPathExcluded = (path, options) => {
401
+ if (!options.excludePathRegex) return false;
402
+ return new RegExp(options.excludePathRegex).test(path);
403
+ };
404
+
405
+ //#endregion
406
+ //#region src/generators/utils/validation.utils.ts
407
+ function getInvalidSchemaError(message) {
408
+ return {
409
+ type: "invalid-schema",
410
+ message
411
+ };
412
+ }
413
+ function getInvalidOperationIdError(operationId) {
414
+ return {
415
+ type: "invalid-operation-id",
416
+ message: `Operation ${operationId}`
417
+ };
418
+ }
419
+ function getMissingPathParameterError(params, path) {
420
+ return {
421
+ type: "missing-path-parameter",
422
+ message: `Path ${path} is missing [${params.map(({ name }) => name).join(", ")}]`
423
+ };
424
+ }
425
+ function getNotAllowedInlineEnumError(enumProperty) {
426
+ return {
427
+ type: "not-allowed-inline-enum",
428
+ message: `${enumProperty} is missing @IsEnum() and @ApiProperty(enum:, enumName:)`
429
+ };
430
+ }
431
+ function getMissingAclConditionPropertyError(propertyName, operation, endpoint) {
432
+ return {
433
+ type: "missing-acl-condition-property",
434
+ message: `Condition property ${propertyName} is not found in parameters or body in operation ${getOperationDescriptor(operation, endpoint)}`
435
+ };
436
+ }
437
+ function getMissingStatusCodeError(statusCode, operation, endpoint) {
438
+ return {
439
+ type: "missing-status-code",
440
+ message: `Missing HTTP status code ${getStatusCodeDescription(statusCode)} in operation ${getOperationDescriptor(operation, endpoint)}`
441
+ };
442
+ }
443
+ function getInvalidStatusCodeError(statusCode, operation, endpoint) {
444
+ return {
445
+ type: "invalid-status-code",
446
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} expected HTTP status code ${getStatusCodeDescription(statusCode.expected)} but received ${getStatusCodeDescription(statusCode.received)}`
447
+ };
448
+ }
449
+ function getMultipleSuccessStatusCodesError(statusCodes, operation, endpoint) {
450
+ return {
451
+ type: "multiple-success-status-codes",
452
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} has multiple success HTTP status codes: ${statusCodes.map(getStatusCodeDescription).join(", ")}`
453
+ };
454
+ }
455
+ function getOperationDescriptor(operation, endpoint) {
456
+ return operation.operationId ?? `${endpoint.method} ${endpoint.path}`;
457
+ }
458
+ function getStatusCodeDescription(statusCode) {
459
+ return `${statusCode} (${HTTP_STATUS_CODES[statusCode]})`;
460
+ }
461
+ function groupByType(validationErrors) {
462
+ return validationErrors.reduce((acc, err) => ({
463
+ ...acc,
464
+ [err.type]: [...acc[err.type] ?? [], err.message]
465
+ }), {});
466
+ }
467
+
468
+ //#endregion
469
+ //#region src/generators/const/package.const.ts
470
+ const PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli";
471
+ const ACL_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/acl";
472
+ const ZOD_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/zod";
473
+
474
+ //#endregion
475
+ //#region src/generators/const/deps.const.ts
476
+ const APP_REST_CLIENT_NAME = "AppRestClient";
477
+ const APP_REST_CLIENT_FILE = {
478
+ fileName: "app-rest-client",
479
+ extension: "ts"
480
+ };
481
+ const QUERY_OPTIONS_TYPES = {
482
+ query: "AppQueryOptions",
483
+ infiniteQuery: "AppInfiniteQueryOptions",
484
+ mutation: "AppMutationOptions"
485
+ };
486
+ const TEMPLATE_DATA_FILE_PATH = "src/data";
487
+ const ERROR_HANDLERS = {
488
+ ErrorHandler: "ErrorHandler",
489
+ SharedErrorHandler: "SharedErrorHandler"
490
+ };
491
+ const ERROR_HANDLING_IMPORT = {
492
+ bindings: [ERROR_HANDLERS.ErrorHandler, ERROR_HANDLERS.SharedErrorHandler],
493
+ from: PACKAGE_IMPORT_PATH
494
+ };
495
+ const BUILDERS_UTILS = {
496
+ dynamicInputs: "dynamicInputs",
497
+ dynamicColumns: "dynamicColumns"
498
+ };
499
+ const QUERY_MODULE_ENUM = "QueryModule";
500
+ const QUERY_MODULES_FILE = {
501
+ fileName: "queryModules",
502
+ extension: "ts"
503
+ };
504
+ const MUTATION_EFFECTS = {
505
+ optionsType: "MutationEffectsOptions",
506
+ hookName: "useMutationEffects",
507
+ runFunctionName: "runMutationEffects"
508
+ };
509
+ const ZOD_EXTENDED = {
510
+ namespace: "ZodExtended",
511
+ exports: {
512
+ parse: "parse",
513
+ sortExp: "sortExp"
514
+ }
515
+ };
516
+
517
+ //#endregion
518
+ //#region src/generators/utils/zod-schema.utils.ts
519
+ const getZodSchemaName = (name, schemaSuffix) => suffixIfNeeded(capitalize(normalizeString(name)), schemaSuffix);
520
+ const getEnumZodSchemaName = (name, enumSuffix, schemaSuffix) => suffixIfNeeded(capitalize(normalizeString(name)), `${enumSuffix}${schemaSuffix}`);
521
+ const isNamedZodSchema = (schema) => ["z.", `${ZOD_EXTENDED.namespace}.`].every((searchString) => !schema.startsWith(searchString));
522
+ const isEnumZodSchema = (schema) => schema.startsWith(ENUM_SCHEMA);
523
+ const getZodSchemaOperationName = (operationName, isUniqueOperationName, tag) => isUniqueOperationName ? operationName : `${tag}_${operationName}`;
524
+ const getBodyZodSchemaName = (operationName) => snakeToCamel(`${operationName}_${BODY_SCHEMA_SUFFIX}`);
525
+ const getParamZodSchemaName = (operationName, paramName) => snakeToCamel(`${operationName}_${paramName}${PARAM_SCHEMA_SUFFIX}`);
526
+ const getMainResponseZodSchemaName = (operationName) => snakeToCamel(`${operationName}${RESPONSE_SCHEMA_SUFFIX}`);
527
+ const getErrorResponseZodSchemaName = (operationName, statusCode) => snakeToCamel(`${operationName}_${statusCode}_${ERROR_RESPONSE_SCHEMA_SUFFIX}`);
528
+ function getResponseZodSchemaName({ statusCode, operationName, isUniqueOperationName, tag }) {
529
+ const status = Number(statusCode);
530
+ const zodSchemaOperationName = getZodSchemaOperationName(operationName, isUniqueOperationName, tag);
531
+ if (!isMainResponseStatus(status) && statusCode !== "default" && isErrorStatus(status)) return getErrorResponseZodSchemaName(zodSchemaOperationName, statusCode);
532
+ return getMainResponseZodSchemaName(zodSchemaOperationName);
533
+ }
534
+
535
+ //#endregion
536
+ //#region src/generators/utils/endpoint.utils.ts
537
+ const isGetEndpoint = (endpoint) => endpoint.method === OpenAPIV3.HttpMethods.GET;
538
+ const isPaginatedGetEndpoint = (endpoint, options) => isGetEndpoint(endpoint) && Object.values(options.infiniteQueryParamNames).every((infiniteQueryParam) => endpoint.parameters.some((param) => param.name === infiniteQueryParam && param.type === "Query"));
539
+ const isReadAllEndpoint = (endpoint, options) => endpoint.method === OpenAPIV3.HttpMethods.GET && !isPathSegmentParam(endpoint.pathSegments.at(-1)) && isPaginatedGetEndpoint(endpoint, options);
540
+ const isReadEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.GET && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
541
+ const isCreateEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.POST && hasMatchingPathWithoutTrailingParam(endpoint, readAllEndpoint);
542
+ const isUpdateEndpoint = (endpoint, readAllEndpoint) => [OpenAPIV3.HttpMethods.PUT, OpenAPIV3.HttpMethods.PATCH].includes(endpoint.method) && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
543
+ const isDeleteEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.DELETE && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
544
+ const isBulkDeleteEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.DELETE && hasMatchingPathWithoutTrailingParam(endpoint, readAllEndpoint);
545
+ const getPathSegments = (path) => path.split("/").filter(Boolean);
546
+ const isPathSegmentParam = (pathSegment) => pathSegment?.startsWith(":");
547
+ const hasMatchingPath = (endpoint, readAllEndpoint) => readAllEndpoint.pathSegments.every((segment, index) => isPathSegmentParam(segment) && isPathSegmentParam(endpoint.pathSegments[index]) || segment === endpoint.pathSegments[index]);
548
+ const hasMatchingPathWithoutTrailingParam = (endpoint, readAllEndpoint) => endpoint.pathSegments.length === readAllEndpoint.pathSegments.length && hasMatchingPath(endpoint, readAllEndpoint);
549
+ const hasMatchingPathWithTrailingParam = (endpoint, readAllEndpoint) => endpoint.pathSegments.length - 1 === readAllEndpoint.pathSegments.length && isPathSegmentParam(endpoint.pathSegments.at(-1)) && hasMatchingPath(endpoint, readAllEndpoint);
550
+
551
+ //#endregion
552
+ //#region src/generators/types/generate.ts
553
+ let GenerateType = /* @__PURE__ */ function(GenerateType) {
554
+ GenerateType["Models"] = "models";
555
+ GenerateType["Endpoints"] = "endpoints";
556
+ GenerateType["Queries"] = "queries";
557
+ GenerateType["Acl"] = "acl";
558
+ GenerateType["Configs"] = "configs";
559
+ return GenerateType;
560
+ }({});
561
+
562
+ //#endregion
563
+ //#region src/generators/utils/namespace.utils.ts
564
+ const getNamespaceName = ({ type, tag, options }) => `${capitalize(tag)}${options.configs[type].namespaceSuffix}`;
565
+
566
+ //#endregion
567
+ //#region src/generators/const/acl.const.ts
568
+ const ACL_APP_ABILITY_FILE = {
569
+ fileName: "acl/app.ability",
570
+ extension: "ts"
571
+ };
572
+ const ACL_APP_ABILITIES = "AppAbilities";
573
+ const ACL_CHECK_HOOK = "useAclCheck";
574
+ const CASL_ABILITY_BINDING = {
575
+ abilityTuple: "AbilityTuple",
576
+ pureAbility: "PureAbility",
577
+ forcedSubject: "ForcedSubject",
578
+ subjectType: "Subject",
579
+ subject: "subject"
580
+ };
581
+ const CASL_ABILITY_IMPORT = {
582
+ bindings: [
583
+ CASL_ABILITY_BINDING.abilityTuple,
584
+ CASL_ABILITY_BINDING.pureAbility,
585
+ CASL_ABILITY_BINDING.forcedSubject,
586
+ CASL_ABILITY_BINDING.subjectType,
587
+ CASL_ABILITY_BINDING.subject
588
+ ],
589
+ from: "@casl/ability"
590
+ };
591
+
592
+ //#endregion
593
+ //#region src/generators/const/options.const.ts
594
+ const DEFAULT_GENERATE_OPTIONS = {
595
+ input: "http://localhost:4000/docs-json/",
596
+ output: "output",
597
+ clearOutput: false,
598
+ incremental: true,
599
+ splitByTags: true,
600
+ defaultTag: "Common",
601
+ includeTags: [],
602
+ excludeTags: [],
603
+ excludePathRegex: "",
604
+ excludeRedundantZodSchemas: true,
605
+ tsNamespaces: true,
606
+ tsPath: "@/data",
607
+ importPath: "ts",
608
+ configs: {
609
+ [GenerateType.Models]: {
610
+ outputFileNameSuffix: "models",
611
+ namespaceSuffix: "Models"
612
+ },
613
+ [GenerateType.Endpoints]: {
614
+ outputFileNameSuffix: "api",
615
+ namespaceSuffix: "Api"
616
+ },
617
+ [GenerateType.Queries]: {
618
+ outputFileNameSuffix: "queries",
619
+ namespaceSuffix: "Queries"
620
+ },
621
+ [GenerateType.Acl]: {
622
+ outputFileNameSuffix: "acl",
623
+ namespaceSuffix: "Acl"
624
+ },
625
+ [GenerateType.Configs]: {
626
+ outputFileNameSuffix: "configs",
627
+ namespaceSuffix: "Configs"
628
+ }
629
+ },
630
+ baseUrl: "",
631
+ modelsOnly: false,
632
+ standalone: false,
633
+ schemaSuffix: SCHEMA_SUFFIX,
634
+ enumSuffix: ENUM_SUFFIX,
635
+ modelsInCommon: false,
636
+ withDefaultValues: true,
637
+ extractEnums: true,
638
+ replaceOptionalWithNullish: false,
639
+ restClientImportPath: "",
640
+ errorHandlingImportPath: "",
641
+ removeOperationPrefixEndingWith: "Controller_",
642
+ parseRequestParams: true,
643
+ inlineEndpoints: false,
644
+ inlineEndpointsExcludeModules: [],
645
+ queryTypesImportPath: PACKAGE_IMPORT_PATH,
646
+ axiosRequestConfig: false,
647
+ mutationEffects: true,
648
+ workspaceContext: false,
649
+ prefetchQueries: true,
650
+ infiniteQueries: false,
651
+ infiniteQueryParamNames: { page: "page" },
652
+ infiniteQueryResponseParamNames: {
653
+ page: "page",
654
+ totalItems: "totalItems",
655
+ limit: "limit"
656
+ },
657
+ acl: true,
658
+ checkAcl: true,
659
+ abilityContextGenericAppAbilities: false,
660
+ abilityContextImportPath: "",
661
+ builderConfigs: false,
662
+ filterParamName: "filter",
663
+ dataResponseParamNames: ["data", "items"],
664
+ dynamicInputsImportPath: "@povio/ui",
665
+ dynamicColumnsImportPath: "@povio/ui"
666
+ };
667
+
668
+ //#endregion
669
+ //#region src/generators/utils/array.utils.ts
670
+ const getUniqueArray = (...arrs) => [...new Set(arrs.flat())];
671
+
672
+ //#endregion
673
+ //#region src/generators/utils/generate/generate.acl.utils.ts
674
+ const getAbilityFunctionName = (endpoint) => `canUse${capitalize(snakeToCamel(endpoint.operationName))}`;
675
+ const getImportedAbilityFunctionName = (endpoint, options) => {
676
+ return `${options.tsNamespaces ? `${getNamespaceName({
677
+ type: GenerateType.Acl,
678
+ tag: getEndpointTag(endpoint, options),
679
+ options
680
+ })}.` : ""}${getAbilityFunctionName(endpoint)}`;
681
+ };
682
+ const getAbilityAction = (endpoint) => endpoint.acl?.[0].action;
683
+ const getAbilitySubject = (endpoint) => endpoint.acl?.[0].subject;
684
+ const hasAbilityConditions = (endpoint) => !!getAbilityConditionsTypes(endpoint)?.length;
685
+ const getAbilityConditionsTypes = (endpoint) => endpoint.acl?.[0].conditionsTypes?.sort((a, b) => a.name.localeCompare(b.name));
686
+ const getAbilityDescription = (endpoint) => endpoint.acl?.[0]?.description;
687
+ const getAbilitySubjectTypes = (endpoint) => {
688
+ const abilitySubject = getAbilitySubject(endpoint);
689
+ const types = [`"${abilitySubject ?? ""}"`];
690
+ if (hasAbilityConditions(endpoint)) types.push(`ForcedSubject<"${abilitySubject}"> & { ${getAbilityConditionsTypes(endpoint)?.map((conditionType) => `${conditionType.name}${conditionType.required ? "" : "?"}: ${conditionType.type ?? ""}${conditionType.zodSchemaName ?? ""},`).join(" ")} }`);
691
+ return types;
692
+ };
693
+ function getAclData({ resolver, data, tag }) {
694
+ const endpoints = data.get(tag)?.endpoints.filter(({ acl }) => acl && acl.length > 0);
695
+ if (!endpoints || endpoints.length === 0) return;
696
+ return {
697
+ endpoints,
698
+ hasAdditionalAbilityImports: endpoints.some(({ acl }) => acl?.[0].conditions && Object.keys(acl[0].conditions).length > 0),
699
+ modelsImports: getModelsImports({
700
+ resolver,
701
+ tag,
702
+ zodSchemasAsTypes: getUniqueArray(endpoints.reduce((acc, endpoint) => {
703
+ const zodSchemas = endpoint.acl?.[0].conditionsTypes?.reduce((acc, propertyType) => [...acc, ...propertyType?.zodSchemaName ? [propertyType.zodSchemaName] : []], []);
704
+ return [...acc, ...zodSchemas ?? []];
705
+ }, []))
706
+ })
707
+ };
708
+ }
709
+ const getAppAbilitiesType = ({ resolver, data }) => {
710
+ const appAbilitiesTypeMap = /* @__PURE__ */ new Map();
711
+ const modelsImportsArr = [];
712
+ let hasAdditionalAbilityImports = false;
713
+ data.forEach((_, tag) => {
714
+ const aclData = getAclData({
715
+ resolver,
716
+ data,
717
+ tag
718
+ });
719
+ if (!aclData) return;
720
+ const { modelsImports: tagModelsImports, hasAdditionalAbilityImports: tagHasAdditionalAbilityImports, endpoints } = aclData;
721
+ modelsImportsArr.push(tagModelsImports);
722
+ hasAdditionalAbilityImports = hasAdditionalAbilityImports || tagHasAdditionalAbilityImports;
723
+ endpoints.forEach((endpoint) => {
724
+ const abilityAction = getAbilityAction(endpoint);
725
+ if (abilityAction) appAbilitiesTypeMap.set(abilityAction, new Set([...appAbilitiesTypeMap.get(abilityAction) ?? [], ...getAbilitySubjectTypes(endpoint)]));
726
+ });
727
+ });
728
+ const modelsImports = mergeImports(resolver.options, ...modelsImportsArr);
729
+ return {
730
+ appAbilitiesType: appAbilitiesTypeMap.size > 0 ? Object.fromEntries(Array.from(appAbilitiesTypeMap.entries()).map(([key, valueSet]) => [key, Array.from(valueSet)])) : void 0,
731
+ modelsImports,
732
+ hasAdditionalAbilityImports
733
+ };
734
+ };
735
+
736
+ //#endregion
737
+ //#region src/generators/utils/generate/generate.query.utils.ts
738
+ const getQueryName = (endpoint, mutation) => {
739
+ const addMutationSuffix = isQuery(endpoint) && isMutation(endpoint) && mutation;
740
+ return `use${capitalize(snakeToCamel(endpoint.operationName))}${addMutationSuffix ? "Mutation" : ""}`;
741
+ };
742
+ const getInfiniteQueryName = (endpoint) => `use${capitalize(snakeToCamel(endpoint.operationName))}Infinite`;
743
+ const getQueryOptionsName = (endpoint) => `${snakeToCamel(endpoint.operationName)}QueryOptions`;
744
+ const getInfiniteQueryOptionsName = (endpoint) => `${snakeToCamel(endpoint.operationName)}InfiniteQueryOptions`;
745
+ const getPrefetchQueryName = (endpoint) => `prefetch${capitalize(snakeToCamel(endpoint.operationName))}`;
746
+ const getPrefetchInfiniteQueryName = (endpoint) => `prefetch${capitalize(snakeToCamel(endpoint.operationName))}Infinite`;
747
+ const getImportedQueryName = (endpoint, options) => {
748
+ return `${options.tsNamespaces ? `${getNamespaceName({
749
+ type: GenerateType.Queries,
750
+ tag: getEndpointTag(endpoint, options),
751
+ options
752
+ })}.` : ""}${getQueryName(endpoint)}`;
753
+ };
754
+ const getImportedInfiniteQueryName = (endpoint, options) => {
755
+ return `${options.tsNamespaces ? `${getNamespaceName({
756
+ type: GenerateType.Queries,
757
+ tag: getEndpointTag(endpoint, options),
758
+ options
759
+ })}.` : ""}${getInfiniteQueryName(endpoint)}`;
760
+ };
761
+
762
+ //#endregion
763
+ //#region src/generators/core/openapi/iterateSchema.ts
764
+ function iterateSchema(schema, options) {
765
+ if (!schema) return;
766
+ const { data, onSchema } = options;
767
+ if (isReferenceObject(schema) && onSchema({
768
+ type: "reference",
769
+ schema,
770
+ data
771
+ }) === true) return;
772
+ const schemaObj = schema;
773
+ if (COMPOSITE_KEYWORDS.some((prop) => prop in schemaObj && schemaObj[prop])) {
774
+ const schemaObjs = schemaObj.allOf ?? schemaObj.anyOf ?? schemaObj.oneOf ?? [];
775
+ for (const compositeObj of schemaObjs) {
776
+ if (onSchema?.({
777
+ type: "composite",
778
+ parentSchema: schema,
779
+ schema: compositeObj,
780
+ data
781
+ }) === true) continue;
782
+ iterateSchema(compositeObj, {
783
+ data,
784
+ onSchema
785
+ });
786
+ }
787
+ }
788
+ if (schemaObj.properties) for (const [propertyName, propertyObj] of Object.entries(schemaObj.properties)) {
789
+ if (onSchema({
790
+ type: "property",
791
+ parentSchema: schema,
792
+ schema: propertyObj,
793
+ data,
794
+ propertyName
795
+ }) === true) continue;
796
+ iterateSchema(propertyObj, options);
797
+ }
798
+ if (schemaObj.additionalProperties && typeof schemaObj.additionalProperties === "object") {
799
+ if (onSchema({
800
+ type: "additionalProperties",
801
+ parentSchema: schema,
802
+ schema: schemaObj.additionalProperties,
803
+ data
804
+ }) === true) return;
805
+ iterateSchema(schemaObj.additionalProperties, options);
806
+ }
807
+ if (schemaObj.type === "array") {
808
+ const arrayObj = schema.items;
809
+ if (onSchema({
810
+ type: "array",
811
+ parentSchema: schema,
812
+ schema: arrayObj,
813
+ data
814
+ }) === true) return;
815
+ iterateSchema(arrayObj, options);
816
+ }
817
+ }
818
+
819
+ //#endregion
820
+ //#region src/generators/utils/generate/generate.openapi.utils.ts
821
+ const schemaDescriptionsCache = /* @__PURE__ */ new WeakMap();
822
+ function getSchemaDescriptions(schemaObj) {
823
+ const cachedSchemaDescriptions = schemaDescriptionsCache.get(schemaObj);
824
+ if (cachedSchemaDescriptions) return cachedSchemaDescriptions;
825
+ const schemaDescriptions = [
826
+ "minimum",
827
+ "exclusiveMinimum",
828
+ "maximum",
829
+ "exclusiveMaximum",
830
+ "minItems",
831
+ "minLength",
832
+ "minProperties",
833
+ "maxItems",
834
+ "maxLength",
835
+ "maxProperties",
836
+ "default",
837
+ "example"
838
+ ].filter((key) => schemaObj[key] !== void 0).reduce((acc, key) => [...acc, `${capitalize(camelToSpaceSeparated(key))}: \`${schemaObj[key]}\``], []);
839
+ schemaDescriptionsCache.set(schemaObj, schemaDescriptions);
840
+ return schemaDescriptions;
841
+ }
842
+
843
+ //#endregion
844
+ //#region src/generators/utils/generate/generate.zod.utils.ts
845
+ const getZodSchemaInferedTypeName = (zodSchemaName, options) => removeSuffix(zodSchemaName, options.schemaSuffix);
846
+ const getImportedZodSchemaName = (resolver, zodSchemaName, namespaceTag) => {
847
+ if (!isNamedZodSchema(zodSchemaName)) return zodSchemaName;
848
+ const tag = namespaceTag ?? resolver.getTagByZodSchemaName(zodSchemaName);
849
+ return `${resolver.options.tsNamespaces ? `${getNamespaceName({
850
+ type: GenerateType.Models,
851
+ tag,
852
+ options: resolver.options
853
+ })}.` : ""}${zodSchemaName}`;
854
+ };
855
+ const getImportedZodSchemaInferedTypeName = (resolver, zodSchemaName, currentTag, namespaceTag) => {
856
+ if (!isNamedZodSchema(zodSchemaName)) return zodSchemaName === VOID_SCHEMA ? "void" : zodSchemaName;
857
+ const tag = namespaceTag ?? resolver.getTagByZodSchemaName(zodSchemaName);
858
+ return `${resolver.options.tsNamespaces && (Boolean(namespaceTag) || tag !== currentTag) ? `${getNamespaceName({
859
+ type: GenerateType.Models,
860
+ tag,
861
+ options: resolver.options
862
+ })}.` : ""}${getZodSchemaInferedTypeName(zodSchemaName, resolver.options)}`;
863
+ };
864
+ function getZodSchemaType(data) {
865
+ return data.isEnum ? "enum" : data.schemaObj?.type ?? "object";
866
+ }
867
+ function getZodSchemaDescription(data) {
868
+ if (!data.schemaObj) return;
869
+ return [data.schemaObj.description, ...getSchemaDescriptions(data.schemaObj)].filter(Boolean).join(". ");
870
+ }
871
+ function getType(resolver, schemaObj, tag) {
872
+ if (isReferenceObject(schemaObj)) {
873
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schemaObj.$ref);
874
+ return zodSchemaName ? getImportedZodSchemaInferedTypeName(resolver, zodSchemaName, tag) : void 0;
875
+ }
876
+ if (isArraySchemaObject(schemaObj)) {
877
+ if (!isReferenceObject(schemaObj.items)) return `${schemaObj.items?.type ?? "unknown"}[]`;
878
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schemaObj.items.$ref);
879
+ return zodSchemaName ? `${getImportedZodSchemaInferedTypeName(resolver, zodSchemaName, tag)}[]` : void 0;
880
+ }
881
+ if (COMPOSITE_KEYWORDS.some((prop) => prop in schemaObj && schemaObj[prop])) {
882
+ const schemaObjs = schemaObj.allOf ?? schemaObj.anyOf ?? schemaObj.oneOf ?? [];
883
+ if (schemaObjs.length > 0) return getType(resolver, schemaObjs[0], tag);
884
+ }
885
+ return schemaObj.type;
886
+ }
887
+ function getZodSchemaPropertyDescriptions(resolver, data, tag) {
888
+ if (!data.schemaObj) return [];
889
+ const ARRAY_INDEX = "[0]";
890
+ const ADDITIONAL_PROPERTIES_KEY = "[key]";
891
+ const properties = {};
892
+ const onSchema = (schemaData) => {
893
+ if (schemaData.type === "reference") return true;
894
+ if (schemaData.type === "composite") return;
895
+ const segments = [...schemaData.data?.pathSegments ?? []];
896
+ if (schemaData.type === "array") segments.push(ARRAY_INDEX);
897
+ else if (schemaData.type === "property") segments.push(schemaData.propertyName);
898
+ else if (schemaData.type === "additionalProperties") segments.push(ADDITIONAL_PROPERTIES_KEY);
899
+ if (schemaData.schema && segments[segments.length - 1] !== ARRAY_INDEX) {
900
+ const resolvedSchema = resolver.resolveObject(schemaData.schema);
901
+ const schemaDescriptions = [resolvedSchema?.description, ...getSchemaDescriptions(resolvedSchema)].filter(Boolean);
902
+ const propertyKey = segments.join(".");
903
+ if (!(properties[propertyKey] && "type" in schemaData.schema && schemaData.schema.type === "object")) {
904
+ delete properties[propertyKey];
905
+ properties[propertyKey] = {
906
+ type: getType(resolver, schemaData.schema, tag) ?? "unknown",
907
+ description: schemaDescriptions.join(". ")
908
+ };
909
+ }
910
+ }
911
+ iterateSchema(schemaData.schema, {
912
+ data: { pathSegments: [...segments] },
913
+ onSchema
914
+ });
915
+ return true;
916
+ };
917
+ if ("allOf" in data.schemaObj && data.schemaObj.allOf) data.schemaObj.allOf.forEach((schemaObj) => {
918
+ if (isReferenceObject(schemaObj)) iterateSchema(resolver.resolveObject(schemaObj), {
919
+ data: { pathSegments: [] },
920
+ onSchema
921
+ });
922
+ });
923
+ iterateSchema(data.schemaObj, {
924
+ data: { pathSegments: [] },
925
+ onSchema
926
+ });
927
+ return properties;
928
+ }
929
+
930
+ //#endregion
931
+ //#region src/generators/utils/generate/generate.imports.utils.ts
932
+ function getModelsImports({ resolver, tag, zodSchemas = [], zodSchemasAsTypes = [] }) {
933
+ const type = GenerateType.Models;
934
+ const getTag = (zodSchemaName) => resolver.getTagByZodSchemaName(zodSchemaName);
935
+ const zodSchemaImports = getImports({
936
+ type,
937
+ tag,
938
+ entities: zodSchemas,
939
+ getTag,
940
+ getEntityName: (zodSchema) => zodSchema,
941
+ options: resolver.options
942
+ });
943
+ const zodSchemaTypeImports = getImports({
944
+ type,
945
+ tag,
946
+ entities: zodSchemasAsTypes,
947
+ getTag,
948
+ getEntityName: (zodSchema) => getZodSchemaInferedTypeName(zodSchema, resolver.options),
949
+ options: resolver.options
950
+ }).map((importData) => ({
951
+ ...importData,
952
+ ...resolver.options.tsNamespaces ? {} : { typeOnly: true }
953
+ }));
954
+ return mergeImports(resolver.options, zodSchemaImports, zodSchemaTypeImports);
955
+ }
956
+ function getEndpointsImports({ tag, endpoints, options }) {
957
+ return getImports({
958
+ type: GenerateType.Endpoints,
959
+ tag,
960
+ entities: endpoints,
961
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
962
+ getEntityName: getEndpointName,
963
+ options
964
+ });
965
+ }
966
+ function getQueriesImports({ tag, endpoints, options }) {
967
+ return getImports({
968
+ type: GenerateType.Queries,
969
+ tag,
970
+ entities: endpoints,
971
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
972
+ getEntityName: getQueryName,
973
+ options
974
+ });
975
+ }
976
+ function getInfiniteQueriesImports({ tag, endpoints, options }) {
977
+ return getImports({
978
+ type: GenerateType.Queries,
979
+ tag,
980
+ entities: endpoints,
981
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
982
+ getEntityName: getInfiniteQueryName,
983
+ options
984
+ });
985
+ }
986
+ function getAclImports({ tag, endpoints, options }) {
987
+ return getImports({
988
+ type: GenerateType.Acl,
989
+ tag,
990
+ entities: endpoints,
991
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
992
+ getEntityName: getAbilityFunctionName,
993
+ options
994
+ });
995
+ }
996
+ function getImportPath(options, fromRoot = false) {
997
+ let importPath = options.tsPath;
998
+ if (options.importPath === "relative") importPath = fromRoot ? "./" : "../";
999
+ else if (options.importPath === "absolute") importPath = options.output;
1000
+ else if (new RegExp(`${TEMPLATE_DATA_FILE_PATH}`, "g").test(options.output)) importPath = options.output.replace(new RegExp(`.*${TEMPLATE_DATA_FILE_PATH}`, "g"), options.tsPath);
1001
+ return `${importPath}/`.replace(/\/\//g, "/");
1002
+ }
1003
+ function getImports({ type = GenerateType.Models, tag: currentTag, entities, getTag, getEntityName, options }) {
1004
+ const imports = /* @__PURE__ */ new Map();
1005
+ entities.forEach((entity) => {
1006
+ const tag = type === GenerateType.Models && options.modelsInCommon && options.splitByTags ? currentTag : getTag(entity);
1007
+ if (!imports.has(tag)) {
1008
+ const sameTagDir = currentTag === tag;
1009
+ imports.set(tag, {
1010
+ bindings: [options.tsNamespaces ? getNamespaceName({
1011
+ type,
1012
+ tag,
1013
+ options
1014
+ }) : getEntityName(entity)],
1015
+ from: `${sameTagDir ? "./" : getImportPath(options)}${getTagImportPath({
1016
+ type,
1017
+ tag,
1018
+ includeTagDir: !sameTagDir,
1019
+ options
1020
+ })}`
1021
+ });
1022
+ } else if (!options.tsNamespaces) imports.get(tag).bindings.push(getEntityName(entity));
1023
+ });
1024
+ return Array.from(imports.values());
1025
+ }
1026
+ function mergeImports(options, ...importArrs) {
1027
+ const merged = /* @__PURE__ */ new Map();
1028
+ importArrs.forEach((imports) => {
1029
+ imports.forEach((importItem) => {
1030
+ if (!merged.has(importItem.from)) merged.set(importItem.from, {
1031
+ ...importItem,
1032
+ bindings: importItem.typeOnly ? [] : [...importItem.bindings],
1033
+ typeBindings: [...importItem.typeBindings ?? [], ...importItem.typeOnly ? importItem.bindings : []]
1034
+ });
1035
+ else {
1036
+ const existing = merged.get(importItem.from);
1037
+ if (!options.tsNamespaces && !importItem.typeOnly) existing.bindings.push(...importItem.bindings);
1038
+ existing.typeBindings = [
1039
+ ...existing.typeBindings ?? [],
1040
+ ...importItem.typeBindings ?? [],
1041
+ ...importItem.typeOnly ? importItem.bindings : []
1042
+ ];
1043
+ existing.typeOnly = false;
1044
+ }
1045
+ });
1046
+ });
1047
+ return Array.from(merged.values()).map((importItem) => ({
1048
+ ...importItem,
1049
+ bindings: getUniqueArray(importItem.bindings),
1050
+ typeBindings: getUniqueArray(importItem.typeBindings ?? []).filter((binding) => !importItem.bindings.includes(binding)),
1051
+ typeOnly: Boolean(importItem.typeOnly && importItem.bindings.length === 0 && (importItem.typeBindings?.length ?? 0) > 0)
1052
+ }));
1053
+ }
1054
+
1055
+ //#endregion
1056
+ //#region src/generators/utils/generate/generate.utils.ts
1057
+ function getFileNameWithExtension({ fileName, extension }) {
1058
+ return `${fileName}.${extension}`;
1059
+ }
1060
+ function getTagFileNameWithoutExtension({ type, tag, options, includeTagDir = true }) {
1061
+ const outputFileNameSuffix = options.configs[type].outputFileNameSuffix;
1062
+ if (!tag) return outputFileNameSuffix;
1063
+ return `${includeTagDir ? `${decapitalize(tag)}/` : ""}${decapitalize(tag)}.${outputFileNameSuffix}`;
1064
+ }
1065
+ function getTagImportPath(...args) {
1066
+ return getTagFileNameWithoutExtension(...args);
1067
+ }
1068
+ function getTagFileName(...args) {
1069
+ return `${getTagFileNameWithoutExtension(...args)}.ts`;
1070
+ }
1071
+ function getAppRestClientImportPath(options) {
1072
+ if (options.restClientImportPath === DEFAULT_GENERATE_OPTIONS.restClientImportPath) return `${getImportPath(options)}${APP_REST_CLIENT_FILE.fileName}`;
1073
+ return options.restClientImportPath;
1074
+ }
1075
+ function getQueryModulesImportPath(options) {
1076
+ return `${getImportPath(options)}${QUERY_MODULES_FILE.fileName}`;
1077
+ }
1078
+ function getQueryTypesImportPath(options) {
1079
+ return options.queryTypesImportPath;
1080
+ }
1081
+
1082
+ //#endregion
1083
+ //#region src/generators/utils/ts.utils.ts
1084
+ function primitiveTypeToTsType(type) {
1085
+ return match(type).with("string", () => "string").with("number", () => "number").with("integer", () => "number").with("boolean", () => "boolean").exhaustive();
1086
+ }
1087
+ function getTsTypeBase({ zodSchemaName, schema, resolver }) {
1088
+ let type = "void";
1089
+ let tag;
1090
+ if (zodSchemaName && isNamedZodSchema(zodSchemaName)) {
1091
+ type = getImportedZodSchemaInferedTypeName(resolver, zodSchemaName);
1092
+ tag = resolver.getTagByZodSchemaName(zodSchemaName);
1093
+ } else if (schema?.type && isPrimitiveType(schema?.type)) type = primitiveTypeToTsType(schema?.type);
1094
+ const splitType = type.split(".");
1095
+ return {
1096
+ type: splitType[splitType.length - 1],
1097
+ ...splitType.length > 1 ? { namespace: splitType[0] } : {},
1098
+ ...tag ? { importPath: getTagImportPath({
1099
+ type: GenerateType.Models,
1100
+ tag,
1101
+ includeTagDir: true,
1102
+ options: resolver.options
1103
+ }) } : {}
1104
+ };
1105
+ }
1106
+ function getSchemaTsMetaType({ schema, isCircular, parentTypes, resolver }) {
1107
+ if (!schema) return { metaType: "primitive" };
1108
+ for (const compositeKeyword of COMPOSITE_KEYWORDS) {
1109
+ const compositeObjs = schema[compositeKeyword];
1110
+ if (!compositeObjs) continue;
1111
+ if (compositeObjs.length > 1) {
1112
+ const metaTypes = compositeObjs.map((compositeObj) => {
1113
+ return getSchemaTsMetaType({
1114
+ schema: resolver.resolveObject(compositeObj),
1115
+ parentTypes,
1116
+ resolver
1117
+ });
1118
+ });
1119
+ if (metaTypes.every(({ metaType }) => metaType === "object")) return {
1120
+ metaType: "object",
1121
+ objectProperties: metaTypes.reduce((acc, { objectProperties }) => {
1122
+ const objectPropertyNames = new Set(objectProperties.map(({ name }) => name));
1123
+ return [...acc.filter(({ name }) => !objectPropertyNames.has(name)), ...objectProperties];
1124
+ }, [])
1125
+ };
1126
+ else return {
1127
+ metaType: "composite",
1128
+ [compositeKeyword]: metaTypes
1129
+ };
1130
+ } else schema = resolver.resolveObject(compositeObjs[0]);
1131
+ }
1132
+ if (schema.type === "array") return {
1133
+ metaType: "array",
1134
+ arrayType: getArraySchemaTsType({
1135
+ arraySchema: schema,
1136
+ resolver,
1137
+ parentTypes
1138
+ })
1139
+ };
1140
+ else if ((schema.type === "object" || schema.properties) && isCircular) return {
1141
+ metaType: "object",
1142
+ objectProperties: [],
1143
+ isCircular: true
1144
+ };
1145
+ else if (schema.type === "object" || schema.properties) return {
1146
+ metaType: "object",
1147
+ objectProperties: getSchemaTsProperties({
1148
+ schema,
1149
+ parentTypes,
1150
+ resolver
1151
+ })
1152
+ };
1153
+ return { metaType: "primitive" };
1154
+ }
1155
+ function getArraySchemaTsType({ arraySchema, parentTypes, resolver }) {
1156
+ let zodSchemaName;
1157
+ let schema;
1158
+ if (isReferenceObject(arraySchema.items)) {
1159
+ const ref = arraySchema.items.$ref;
1160
+ zodSchemaName = resolver.getZodSchemaNameByRef(ref);
1161
+ schema = resolver.getSchemaByRef(ref);
1162
+ } else schema = arraySchema.items;
1163
+ const tsType = getTsTypeBase({
1164
+ zodSchemaName,
1165
+ schema,
1166
+ resolver
1167
+ });
1168
+ const isCircular = getIsCircular(tsType, parentTypes);
1169
+ const tsMetaType = getSchemaTsMetaType({
1170
+ schema,
1171
+ isCircular,
1172
+ parentTypes: [...parentTypes, tsType],
1173
+ resolver
1174
+ });
1175
+ return {
1176
+ ...tsType,
1177
+ ...tsMetaType
1178
+ };
1179
+ }
1180
+ function getSchemaTsProperties({ schema, parentTypes, resolver }) {
1181
+ return Object.entries(schema?.properties ?? {}).map(([name, property]) => {
1182
+ const isRequired = schema?.required?.includes(name) ?? false;
1183
+ if (isReferenceObject(property)) {
1184
+ const zodSchemaName = resolver.getZodSchemaNameByRef(property.$ref);
1185
+ const schema = resolver.getSchemaByRef(property.$ref);
1186
+ const tsType = getTsTypeBase({
1187
+ zodSchemaName,
1188
+ schema,
1189
+ resolver
1190
+ });
1191
+ const tsMetaType = getSchemaTsMetaType({
1192
+ schema,
1193
+ isCircular: getIsCircular(tsType, parentTypes),
1194
+ parentTypes: [...parentTypes, tsType],
1195
+ resolver
1196
+ });
1197
+ return {
1198
+ name,
1199
+ isRequired,
1200
+ ...tsType,
1201
+ ...tsMetaType
1202
+ };
1203
+ } else if (property.type === "array") return {
1204
+ name,
1205
+ isRequired,
1206
+ type: "array",
1207
+ metaType: "array",
1208
+ arrayType: getArraySchemaTsType({
1209
+ arraySchema: property,
1210
+ parentTypes,
1211
+ resolver
1212
+ })
1213
+ };
1214
+ else if (isPrimitiveType(property.type)) return {
1215
+ name,
1216
+ isRequired,
1217
+ type: primitiveTypeToTsType(property.type),
1218
+ metaType: "primitive"
1219
+ };
1220
+ return {
1221
+ name,
1222
+ isRequired,
1223
+ type: "void",
1224
+ metaType: "primitive"
1225
+ };
1226
+ });
1227
+ }
1228
+ function getIsCircular(tsType, parentTypes) {
1229
+ return parentTypes.findIndex(({ type, namespace }) => type === tsType.type && namespace === tsType.namespace) > -1;
1230
+ }
1231
+
1232
+ //#endregion
1233
+ //#region src/generators/utils/generate/generate.endpoints.utils.ts
1234
+ const getEndpointName = (endpoint) => decapitalize(snakeToCamel(endpoint.operationName));
1235
+ function getImportedEndpointName(endpoint, options) {
1236
+ return `${options.tsNamespaces ? `${getNamespaceName({
1237
+ type: GenerateType.Endpoints,
1238
+ tag: getEndpointTag(endpoint, options),
1239
+ options
1240
+ })}.` : ""}${getEndpointName(endpoint)}`;
1241
+ }
1242
+ const requiresBody = (endpoint) => endpoint.method !== OpenAPIV3.HttpMethods.GET;
1243
+ const getEndpointBody$1 = (endpoint) => endpoint.parameters.find((param) => param.type === "Body");
1244
+ const hasEndpointConfig = (endpoint, resolver) => {
1245
+ const endpointConfig = getEndpointConfig(endpoint);
1246
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1247
+ return Object.keys(endpointConfig).length > 0 || hasAxiosRequestConfig;
1248
+ };
1249
+ const getEndpointPath = (endpoint) => endpoint.path.replace(/:([a-zA-Z0-9_]+)/g, "${$1}");
1250
+ function mapEndpointParamsToFunctionParams(resolver, endpoint, options) {
1251
+ const params = endpoint.parameters.map((param) => {
1252
+ let type = "string";
1253
+ if (isNamedZodSchema(param.zodSchema)) type = getImportedZodSchemaInferedTypeName(resolver, param.zodSchema, void 0, options?.modelNamespaceTag);
1254
+ else if (param.parameterObject?.schema && isSchemaObject(param.parameterObject.schema)) {
1255
+ const openApiSchemaType = (param.parameterObject?.schema)?.type;
1256
+ if (openApiSchemaType && isPrimitiveType(openApiSchemaType)) type = primitiveTypeToTsType(openApiSchemaType);
1257
+ }
1258
+ return {
1259
+ name: invalidVariableNameCharactersToCamel(param.name),
1260
+ type,
1261
+ paramType: param.type,
1262
+ required: param.parameterObject?.required ?? true,
1263
+ parameterObject: param.parameterObject,
1264
+ bodyObject: param.bodyObject
1265
+ };
1266
+ });
1267
+ if (options?.includeFileParam && endpoint.mediaUpload) params.push({
1268
+ name: "file",
1269
+ type: "File",
1270
+ paramType: "Body",
1271
+ required: false,
1272
+ parameterObject: void 0,
1273
+ bodyObject: void 0
1274
+ });
1275
+ return params.toSorted((a, b) => {
1276
+ if (a.required === b.required) {
1277
+ const sortedParamTypes = [
1278
+ "Path",
1279
+ "Body",
1280
+ "Query",
1281
+ "Header"
1282
+ ];
1283
+ return sortedParamTypes.indexOf(a.paramType) - sortedParamTypes.indexOf(b.paramType);
1284
+ }
1285
+ return a.required ? -1 : 1;
1286
+ }).filter((param) => (!options?.excludeBodyParam || param.name !== BODY_PARAMETER_NAME) && (!options?.excludePageParam || param.name !== resolver.options.infiniteQueryParamNames.page) && (!options?.includeOnlyRequiredParams || param.required)).map((param) => ({
1287
+ ...param,
1288
+ name: options?.replacePageParam && param.name === resolver.options.infiniteQueryParamNames.page ? "pageParam" : param.name,
1289
+ required: options?.optionalPathParams && param.paramType === "Path" ? false : param.required && (param.paramType === "Path" || !options?.pathParamsRequiredOnly)
1290
+ }));
1291
+ }
1292
+ function getEndpointConfig(endpoint) {
1293
+ const params = endpoint.parameters.filter((param) => param.type === "Query").map((param) => {
1294
+ const paramPropertyName = isValidPropertyName(param.name) ? param.name : `"${param.name}"`;
1295
+ const paramVariableName = invalidVariableNameCharactersToCamel(param.name);
1296
+ return {
1297
+ ...param,
1298
+ name: paramPropertyName,
1299
+ value: paramVariableName
1300
+ };
1301
+ });
1302
+ const headers = {};
1303
+ if (endpoint.requestFormat !== DEFAULT_HEADERS["Content-Type"]) headers["Content-Type"] = `'${endpoint.requestFormat}'`;
1304
+ if (endpoint.responseFormat && endpoint.responseFormat !== DEFAULT_HEADERS.Accept) headers.Accept = `'${endpoint.responseFormat}'`;
1305
+ endpoint.parameters.filter((param) => param.type === "Header").forEach((param) => {
1306
+ headers[param.name] = invalidVariableNameCharactersToCamel(param.name);
1307
+ });
1308
+ return {
1309
+ ...params.length > 0 ? { params } : {},
1310
+ ...Object.keys(headers).length ? { headers } : {}
1311
+ };
1312
+ }
1313
+
1314
+ //#endregion
1315
+ //#region src/generators/utils/query.utils.ts
1316
+ const isQuery = (endpoint) => isGetEndpoint(endpoint);
1317
+ const isMutation = (endpoint) => !isGetEndpoint(endpoint) || !!endpoint.mediaDownload;
1318
+ const isInfiniteQuery = (endpoint, options) => isPaginatedGetEndpoint(endpoint, options);
1319
+ const getDestructuredVariables = (resolver, endpoint, updateQueryEndpoints) => {
1320
+ const requiredUpdateQueryParams = updateQueryEndpoints.reduce((acc, updateEndpoint) => [...acc, ...mapEndpointParamsToFunctionParams(resolver, updateEndpoint, { includeOnlyRequiredParams: true }).map((param) => param.name)], []);
1321
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, {
1322
+ includeOnlyRequiredParams: true,
1323
+ excludeBodyParam: true
1324
+ }).filter((param) => requiredUpdateQueryParams.includes(param.name)).map((param) => param.name);
1325
+ };
1326
+
1327
+ //#endregion
1328
+ //#region src/generators/core/endpoints/getEndpointAcl.ts
1329
+ function getEndpointAcl({ resolver, endpoint, operation }) {
1330
+ const acl = operation["x-acl"];
1331
+ return acl?.map((item) => {
1332
+ const conditionsTypes = Object.keys(item.conditions ?? {}).reduce((acc, name) => {
1333
+ const propertyType = getEndpointAclConditionPropertyType({
1334
+ resolver,
1335
+ endpoint,
1336
+ acl,
1337
+ name
1338
+ });
1339
+ if (!propertyType) {
1340
+ resolver.validationErrors.push(getMissingAclConditionPropertyError(name, operation, endpoint));
1341
+ return acc;
1342
+ }
1343
+ return [...acc, propertyType];
1344
+ }, []);
1345
+ return {
1346
+ ...item,
1347
+ conditionsTypes
1348
+ };
1349
+ });
1350
+ }
1351
+ function getEndpointAclConditionPropertyType({ resolver, endpoint, acl, name }) {
1352
+ const conditionPropertyPath = acl[0]?.conditions?.[name];
1353
+ if (!conditionPropertyPath) return;
1354
+ const pathSplits = conditionPropertyPath.replace(/^\$[^.]*\./, "").split(".");
1355
+ let schema = void 0;
1356
+ let required = void 0;
1357
+ let info = void 0;
1358
+ let index = 0;
1359
+ const parameter = endpoint.parameters.find(({ name }) => name === pathSplits[index]);
1360
+ if (parameter) {
1361
+ required = parameter.parameterObject?.required;
1362
+ schema = parameter.parameterObject?.schema;
1363
+ info = `${parameter.name} ${decapitalize(parameter.type)} parameter`;
1364
+ index++;
1365
+ } else {
1366
+ const bodyParameter = endpoint.parameters.find(({ bodyObject }) => !!bodyObject);
1367
+ const matchingMediaType = Object.keys(bodyParameter?.bodyObject?.content ?? {}).find(isParamMediaTypeAllowed);
1368
+ if (matchingMediaType) {
1369
+ schema = bodyParameter?.bodyObject?.content?.[matchingMediaType]?.schema;
1370
+ info = `${isQuery(endpoint) ? "query" : "mutation"} data`;
1371
+ }
1372
+ }
1373
+ while (schema && index < pathSplits.length) {
1374
+ const resolvedSchema = resolver.resolveObject(schema);
1375
+ schema = Object.entries(resolvedSchema.properties ?? {}).find(([key]) => key === pathSplits[index])?.[1];
1376
+ required = resolvedSchema.required?.includes(pathSplits[index]) ?? false;
1377
+ index++;
1378
+ }
1379
+ if (!schema) return;
1380
+ return {
1381
+ name,
1382
+ type: isReferenceObject(schema) ? void 0 : schema.type,
1383
+ zodSchemaName: isReferenceObject(schema) ? resolver.getZodSchemaNameByRef(schema.$ref) : void 0,
1384
+ required,
1385
+ info
1386
+ };
1387
+ }
1388
+
1389
+ //#endregion
1390
+ //#region src/generators/core/zod/getZodChain.ts
1391
+ function getZodChain({ schema, meta, options }) {
1392
+ const chains = [];
1393
+ match(schema.type).with("string", () => chains.push(getZodChainableStringValidations(schema))).with("number", "integer", () => chains.push(getZodChainableNumberValidations(schema))).with("array", () => chains.push(getZodChainableArrayValidations(schema))).otherwise(() => void 0);
1394
+ if (typeof schema.description === "string" && schema.description !== "" && options.withDescription) chains.push(`describe(${JSON.stringify(schema.description)})`);
1395
+ const output = chains.concat(getZodChainablePresence({
1396
+ schema,
1397
+ meta,
1398
+ options
1399
+ }), options.withDefaultValues !== false ? getZodChainableDefault(schema) : []).filter(Boolean).join(".");
1400
+ return output ? `.${output}` : "";
1401
+ }
1402
+ function getZodChainablePresence({ schema, meta, options }) {
1403
+ if (schema.nullable && !meta?.isRequired) return "nullish()";
1404
+ if (schema.nullable || options.replaceOptionalWithNullish && meta?.isParentPartial) return "nullable()";
1405
+ if (!meta?.isRequired) return options.replaceOptionalWithNullish ? "nullish()" : "optional()";
1406
+ return "";
1407
+ }
1408
+ function getZodChainableDefault(schema) {
1409
+ if (schema.default !== void 0) return `default(${match(schema.type).with("number", "integer", () => unwrapQuotesIfNeeded(schema.default)).otherwise(() => JSON.stringify(schema.default))})`;
1410
+ return "";
1411
+ }
1412
+ function getZodChainableStringValidations(schema) {
1413
+ const validations = [];
1414
+ if (!schema.enum) {
1415
+ if (schema.minLength !== void 0) validations.push(`min(${schema.minLength})`);
1416
+ if (schema.maxLength !== void 0) validations.push(`max(${schema.maxLength})`);
1417
+ }
1418
+ if (schema.pattern) validations.push(`regex(${formatPatternIfNeeded(schema.pattern)})`);
1419
+ return validations.join(".");
1420
+ }
1421
+ function formatPatternIfNeeded(pattern) {
1422
+ if (pattern.startsWith("/") && pattern.endsWith("/")) pattern = pattern.slice(1, -1);
1423
+ pattern = escapeControlCharacters(pattern);
1424
+ return `/${pattern}/`;
1425
+ }
1426
+ function getZodChainableNumberValidations(schema) {
1427
+ const validations = [];
1428
+ if (schema.enum) return "";
1429
+ if (schema.minimum !== void 0) if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
1430
+ else validations.push(`gte(${schema.minimum})`);
1431
+ else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
1432
+ if (schema.maximum !== void 0) if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
1433
+ else validations.push(`lte(${schema.maximum})`);
1434
+ else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
1435
+ if (schema.multipleOf) validations.push(`multipleOf(${schema.multipleOf})`);
1436
+ return validations.join(".");
1437
+ }
1438
+ function getZodChainableArrayValidations(schema) {
1439
+ const validations = [];
1440
+ if (schema.minItems) validations.push(`min(${schema.minItems})`);
1441
+ if (schema.maxItems) validations.push(`max(${schema.maxItems})`);
1442
+ return validations.join(".");
1443
+ }
1444
+
1445
+ //#endregion
1446
+ //#region src/generators/core/zod/getZodSchemaRefs.ts
1447
+ function getZodSchemaRefs(resolver, zodSchemaName) {
1448
+ const schemaRef = resolver.getRefByZodSchemaName(zodSchemaName);
1449
+ if (schemaRef) {
1450
+ const refs = Array.from(resolver.dependencyGraph.refsDependencyGraph[schemaRef] ?? []).map((ref) => resolver.getZodSchemaNameByRef(ref));
1451
+ const enumRefs = resolver.getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef);
1452
+ return [...refs, ...enumRefs];
1453
+ }
1454
+ const zodSchema = resolver.getCompositeZodSchemaByZodSchemaName(zodSchemaName);
1455
+ if (zodSchema) return Array.from(getSchemaRefs(zodSchema)).map((schemaRef) => resolver.getZodSchemaNameByRef(schemaRef));
1456
+ return [];
1457
+ }
1458
+ function getSchemaRefs(zodSchema, { skipObjectSchema = false } = {}) {
1459
+ return zodSchema.children.reduce((acc, child) => {
1460
+ const ref = child.ref ?? child.enumRef;
1461
+ if (ref) acc.add(ref);
1462
+ if (child.children.length > 0 && (!skipObjectSchema || !isSchemaObject(child.schema) || child.schema.type !== "object")) getSchemaRefs(child).forEach((ref) => acc.add(ref));
1463
+ return acc;
1464
+ }, /* @__PURE__ */ new Set());
1465
+ }
1466
+
1467
+ //#endregion
1468
+ //#region src/generators/utils/math.utils.ts
1469
+ const sum = (arr) => arr.reduce((acc, item) => acc + item, 0);
1470
+
1471
+ //#endregion
1472
+ //#region src/generators/core/openapi/getOpenAPISchemaComplexity.ts
1473
+ function getOpenAPISchemaComplexity(current, schema) {
1474
+ if (!schema) return current;
1475
+ if (isReferenceObject(schema)) return current + 2;
1476
+ if (Array.isArray(schema.type)) {
1477
+ if (schema.type.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, {
1478
+ ...schema,
1479
+ type: schema.type[0]
1480
+ });
1481
+ return current + complexityByComposite("oneOf") + sum(schema.type.map((prop) => getOpenAPISchemaComplexity(0, {
1482
+ ...schema,
1483
+ type: prop
1484
+ })));
1485
+ }
1486
+ if (schema.oneOf) {
1487
+ if (schema.oneOf.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, schema.oneOf[0]);
1488
+ return current + complexityByComposite("oneOf") + sum(schema.oneOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1489
+ }
1490
+ if (schema.anyOf) {
1491
+ if (schema.anyOf.length === 1) return complexityByComposite("anyOf") + getOpenAPISchemaComplexity(current, schema.anyOf[0]);
1492
+ return current + complexityByComposite("anyOf") + sum(schema.anyOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1493
+ }
1494
+ if (schema.allOf) {
1495
+ if (schema.allOf.length === 1) return complexityByComposite("allOf") + getOpenAPISchemaComplexity(current, schema.allOf[0]);
1496
+ return current + complexityByComposite("allOf") + sum(schema.allOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1497
+ }
1498
+ if (!schema.type) return current;
1499
+ if (isPrimitiveType(schema.type)) {
1500
+ if (schema.enum) return current + complexityByType(schema) + complexityByComposite("enum") + sum(schema.enum.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1501
+ return current + complexityByType(schema);
1502
+ }
1503
+ if (schema.type === "array") {
1504
+ if (schema.items) return complexityByComposite("array") + getOpenAPISchemaComplexity(current, schema.items);
1505
+ return complexityByComposite("array") + getOpenAPISchemaComplexity(current);
1506
+ }
1507
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
1508
+ if (schema.properties) {
1509
+ const props = Object.values(schema.properties);
1510
+ current += complexityByComposite("object") + sum(props.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1511
+ } else current += complexityByComposite("empty-object");
1512
+ if (schema.additionalProperties) if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
1513
+ else current += getOpenAPISchemaComplexity(1);
1514
+ }
1515
+ return current;
1516
+ }
1517
+ function complexityByType(schema) {
1518
+ return match(schema.type).with("string", "number", "integer", "boolean", () => 1).otherwise(() => 0);
1519
+ }
1520
+ function complexityByComposite(type) {
1521
+ return match(type).with("oneOf", () => 2).with("anyOf", () => 3).with("allOf", () => 2).with("enum", "array", "empty-object", () => 1).with("object", () => 2).otherwise(() => 0);
1522
+ }
1523
+
1524
+ //#endregion
1525
+ //#region src/generators/core/zod/ZodSchema.class.ts
1526
+ var ZodSchema = class {
1527
+ code;
1528
+ ref;
1529
+ enumRef;
1530
+ children = [];
1531
+ meta;
1532
+ constructor(schema, resolver, meta = { referencedBy: [] }, enumRef) {
1533
+ this.schema = schema;
1534
+ this.resolver = resolver;
1535
+ if (isReferenceObject(schema)) this.ref = schema.$ref;
1536
+ if (enumRef) this.enumRef = enumRef;
1537
+ this.meta = {
1538
+ ...meta,
1539
+ referencedBy: [...meta?.referencedBy ?? []]
1540
+ };
1541
+ if (this.ref) this.meta.referencedBy.push(this);
1542
+ }
1543
+ getCodeString(tag, options) {
1544
+ if (!this.ref && this.code) return this.code;
1545
+ if (!this.ref) throw new Error("Zod schema is missing both ref and code");
1546
+ const zodSchemaName = this.resolver?.getZodSchemaNameByRef(this.ref);
1547
+ if (!zodSchemaName) return this.ref;
1548
+ const zodSchemaTag = this.resolver?.getTagByZodSchemaName(zodSchemaName);
1549
+ if (options?.tsNamespaces && zodSchemaTag && zodSchemaTag !== tag) return `${getNamespaceName({
1550
+ type: GenerateType.Models,
1551
+ tag: zodSchemaTag,
1552
+ options
1553
+ })}.${zodSchemaName}`;
1554
+ return zodSchemaName;
1555
+ }
1556
+ get complexity() {
1557
+ return getOpenAPISchemaComplexity(0, this.schema);
1558
+ }
1559
+ assign(code) {
1560
+ this.code = code;
1561
+ return this;
1562
+ }
1563
+ inherit(parent) {
1564
+ if (parent) parent.children.push(this);
1565
+ return this;
1566
+ }
1567
+ };
1568
+ function getParentRef(meta) {
1569
+ if (!meta) return;
1570
+ if (meta.parent?.ref) return meta.parent.ref;
1571
+ return getParentRef(meta.parent?.meta);
1572
+ }
1573
+
1574
+ //#endregion
1575
+ //#region src/generators/core/zod/getZodSchema.ts
1576
+ /**
1577
+ * @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject
1578
+ * @see https://github.com/colinhacks/zod
1579
+ */
1580
+ function getZodSchema({ schema, resolver, meta: inheritedMeta, tag }) {
1581
+ const zodSchema = new ZodSchema(schema, resolver, inheritedMeta);
1582
+ const meta = {
1583
+ parent: zodSchema.inherit(inheritedMeta?.parent),
1584
+ referencedBy: [...zodSchema.meta.referencedBy]
1585
+ };
1586
+ const params = {
1587
+ resolver,
1588
+ meta,
1589
+ tag
1590
+ };
1591
+ if (isReferenceObject(schema)) return getReferenceZodSchema({
1592
+ schema,
1593
+ zodSchema,
1594
+ resolver,
1595
+ meta,
1596
+ tag
1597
+ });
1598
+ const arrayZodSchema = getArrayZodSchema({
1599
+ schema,
1600
+ zodSchema,
1601
+ resolver,
1602
+ meta,
1603
+ tag
1604
+ });
1605
+ if (arrayZodSchema) return arrayZodSchema;
1606
+ const oneOfZodSchema = getOneOfZodSchema({
1607
+ schema,
1608
+ zodSchema,
1609
+ resolver,
1610
+ meta,
1611
+ tag
1612
+ });
1613
+ if (oneOfZodSchema) return oneOfZodSchema;
1614
+ const anyOfZodSchema = getAnyOfZodSchema({
1615
+ schema,
1616
+ zodSchema,
1617
+ resolver,
1618
+ meta,
1619
+ tag
1620
+ });
1621
+ if (anyOfZodSchema) return anyOfZodSchema;
1622
+ const allOfZodSchema = getAllOfZodSchema({
1623
+ schema,
1624
+ zodSchema,
1625
+ resolver,
1626
+ meta,
1627
+ tag
1628
+ });
1629
+ if (allOfZodSchema) return allOfZodSchema;
1630
+ const primitiveZodSchema = getPrimitiveZodSchema({
1631
+ schema,
1632
+ zodSchema,
1633
+ resolver,
1634
+ meta,
1635
+ tag
1636
+ });
1637
+ if (primitiveZodSchema) return primitiveZodSchema;
1638
+ const readonly = resolver.options.allReadonly ? ".readonly()" : "";
1639
+ if (isArraySchemaObject(schema)) {
1640
+ if (schema.items) return zodSchema.assign(`z.array(${getZodSchema({
1641
+ ...params,
1642
+ schema: schema.items
1643
+ }).getCodeString(tag, resolver.options)}${getZodChain({
1644
+ schema: schema.items,
1645
+ meta: {
1646
+ ...meta,
1647
+ isRequired: true
1648
+ },
1649
+ options: resolver.options
1650
+ })})${readonly}`);
1651
+ return zodSchema.assign(`z.array(${ANY_SCHEMA})${readonly}`);
1652
+ }
1653
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
1654
+ if (schemaType === "object" || schema.properties || schema.additionalProperties) {
1655
+ const hasRequiredArray = schema.required && schema.required.length > 0;
1656
+ const isPartial = resolver.options.withImplicitRequiredProps ? false : schema.properties && !schema.required?.length;
1657
+ let properties = "{}";
1658
+ if (schema.properties) properties = `{ ${Object.entries(schema.properties).map(([prop, propSchema]) => {
1659
+ const propMetadata = {
1660
+ ...meta,
1661
+ isRequired: isPartial ? true : hasRequiredArray ? schema.required?.includes(prop) : resolver.options.withImplicitRequiredProps,
1662
+ name: prop,
1663
+ isParentPartial: isPartial
1664
+ };
1665
+ let propActualSchema = propSchema;
1666
+ if (isReferenceObject(propSchema) && resolver) {
1667
+ propActualSchema = resolver.getSchemaByRef(propSchema.$ref);
1668
+ if (!propActualSchema) throw new Error(`Schema ${propSchema.$ref} not found`);
1669
+ }
1670
+ const zodSchema = getZodSchema({
1671
+ ...params,
1672
+ schema: propSchema,
1673
+ meta: propMetadata
1674
+ });
1675
+ const propZodSchema = zodSchema.getCodeString(tag, resolver.options) + getZodChain({
1676
+ schema: propActualSchema,
1677
+ meta: propMetadata,
1678
+ options: resolver.options
1679
+ });
1680
+ let isCircular = false;
1681
+ const parentRef = getParentRef(inheritedMeta);
1682
+ if (parentRef) isCircular = [...isReferenceObject(propSchema) ? [propSchema.$ref] : [], ...getSchemaRefs(zodSchema, { skipObjectSchema: true })].some((ref) => resolver.dependencyGraph.deepDependencyGraph[ref]?.has(parentRef));
1683
+ return [
1684
+ prop,
1685
+ propZodSchema,
1686
+ isCircular
1687
+ ];
1688
+ }).map(([prop, propSchema, isCircular]) => isCircular ? `get ${wrapWithQuotesIfNeeded(prop)}() { return ${propSchema} }` : `${wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
1689
+ let additionalPropsSchema = "";
1690
+ if (schema.additionalProperties) additionalPropsSchema = `.catchall(${typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0 ? getZodSchema({
1691
+ ...params,
1692
+ schema: schema.additionalProperties
1693
+ }).getCodeString(tag, resolver.options) + getZodChain({
1694
+ schema: schema.additionalProperties,
1695
+ meta: {
1696
+ ...meta,
1697
+ isRequired: true
1698
+ },
1699
+ options: resolver.options
1700
+ }) : ANY_SCHEMA})`;
1701
+ const zodObject = `z.object(${properties})${isPartial ? ".partial()" : ""}${additionalPropsSchema}${readonly}`;
1702
+ return zodSchema.assign(zodObject);
1703
+ }
1704
+ if (schemaType === "any") return zodSchema.assign(ANY_SCHEMA);
1705
+ if (schemaType === "null") return zodSchema.assign("z.null()");
1706
+ if (!schemaType) return zodSchema.assign("z.unknown()");
1707
+ throw new Error(`Unsupported schema type: ${schemaType}`);
1708
+ }
1709
+ function getReferenceZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1710
+ if (!isReferenceObject(schema)) return;
1711
+ const refsPath = zodSchema.meta.referencedBy.slice(0, -1).map((prev) => prev.ref ? resolver.getZodSchemaNameByRef(prev.ref) ?? prev.ref : void 0).filter(Boolean);
1712
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schema.$ref);
1713
+ if (refsPath.length > 1 && refsPath.includes(zodSchemaName)) return zodSchema.assign(resolver.getCodeByZodSchemaName(zodSchema.ref));
1714
+ let result = resolver.getCodeByZodSchemaName(schema.$ref);
1715
+ if (!result) {
1716
+ const actualSchema = resolver.getSchemaByRef(schema.$ref);
1717
+ if (!actualSchema) throw new Error(`Schema ${schema.$ref} not found`);
1718
+ result = getZodSchema({
1719
+ schema: actualSchema,
1720
+ resolver,
1721
+ meta,
1722
+ tag
1723
+ }).getCodeString(tag, resolver.options);
1724
+ }
1725
+ if (resolver.getCodeByZodSchemaName(zodSchemaName)) return zodSchema;
1726
+ resolver.setZodSchema(zodSchemaName, result, tag);
1727
+ return zodSchema;
1728
+ }
1729
+ function getOneOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1730
+ if (!isSchemaObject(schema) || !schema.oneOf) return;
1731
+ if (schema.oneOf.length === 1) {
1732
+ const type = getZodSchema({
1733
+ schema: schema.oneOf[0],
1734
+ resolver,
1735
+ meta,
1736
+ tag
1737
+ });
1738
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1739
+ }
1740
+ const hasMultipleAllOf = schema.oneOf?.some((obj) => isSchemaObject(obj) && (obj?.allOf || []).length > 1);
1741
+ if (schema.discriminator && !hasMultipleAllOf) {
1742
+ const propertyName = schema.discriminator.propertyName;
1743
+ return zodSchema.assign(`
1744
+ z.discriminatedUnion("${propertyName}", [${schema.oneOf.map((schema) => getZodSchema({
1745
+ schema,
1746
+ resolver,
1747
+ meta,
1748
+ tag
1749
+ }).getCodeString(tag, resolver.options)).join(", ")}])
1750
+ `);
1751
+ }
1752
+ return zodSchema.assign(`z.union([${schema.oneOf.map((schema) => getZodSchema({
1753
+ schema,
1754
+ resolver,
1755
+ meta,
1756
+ tag
1757
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
1758
+ }
1759
+ function getArrayZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1760
+ if (!isSchemaObject(schema) || !Array.isArray(schema.type)) return;
1761
+ if (schema.type.length === 1) return getZodSchema({
1762
+ schema: {
1763
+ ...schema,
1764
+ type: schema.type[0]
1765
+ },
1766
+ resolver,
1767
+ meta,
1768
+ tag
1769
+ });
1770
+ return zodSchema.assign(`z.union([${schema.type.map((prop) => getZodSchema({
1771
+ schema: {
1772
+ ...schema,
1773
+ type: prop
1774
+ },
1775
+ resolver,
1776
+ meta,
1777
+ tag
1778
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
1779
+ }
1780
+ function getAnyOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1781
+ if (!isSchemaObject(schema) || !schema.anyOf) return;
1782
+ if (schema.anyOf.length === 1) {
1783
+ const type = getZodSchema({
1784
+ schema: schema.anyOf[0],
1785
+ resolver,
1786
+ meta,
1787
+ tag
1788
+ });
1789
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1790
+ }
1791
+ const types = schema.anyOf.map((schema) => getZodSchema({
1792
+ schema,
1793
+ resolver,
1794
+ meta,
1795
+ tag
1796
+ })).map((type) => type.getCodeString(tag, resolver.options)).join(", ");
1797
+ return zodSchema.assign(`z.union([${types}])`);
1798
+ }
1799
+ function getAllOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1800
+ if (!isSchemaObject(schema) || !schema.allOf) return;
1801
+ if (schema.allOf.length === 1) {
1802
+ const type = getZodSchema({
1803
+ schema: schema.allOf[0],
1804
+ resolver,
1805
+ meta,
1806
+ tag
1807
+ });
1808
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1809
+ }
1810
+ const { patchRequiredSchemaInLoop, noRequiredOnlyAllof, composedRequiredSchema } = inferRequiredSchema(schema);
1811
+ const types = noRequiredOnlyAllof.map((schema) => {
1812
+ const type = getZodSchema({
1813
+ schema,
1814
+ resolver,
1815
+ meta,
1816
+ tag
1817
+ });
1818
+ if (resolver) patchRequiredSchemaInLoop(schema, resolver.getSchemaByRef.bind(resolver));
1819
+ return type;
1820
+ });
1821
+ if (composedRequiredSchema.required.length) types.push(getZodSchema({
1822
+ schema: composedRequiredSchema,
1823
+ resolver,
1824
+ meta,
1825
+ tag
1826
+ }));
1827
+ const first = types.at(0);
1828
+ const rest = types.slice(1).map((type) => `...${type.getCodeString(tag, resolver.options)}.shape`).join(", ");
1829
+ return zodSchema.assign(`z.object({ ...${first.getCodeString(tag, resolver.options)}.shape, ${rest} })`);
1830
+ }
1831
+ function getPrimitiveZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1832
+ if (!isSchemaObject(schema)) return;
1833
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
1834
+ if (schemaType && isPrimitiveType(schemaType)) {
1835
+ if (schema.enum) {
1836
+ if (schemaType === "string") return getEnumZodSchema({
1837
+ schema,
1838
+ zodSchema,
1839
+ resolver,
1840
+ meta,
1841
+ tag
1842
+ });
1843
+ if (schema.enum.some((e) => typeof e === "string")) return zodSchema.assign("z.never()");
1844
+ if (schema.enum.length === 1) {
1845
+ const value = schema.enum[0];
1846
+ return zodSchema.assign(`z.literal(${value === null ? "null" : value})`);
1847
+ }
1848
+ return zodSchema.assign(`z.union([${schema.enum.map((value) => `z.literal(${value === null ? "null" : value})`).join(", ")}])`);
1849
+ }
1850
+ return zodSchema.assign(match(schemaType).with("integer", () => match(schema.type).with("integer", () => INT_SCHEMA).otherwise(() => NUMBER_SCHEMA)).with("string", () => match(schema.format).with("binary", () => BLOB_SCHEMA).with("email", () => EMAIL_SCHEMA).with("hostname", "uri", () => URL_SCHEMA).with("uuid", () => UUID_SCHEMA).with("date-time", () => DATETIME_SCHEMA).otherwise(() => STRING_SCHEMA)).otherwise((type) => `z.${type}()`));
1851
+ }
1852
+ }
1853
+ function getEnumZodSchema({ resolver, schema, zodSchema, meta, tag }) {
1854
+ if (!isSchemaObject(schema)) return;
1855
+ const code = getEnumZodSchemaCode(schema);
1856
+ if (!resolver.options.extractEnums) return zodSchema.assign(code);
1857
+ const enumZodSchema = resolver.getEnumZodSchemaDataByCode(code);
1858
+ if (enumZodSchema) {
1859
+ if (zodSchema.meta.parent?.ref === resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName)) return zodSchema.assign(enumZodSchema.code);
1860
+ return new ZodSchema({ $ref: resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName) }, resolver, meta).inherit(zodSchema).assign(code);
1861
+ }
1862
+ const extractedEnumZodSchema = resolver.getExtractedEnumZodSchemaDataByCode(code);
1863
+ if (!extractedEnumZodSchema) return zodSchema.assign(code);
1864
+ if (!extractedEnumZodSchema.zodSchemaName || !extractedEnumZodSchema.tag) throw new Error(`Enum zod schema name or tag not resolved for code: ${code}`);
1865
+ const namespacePrefix = resolver.options.tsNamespaces && extractedEnumZodSchema.tag !== tag ? `${getNamespaceName({
1866
+ type: GenerateType.Models,
1867
+ tag: extractedEnumZodSchema.tag,
1868
+ options: resolver.options
1869
+ })}.` : "";
1870
+ return zodSchema.assign(`${namespacePrefix}${extractedEnumZodSchema.zodSchemaName}`);
1871
+ }
1872
+ function getEnumZodSchemaCode(schema) {
1873
+ return `${ENUM_SCHEMA}([${schema.enum?.map((value) => value === null ? "null" : `"${value}"`).join(", ")}])`;
1874
+ }
1875
+ function getEnumZodSchemaCodeFromEnumNames(enumNames) {
1876
+ return `${ENUM_SCHEMA}([${enumNames.map((value) => `"${value}"`).join(", ")}])`;
1877
+ }
1878
+
1879
+ //#endregion
1880
+ //#region src/generators/core/zod/resolveZodSchemaName.ts
1881
+ const resolverResolveZodSchemaNameCache = /* @__PURE__ */ new WeakMap();
1882
+ function resolveZodSchemaName({ schema, zodSchema, fallbackName, resolver, tag }) {
1883
+ const result = zodSchema.getCodeString();
1884
+ const cacheKey = `${zodSchema.ref ?? ""}|${fallbackName ?? ""}|${tag}|${zodSchema.complexity}|${result}`;
1885
+ let cacheForResolver = resolverResolveZodSchemaNameCache.get(resolver);
1886
+ if (!cacheForResolver) {
1887
+ cacheForResolver = /* @__PURE__ */ new Map();
1888
+ resolverResolveZodSchemaNameCache.set(resolver, cacheForResolver);
1889
+ }
1890
+ const cachedName = cacheForResolver.get(cacheKey);
1891
+ if (cachedName) return cachedName;
1892
+ if ((!isNamedZodSchema(result) || zodSchema.ref === void 0) && fallbackName) {
1893
+ if (zodSchema.complexity < COMPLEXITY_THRESHOLD) return result;
1894
+ const zodSchemaName = getZodSchemaName(fallbackName, resolver.options.schemaSuffix);
1895
+ while (resolver.getCodeByZodSchemaName(zodSchemaName)) if (resolver.getZodSchemaNamesByCompositeCode(result)?.includes(zodSchemaName)) return zodSchemaName;
1896
+ else if (resolver.getCodeByZodSchemaName(zodSchemaName) === zodSchemaName) return zodSchemaName;
1897
+ else throw new Error(`Can't uniquely resolve zod schema name: ${zodSchemaName}`);
1898
+ resolver.setZodSchema(zodSchemaName, result, tag);
1899
+ resolver.addZodSchemaForCompositeCode(result, zodSchema, zodSchemaName, schema);
1900
+ cacheForResolver.set(cacheKey, zodSchemaName);
1901
+ return zodSchemaName;
1902
+ }
1903
+ let resolvedSchema = resolver.getCodeByZodSchemaName(result);
1904
+ if (!resolvedSchema && zodSchema.ref) resolvedSchema = resolver.getCodeByZodSchemaName(resolver.getZodSchemaNameByRef(zodSchema.ref));
1905
+ if (zodSchema.ref && resolvedSchema) {
1906
+ if (getOpenAPISchemaComplexity(0, resolver.getSchemaByRef(zodSchema.ref)) < COMPLEXITY_THRESHOLD) {
1907
+ const resolvedName = resolver.getCodeByZodSchemaName(result);
1908
+ cacheForResolver.set(cacheKey, resolvedName);
1909
+ return resolvedName;
1910
+ }
1911
+ cacheForResolver.set(cacheKey, result);
1912
+ return result;
1913
+ }
1914
+ if (zodSchema.ref) {
1915
+ const resolvedRefName = resolver.getZodSchemaNameByRef(zodSchema.ref);
1916
+ cacheForResolver.set(cacheKey, resolvedRefName);
1917
+ return resolvedRefName;
1918
+ }
1919
+ throw new Error(`Invalid ref: ${zodSchema.ref}`);
1920
+ }
1921
+
1922
+ //#endregion
1923
+ //#region src/generators/core/endpoints/resolveEndpointZodSchema.ts
1924
+ const resolverEndpointZodSchemaCache = /* @__PURE__ */ new WeakMap();
1925
+ function getResolverSchemaCache(resolver) {
1926
+ let schemaCache = resolverEndpointZodSchemaCache.get(resolver);
1927
+ if (!schemaCache) {
1928
+ schemaCache = {
1929
+ byObject: /* @__PURE__ */ new WeakMap(),
1930
+ byRef: /* @__PURE__ */ new Map()
1931
+ };
1932
+ resolverEndpointZodSchemaCache.set(resolver, schemaCache);
1933
+ }
1934
+ return schemaCache;
1935
+ }
1936
+ function getOrCreateSchemaEntries(schemaCache, schema) {
1937
+ if (isReferenceObject(schema)) {
1938
+ let entries = schemaCache.byRef.get(schema.$ref);
1939
+ if (!entries) {
1940
+ entries = /* @__PURE__ */ new Map();
1941
+ schemaCache.byRef.set(schema.$ref, entries);
1942
+ }
1943
+ return entries;
1944
+ }
1945
+ let entries = schemaCache.byObject.get(schema);
1946
+ if (!entries) {
1947
+ entries = /* @__PURE__ */ new Map();
1948
+ schemaCache.byObject.set(schema, entries);
1949
+ }
1950
+ return entries;
1951
+ }
1952
+ function resolveEndpointZodSchema({ resolver, schema, meta, tag, fallbackName, composeBeforeResolve }) {
1953
+ const entries = getOrCreateSchemaEntries(getResolverSchemaCache(resolver), schema);
1954
+ const isRefSchema = isReferenceObject(schema);
1955
+ const normalizedFallbackName = isRefSchema ? "" : fallbackName ?? "";
1956
+ const normalizedTag = isRefSchema ? "" : tag;
1957
+ const metaKey = `required:${Boolean(meta.isRequired)}|name:${meta.name ?? ""}|parentPartial:${Boolean(meta.isParentPartial)}|fallback:${normalizedFallbackName}|tag:${normalizedTag}|compose:${composeBeforeResolve ? 1 : 0}`;
1958
+ const cached = entries.get(metaKey);
1959
+ if (cached) return cached;
1960
+ const zodSchema = getZodSchema({
1961
+ schema,
1962
+ resolver,
1963
+ meta,
1964
+ tag
1965
+ });
1966
+ const schemaObject = resolver.resolveObject(schema);
1967
+ const zodChain = getZodChain({
1968
+ schema: schemaObject,
1969
+ meta: zodSchema.meta,
1970
+ options: resolver.options
1971
+ });
1972
+ const resolved = composeBeforeResolve ? resolveZodSchemaName({
1973
+ schema: schemaObject,
1974
+ zodSchema: zodSchema.assign(zodSchema.getCodeString(tag) + zodChain),
1975
+ fallbackName,
1976
+ resolver,
1977
+ tag
1978
+ }) : `${resolveZodSchemaName({
1979
+ schema: schemaObject,
1980
+ zodSchema,
1981
+ fallbackName,
1982
+ resolver,
1983
+ tag
1984
+ })}${zodChain}`;
1985
+ entries.set(metaKey, resolved);
1986
+ return resolved;
1987
+ }
1988
+
1989
+ //#endregion
1990
+ //#region src/generators/core/endpoints/getEndpointBody.ts
1991
+ function getEndpointBody({ resolver, operation, operationName, isUniqueOperationName, tag }) {
1992
+ const requestBodyObj = resolver.resolveObject(operation.requestBody);
1993
+ if (!requestBodyObj) return;
1994
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
1995
+ if (!matchingMediaType) return;
1996
+ const schema = requestBodyObj.content?.[matchingMediaType]?.schema;
1997
+ if (!schema) return;
1998
+ const zodSchema = resolveEndpointZodSchema({
1999
+ resolver,
2000
+ schema,
2001
+ meta: { isRequired: requestBodyObj.required ?? true },
2002
+ tag,
2003
+ fallbackName: getBodyZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag)),
2004
+ composeBeforeResolve: false
2005
+ });
2006
+ return {
2007
+ endpointParameter: {
2008
+ name: BODY_PARAMETER_NAME,
2009
+ type: "Body",
2010
+ description: requestBodyObj.description,
2011
+ zodSchema,
2012
+ bodyObject: requestBodyObj
2013
+ },
2014
+ requestFormat: matchingMediaType
2015
+ };
2016
+ }
2017
+
2018
+ //#endregion
2019
+ //#region src/generators/core/endpoints/getEndpointParameter.ts
2020
+ function getEndpointParameter({ resolver, param, operationName, isUniqueOperationName, tag }) {
2021
+ const paramObj = resolver.resolveObject(param);
2022
+ if (!ALLOWED_PATH_IN.includes(paramObj.in)) return;
2023
+ let schema = {};
2024
+ if (paramObj.content) {
2025
+ const mediaTypes = Object.keys(paramObj.content ?? {});
2026
+ const matchingMediaType = mediaTypes.find(isParamMediaTypeAllowed);
2027
+ if (!matchingMediaType) throw new Error(`Unsupported media type for param ${paramObj.name}: ${mediaTypes.join(", ")}`);
2028
+ const mediaTypeObject = paramObj.content?.[matchingMediaType];
2029
+ if (!mediaTypeObject) throw new Error(`No content with media type for param ${paramObj.name}: ${matchingMediaType}`);
2030
+ schema = mediaTypeObject?.schema ?? mediaTypeObject;
2031
+ } else if (paramObj.schema) schema = paramObj.schema;
2032
+ if (resolver.options.withDescription && schema) schema.description = (paramObj.description ?? "").trim();
2033
+ const fallbackName = getParamZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag), paramObj.name);
2034
+ let parameterSortingEnumSchemaName = void 0;
2035
+ if (isSortingParameterObject(paramObj)) {
2036
+ const enumZodSchemaName = getEnumZodSchemaName(fallbackName, resolver.options.enumSuffix, resolver.options.schemaSuffix);
2037
+ const code = getEnumZodSchemaCodeFromEnumNames(paramObj["x-enumNames"]);
2038
+ resolver.setZodSchema(enumZodSchemaName, code, tag);
2039
+ parameterSortingEnumSchemaName = enumZodSchemaName;
2040
+ }
2041
+ const zodSchemaName = resolveEndpointZodSchema({
2042
+ resolver,
2043
+ schema,
2044
+ meta: { isRequired: paramObj.in === "path" ? true : paramObj.required ?? false },
2045
+ tag,
2046
+ fallbackName,
2047
+ composeBeforeResolve: true
2048
+ });
2049
+ return {
2050
+ name: match(paramObj.in).with("path", () => pathParamToVariableName(paramObj.name)).otherwise(() => paramObj.name),
2051
+ type: match(paramObj.in).with("header", () => "Header").with("query", () => "Query").with("path", () => "Path").run(),
2052
+ zodSchema: zodSchemaName,
2053
+ parameterObject: paramObj,
2054
+ parameterSortingEnumSchemaName
2055
+ };
2056
+ }
2057
+
2058
+ //#endregion
2059
+ //#region src/generators/core/endpoints/getEndpointsFromOpenAPIDoc.ts
2060
+ function getEndpointsFromOpenAPIDoc(resolver, profiler) {
2061
+ const endpoints = [];
2062
+ const p = profiler ?? new Profiler(false);
2063
+ for (const context of resolver.getOperationContexts()) endpoints.push(buildEndpointFromOperationContext(resolver, context, p));
2064
+ return endpoints;
2065
+ }
2066
+ function buildEndpointFromOperationContext(resolver, context, profiler) {
2067
+ const p = profiler ?? new Profiler(false);
2068
+ const { path, method, operation, operationName, isUniqueOperationName, tag, parameters, responses } = context;
2069
+ const invalidOperationId = operation.operationId && operation.operationId !== invalidVariableNameCharactersToCamel(operation.operationId);
2070
+ if (operation.operationId && invalidOperationId) resolver.validationErrors.push(getInvalidOperationIdError(operation.operationId));
2071
+ const endpoint = {
2072
+ method,
2073
+ path: replaceHyphenatedPath(path),
2074
+ operationName,
2075
+ description: operation.description,
2076
+ summary: operation.summary,
2077
+ tags: operation.tags?.map(formatTag),
2078
+ requestFormat: JSON_APPLICATION_FORMAT,
2079
+ parameters: [],
2080
+ response: "",
2081
+ errors: [],
2082
+ responseStatusCodes: [],
2083
+ mediaUpload: !!operation["x-media-upload"],
2084
+ mediaDownload: !!operation["x-media-download"]
2085
+ };
2086
+ p.runSync("endpoints.requestBody", () => {
2087
+ if (operation.requestBody) {
2088
+ const body = getEndpointBody({
2089
+ resolver,
2090
+ operation,
2091
+ operationName,
2092
+ isUniqueOperationName,
2093
+ tag
2094
+ });
2095
+ if (body) {
2096
+ endpoint.parameters.push(body.endpointParameter);
2097
+ endpoint.requestFormat = body.requestFormat;
2098
+ }
2099
+ }
2100
+ });
2101
+ p.runSync("endpoints.params", () => {
2102
+ for (const param of parameters) {
2103
+ const endpointParameter = getEndpointParameter({
2104
+ resolver,
2105
+ param,
2106
+ operationName,
2107
+ isUniqueOperationName,
2108
+ tag
2109
+ });
2110
+ if (endpointParameter) endpoint.parameters.push(endpointParameter);
2111
+ }
2112
+ });
2113
+ p.runSync("endpoints.pathParams", () => {
2114
+ const missingPathParameters = getMissingPathParameters(endpoint);
2115
+ missingPathParameters.forEach((pathParam) => {
2116
+ endpoint.parameters.push(pathParam);
2117
+ });
2118
+ if (missingPathParameters.length > 0) resolver.validationErrors.push(getMissingPathParameterError(missingPathParameters, path));
2119
+ });
2120
+ p.runSync("endpoints.responses", () => {
2121
+ for (const responseData of responses) {
2122
+ const { statusCode, responseObj, matchingMediaType, schema } = responseData;
2123
+ endpoint.responseStatusCodes.push(statusCode);
2124
+ let responseZodSchema;
2125
+ if (matchingMediaType) endpoint.responseFormat = matchingMediaType;
2126
+ else {
2127
+ responseZodSchema = VOID_SCHEMA;
2128
+ if (statusCode === "200") resolver.validationErrors.push(getInvalidStatusCodeError({
2129
+ received: "200",
2130
+ expected: "204"
2131
+ }, operation, endpoint));
2132
+ }
2133
+ if (schema) responseZodSchema = resolveEndpointZodSchema({
2134
+ resolver,
2135
+ schema,
2136
+ meta: { isRequired: true },
2137
+ tag,
2138
+ fallbackName: isReferenceObject(schema) ? void 0 : getResponseZodSchemaName({
2139
+ statusCode,
2140
+ operationName,
2141
+ isUniqueOperationName,
2142
+ tag
2143
+ }),
2144
+ composeBeforeResolve: false
2145
+ });
2146
+ if (responseZodSchema) {
2147
+ const status = Number(statusCode);
2148
+ if (isMainResponseStatus(status) && !endpoint.response) {
2149
+ endpoint.response = responseZodSchema;
2150
+ endpoint.responseObject = responseObj;
2151
+ endpoint.responseDescription = responseObj?.description;
2152
+ } else if (statusCode !== "default" && isErrorStatus(status)) endpoint.errors.push({
2153
+ zodSchema: responseZodSchema,
2154
+ status,
2155
+ description: responseObj?.description
2156
+ });
2157
+ }
2158
+ }
2159
+ });
2160
+ if (!endpoint.response) endpoint.response = VOID_SCHEMA;
2161
+ p.runSync("endpoints.statusValidation", () => {
2162
+ const mainStatusCodes = Object.keys(operation.responses).map(Number).filter(isMainResponseStatus);
2163
+ if (mainStatusCodes.length > 1) resolver.validationErrors.push(getMultipleSuccessStatusCodesError(mainStatusCodes.map(String), operation, endpoint));
2164
+ });
2165
+ p.runSync("endpoints.acl", () => {
2166
+ endpoint.acl = getEndpointAcl({
2167
+ resolver,
2168
+ endpoint,
2169
+ operation
2170
+ });
2171
+ });
2172
+ if (operation.security?.[0].Authorization && !endpoint.responseStatusCodes.includes("401")) resolver.validationErrors.push(getMissingStatusCodeError("401", operation, endpoint));
2173
+ if (endpoint.acl?.[0] && !endpoint.responseStatusCodes.includes("403")) resolver.validationErrors.push(getMissingStatusCodeError("403", operation, endpoint));
2174
+ return endpoint;
2175
+ }
2176
+ function getMissingPathParameters(endpoint) {
2177
+ return [...endpoint.path.matchAll(/:([a-zA-Z0-9_]+)/g)].map((param) => param[1]).filter((pathParam) => endpoint.parameters.findIndex(({ name }) => name === pathParam) === -1).map((name) => getPathParameterFromName(name));
2178
+ }
2179
+ function getPathParameterFromName(name) {
2180
+ return {
2181
+ name,
2182
+ type: "Path",
2183
+ zodSchema: STRING_SCHEMA,
2184
+ parameterObject: {
2185
+ name,
2186
+ required: true,
2187
+ in: "path",
2188
+ schema: { type: "string" }
2189
+ }
2190
+ };
2191
+ }
2192
+
2193
+ //#endregion
2194
+ //#region src/generators/utils/object.utils.ts
2195
+ /** Pick given properties in object */
2196
+ function pick(obj, paths) {
2197
+ const result = {};
2198
+ Object.keys(obj).forEach((key) => {
2199
+ if (!paths.includes(key)) return;
2200
+ result[key] = obj[key];
2201
+ });
2202
+ return result;
2203
+ }
2204
+ /**
2205
+ * Deep merge two or more objects/arrays recursively.
2206
+ * Arrays are concatenated, objects are merged recursively.
2207
+ * Later arguments take precedence over earlier ones.
2208
+ * Returns a new object/array without mutating the originals.
2209
+ */
2210
+ function deepMerge(source, ...sources) {
2211
+ if (sources.length === 0) return source;
2212
+ let result = source;
2213
+ for (const source of sources) result = mergeTwoValues(result, source);
2214
+ return result;
2215
+ }
2216
+ /**
2217
+ * Merge two values recursively
2218
+ */
2219
+ function mergeTwoValues(target, source) {
2220
+ if (source === null || source === void 0) return target;
2221
+ if (target === null || target === void 0) return deepClone(source);
2222
+ if (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];
2223
+ if (isPlainObject(target) && isPlainObject(source)) {
2224
+ const result = {};
2225
+ for (const [key, targetValue] of Object.entries(target)) result[key] = deepClone(targetValue);
2226
+ for (const [key, sourceValue] of Object.entries(source)) {
2227
+ const targetValue = result[key];
2228
+ if (sourceValue === void 0) continue;
2229
+ else if (sourceValue === null) result[key] = sourceValue;
2230
+ else if (isPlainObject(targetValue) && isPlainObject(sourceValue)) result[key] = mergeTwoValues(targetValue, sourceValue);
2231
+ else if (Array.isArray(targetValue) && Array.isArray(sourceValue)) result[key] = [...targetValue, ...sourceValue];
2232
+ else result[key] = deepClone(sourceValue);
2233
+ }
2234
+ return result;
2235
+ }
2236
+ return deepClone(source);
2237
+ }
2238
+ /**
2239
+ * Deep clone an object or array to avoid reference sharing.
2240
+ * Helper function for deepMerge.
2241
+ */
2242
+ function deepClone(obj) {
2243
+ if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
2244
+ if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
2245
+ if (isPlainObject(obj)) {
2246
+ const result = {};
2247
+ for (const [key, value] of Object.entries(obj)) result[key] = deepClone(value);
2248
+ return result;
2249
+ }
2250
+ return obj;
2251
+ }
2252
+ /**
2253
+ * Check if a value is a plain object (not an array, Date, etc.)
2254
+ */
2255
+ function isPlainObject(obj) {
2256
+ return obj !== null && typeof obj === "object" && !Array.isArray(obj) && Object.prototype.toString.call(obj) === "[object Object]";
2257
+ }
2258
+
2259
+ //#endregion
2260
+ //#region src/generators/const/js.const.ts
2261
+ const RESERVED_WORDS = [
2262
+ "break",
2263
+ "case",
2264
+ "catch",
2265
+ "class",
2266
+ "const",
2267
+ "continue",
2268
+ "debugger",
2269
+ "default",
2270
+ "delete",
2271
+ "do",
2272
+ "else",
2273
+ "export",
2274
+ "extends",
2275
+ "false",
2276
+ "finally",
2277
+ "for",
2278
+ "function",
2279
+ "if",
2280
+ "import",
2281
+ "in",
2282
+ "instanceof",
2283
+ "new",
2284
+ "null",
2285
+ "return",
2286
+ "super",
2287
+ "switch",
2288
+ "this",
2289
+ "throw",
2290
+ "true",
2291
+ "try",
2292
+ "typeof",
2293
+ "var",
2294
+ "void",
2295
+ "while",
2296
+ "with"
2297
+ ];
2298
+
2299
+ //#endregion
2300
+ //#region src/generators/utils/operation.utils.ts
2301
+ function isOperationExcluded(operation, options) {
2302
+ const isDeprecated = operation.deprecated && !options.withDeprecatedEndpoints;
2303
+ const isIncluded = isTagIncluded(getOperationTag(operation, options), options);
2304
+ return isDeprecated || !isIncluded;
2305
+ }
2306
+ function getOperationName({ path, method, operation, options, tag, keepOperationTag, keepOperationPrefix }) {
2307
+ const pathOperationName = `${method}${pathToVariableName(path)}`;
2308
+ let operationName = operation.operationId ? invalidVariableNameCharactersToCamel(operation.operationId) : pathOperationName;
2309
+ if (options.removeOperationPrefixEndingWith && keepOperationPrefix) operationName = operationName.split(options.removeOperationPrefixEndingWith).map((split, index) => index === 0 ? split : capitalize(split)).join("");
2310
+ else if (options.removeOperationPrefixEndingWith && !keepOperationPrefix) {
2311
+ const regex = new RegExp(`^.*${options.removeOperationPrefixEndingWith}`);
2312
+ operationName = operationName.replace(regex, "");
2313
+ }
2314
+ if (options.tsNamespaces && !keepOperationTag) {
2315
+ const operationNameWithoutTag = removeWord(operationName, tag);
2316
+ if (operationNameWithoutTag === "") operationName = method.toLowerCase();
2317
+ else if (!RESERVED_WORDS.includes(operationNameWithoutTag)) operationName = operationNameWithoutTag;
2318
+ }
2319
+ return RESERVED_WORDS.includes(operationName) ? pathOperationName : operationName;
2320
+ }
2321
+ function getUniqueOperationName({ operationsByTag, ...params }) {
2322
+ const { operation, options } = params;
2323
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
2324
+ const operationName = (keepOperationTag) => {
2325
+ const name = getOperationName({
2326
+ ...params,
2327
+ tag,
2328
+ keepOperationTag
2329
+ });
2330
+ if (operationsByTag[tag].filter((operation) => getOperationName({
2331
+ ...params,
2332
+ operation,
2333
+ tag,
2334
+ keepOperationTag
2335
+ }) === name).length === 1) return name;
2336
+ };
2337
+ return operationName() ?? operationName(true) ?? getOperationName({
2338
+ ...params,
2339
+ tag,
2340
+ keepOperationTag: true,
2341
+ keepOperationPrefix: true
2342
+ });
2343
+ }
2344
+ function getUniqueOperationNamesWithoutSplitByTags(openApiDoc, operationsByTag, options) {
2345
+ const operationNames = [];
2346
+ for (const path in openApiDoc.paths) {
2347
+ if (isPathExcluded(path, options)) continue;
2348
+ const pathItemObj = openApiDoc.paths[path];
2349
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2350
+ for (const method in pathItem) {
2351
+ const operation = pathItem[method];
2352
+ if (!operation || isOperationExcluded(operation, options)) continue;
2353
+ const operationName = getUniqueOperationName({
2354
+ path,
2355
+ method,
2356
+ operation,
2357
+ operationsByTag,
2358
+ options
2359
+ });
2360
+ operationNames.push(operationName);
2361
+ }
2362
+ }
2363
+ return operationNames;
2364
+ }
2365
+ function getOperationsByTag(openApiDoc, options) {
2366
+ const operationsByTag = {};
2367
+ for (const path in openApiDoc.paths) {
2368
+ if (isPathExcluded(path, options)) continue;
2369
+ const pathItemObj = openApiDoc.paths[path];
2370
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2371
+ for (const method in pathItem) {
2372
+ const operation = pathItem[method];
2373
+ if (!operation || isOperationExcluded(operation, options)) continue;
2374
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
2375
+ if (!operationsByTag[tag]) operationsByTag[tag] = [];
2376
+ operationsByTag[tag].push(operation);
2377
+ }
2378
+ }
2379
+ return operationsByTag;
2380
+ }
2381
+
2382
+ //#endregion
2383
+ //#region src/generators/core/openapi/getOpenAPISchemaDependencyGraph.ts
2384
+ function getOpenAPISchemaDependencyGraph(schemaRef, getSchemaByRef) {
2385
+ const refsDependencyGraph = getRefsDependencyGraph(schemaRef, getSchemaByRef);
2386
+ return {
2387
+ refsDependencyGraph,
2388
+ deepDependencyGraph: getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph)
2389
+ };
2390
+ }
2391
+ function getRefsDependencyGraph(schemaRef, getSchemaByRef) {
2392
+ const visitedRefs = {};
2393
+ const refsDependencyGraph = {};
2394
+ schemaRef.forEach((ref) => getSchemaRefsDependencyGraph({
2395
+ schema: getSchemaByRef(ref),
2396
+ fromRef: ref,
2397
+ getSchemaByRef,
2398
+ visitedRefs,
2399
+ refsDependencyGraph
2400
+ }));
2401
+ return refsDependencyGraph;
2402
+ }
2403
+ function getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph) {
2404
+ const visitedDeepRefs = {};
2405
+ const deepDependencyGraph = {};
2406
+ const visit = (dep, ref) => {
2407
+ deepDependencyGraph[ref].add(dep);
2408
+ if (refsDependencyGraph[dep] && ref !== dep) refsDependencyGraph[dep].forEach((transitive) => {
2409
+ const refName = `${ref}__${transitive}`;
2410
+ if (visitedDeepRefs[refName]) return;
2411
+ visitedDeepRefs[refName] = true;
2412
+ visit(transitive, ref);
2413
+ });
2414
+ };
2415
+ schemaRef.forEach((ref) => {
2416
+ const deps = refsDependencyGraph[ref];
2417
+ if (!deps) return;
2418
+ if (!deepDependencyGraph[ref]) deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
2419
+ deps.forEach((dep) => visit(dep, ref));
2420
+ });
2421
+ return deepDependencyGraph;
2422
+ }
2423
+ function getSchemaRefsDependencyGraph({ schema, fromRef, getSchemaByRef, visitedRefs = {}, refsDependencyGraph = {} }) {
2424
+ const onSchema = (callbackData) => {
2425
+ if (callbackData.type !== "reference" || !callbackData.data) return;
2426
+ const { schema, data } = callbackData;
2427
+ if (!refsDependencyGraph[data.fromRef]) refsDependencyGraph[data.fromRef] = /* @__PURE__ */ new Set();
2428
+ refsDependencyGraph[data.fromRef].add(schema.$ref);
2429
+ if (visitedRefs[schema.$ref]) return true;
2430
+ visitedRefs[data.fromRef] = true;
2431
+ iterateSchema(getSchemaByRef(schema.$ref), {
2432
+ data: { fromRef: schema.$ref },
2433
+ onSchema
2434
+ });
2435
+ };
2436
+ iterateSchema(schema, {
2437
+ data: { fromRef },
2438
+ onSchema
2439
+ });
2440
+ return {
2441
+ visitedRefs,
2442
+ refsDependencyGraph
2443
+ };
2444
+ }
2445
+
2446
+ //#endregion
2447
+ //#region src/generators/core/openapi/getSchemaRefObjs.ts
2448
+ function getSchemaRefObjs(resolver, schema, schemaInfo) {
2449
+ const schemaRefObjs = [];
2450
+ const onSchema = (data) => {
2451
+ if (data.type === "reference") schemaRefObjs.push(data.schema);
2452
+ else if (isReferenceObject(data.parentSchema)) {
2453
+ if (data.type === "property") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and properties`));
2454
+ else if (data.type === "additionalProperties") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and additionalProperties`));
2455
+ else if (data.type === "array") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} is both reference and array schema`));
2456
+ else if (data.type === "composite") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and composite keyword`));
2457
+ }
2458
+ };
2459
+ iterateSchema(schema, { onSchema });
2460
+ return schemaRefObjs;
2461
+ }
2462
+ function getDeepSchemaRefObjs(resolver, schemaRefs) {
2463
+ return schemaRefs.map((schemaRef) => autocorrectRef(schemaRef.$ref)).reduce((acc, schemaRef) => {
2464
+ const refs = resolver.dependencyGraph.deepDependencyGraph[schemaRef];
2465
+ return [
2466
+ ...acc,
2467
+ schemaRef,
2468
+ ...Array.from(refs ?? [])
2469
+ ];
2470
+ }, []);
2471
+ }
2472
+
2473
+ //#endregion
2474
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.ts
2475
+ function resolveExtractedEnumZodSchemaNames(resolver) {
2476
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2477
+ const mostCommonLastSegment = getMostCommonAdjacentCombinationSplit(enumData.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - 1]).filter(Boolean));
2478
+ if (!mostCommonLastSegment) throw new Error(`No common last segment found for enum: ${enumData.code}`);
2479
+ enumData.zodSchemaName = getEnumZodSchemaName(mostCommonLastSegment, resolver.options.enumSuffix, resolver.options.schemaSuffix);
2480
+ });
2481
+ let nameResolutionIterationsCounter = 0;
2482
+ while (nameResolutionIterationsCounter < 5) {
2483
+ if (allExtractedEnumZodSchemaNamesAreUnique(resolver)) break;
2484
+ additionalResolveExtractedEnumZodSchemaName(resolver, nameResolutionIterationsCounter + 2);
2485
+ nameResolutionIterationsCounter++;
2486
+ }
2487
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) resolver.extractedEnumZodSchemaData.filter((enumData) => !isUnique(resolver, enumData)).forEach((enumData) => {
2488
+ enumData.zodSchemaName = getEnumZodSchemaName(enumData.meta.zodSchemaNameSegments[0].map((name) => sanitizeName(capitalize(name))).join(""), resolver.options.enumSuffix, resolver.options.schemaSuffix);
2489
+ });
2490
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) throw new Error("Failed to resolve unique names for enum zod schemas");
2491
+ }
2492
+ function allExtractedEnumZodSchemaNamesAreUnique(resolver) {
2493
+ return resolver.extractedEnumZodSchemaData.every((enumData) => isUnique(resolver, enumData));
2494
+ }
2495
+ function additionalResolveExtractedEnumZodSchemaName(resolver, index) {
2496
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2497
+ const enumsDataWithSameName = resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName);
2498
+ if (enumsDataWithSameName.length === 1) return;
2499
+ suffixWithPreviousSegmentName(enumsDataWithSameName, index);
2500
+ });
2501
+ }
2502
+ function suffixWithPreviousSegmentName(enumsData, index = 2) {
2503
+ enumsData.forEach((data) => {
2504
+ const precedingLastFragments = data.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - index]).filter(Boolean);
2505
+ if (precedingLastFragments.length === 1) data.zodSchemaName = [sanitizeName(capitalize(precedingLastFragments[0])), data.zodSchemaName].filter(Boolean).join("");
2506
+ else {
2507
+ const secondLastFragmentSplit = getMostCommonAdjacentCombinationSplit(precedingLastFragments);
2508
+ data.zodSchemaName = [secondLastFragmentSplit ? sanitizeName(capitalize(secondLastFragmentSplit)) : "", data.zodSchemaName].filter(Boolean).join("");
2509
+ }
2510
+ });
2511
+ }
2512
+ function isUnique(resolver, enumData) {
2513
+ return resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName).length === 1;
2514
+ }
2515
+ function sanitizeName(name) {
2516
+ return name.replace(/(Dto|DTO|Response|Request)/g, "");
2517
+ }
2518
+
2519
+ //#endregion
2520
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.ts
2521
+ function resolveExtractedEnumZodSchemaTags(resolver) {
2522
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2523
+ const tags = getUniqueArray(enumData.meta.tags);
2524
+ enumData.tag = tags.length === 1 ? tags[0] : resolver.options.defaultTag;
2525
+ });
2526
+ }
2527
+
2528
+ //#endregion
2529
+ //#region src/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.ts
2530
+ function updateExtractedEnumZodSchemaData({ schema, nameSegments = [], includeSelf, ...params }) {
2531
+ if (includeSelf) handleExtractedEnumZodSchemaDataUpdate({
2532
+ schema,
2533
+ nameSegments,
2534
+ ...params
2535
+ });
2536
+ const onSchema = (data) => {
2537
+ if (data.type === "reference") return true;
2538
+ const segments = [...data.data?.nameSegments ?? []];
2539
+ if (data.type === "property") segments.push(data.propertyName);
2540
+ handleExtractedEnumZodSchemaDataUpdate({
2541
+ schema: data.schema,
2542
+ nameSegments: [...segments],
2543
+ ...params
2544
+ });
2545
+ };
2546
+ iterateSchema(schema, {
2547
+ data: { nameSegments },
2548
+ onSchema
2549
+ });
2550
+ }
2551
+ function handleExtractedEnumZodSchemaDataUpdate({ resolver, schema, schemaRef, schemaInfo, tags, nameSegments = [] }) {
2552
+ if (!schema || isReferenceObject(schema) || !schema.enum) return;
2553
+ const code = getEnumZodSchemaCode(schema);
2554
+ const enumZodSchema = resolver.extractedEnumZodSchemaData.find((data) => data.code === code);
2555
+ if (enumZodSchema) {
2556
+ enumZodSchema.meta.zodSchemaNameSegments.push(nameSegments);
2557
+ enumZodSchema.meta.tags.push(...tags);
2558
+ enumZodSchema.meta.schemaRefs.push(...schemaRef ? [schemaRef] : []);
2559
+ enumZodSchema.meta.schemas.push(...schema ? [schema] : []);
2560
+ } else resolver.extractedEnumZodSchemaData.push({
2561
+ code,
2562
+ meta: {
2563
+ zodSchemaNameSegments: [nameSegments],
2564
+ tags: [...tags],
2565
+ schemaRefs: schemaRef ? [schemaRef] : [],
2566
+ schemas: schema ? [schema] : []
2567
+ }
2568
+ });
2569
+ resolver.validationErrors.push(getNotAllowedInlineEnumError(schemaRef ? `${getSchemaNameByRef(schemaRef)}.${nameSegments[nameSegments.length - 1]}` : schemaInfo ?? nameSegments.join(".")));
2570
+ }
2571
+
2572
+ //#endregion
2573
+ //#region src/generators/core/zod/getZodSchemasFromOpenAPIDoc.ts
2574
+ function getZodSchemasFromOpenAPIDoc(resolver, profiler) {
2575
+ const p = profiler ?? new Profiler(false);
2576
+ const zodSchemas = {};
2577
+ const enumZodSchemas = {};
2578
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => p.runSync("zod.extract.schemaEntry", () => {
2579
+ const schemaData = resolver.getSchemaDataByName(name);
2580
+ if (resolver.options.excludeRedundantZodSchemas && (!schemaData || schemaData.deepRefOperations.length === 0 && schemaData.tags.length === 0)) return;
2581
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
2582
+ if (zodSchemas[zodSchemaName]) return;
2583
+ const tag = resolver.getTagByZodSchemaName(zodSchemaName);
2584
+ const schemaObject = resolver.resolveObject(schema);
2585
+ if (schemaObject.enum) enumZodSchemas[zodSchemaName] = getEnumZodSchemaCode(schemaObject);
2586
+ else zodSchemas[zodSchemaName] = p.runSync("zod.extract.schemaToCode", () => getZodSchema({
2587
+ schema,
2588
+ resolver,
2589
+ tag
2590
+ }).getCodeString(tag));
2591
+ }));
2592
+ return {
2593
+ zodSchemas,
2594
+ enumZodSchemas
2595
+ };
2596
+ }
2597
+ function getEnumZodSchemasFromOpenAPIDoc(resolver) {
2598
+ const enumZodSchemas = [];
2599
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => {
2600
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
2601
+ const schemaObject = resolver.resolveObject(schema);
2602
+ if (!enumZodSchemas.find((enumZodSchema) => enumZodSchema.zodSchemaName === zodSchemaName) && schemaObject.enum) enumZodSchemas.push({
2603
+ zodSchemaName,
2604
+ code: getEnumZodSchemaCode(schemaObject)
2605
+ });
2606
+ });
2607
+ return enumZodSchemas;
2608
+ }
2609
+
2610
+ //#endregion
2611
+ //#region src/generators/core/SchemaResolver.class.ts
2612
+ var SchemaResolver = class {
2613
+ schemaData = [];
2614
+ zodSchemaData = [];
2615
+ compositeZodSchemaData = [];
2616
+ schemaRefs;
2617
+ schemaByRef = /* @__PURE__ */ new Map();
2618
+ schemaDataByRef = /* @__PURE__ */ new Map();
2619
+ schemaDataByName = /* @__PURE__ */ new Map();
2620
+ refByZodSchemaName = /* @__PURE__ */ new Map();
2621
+ zodSchemaDataByName = /* @__PURE__ */ new Map();
2622
+ compositeByCode = /* @__PURE__ */ new Map();
2623
+ compositeSchemaByZodSchemaName = /* @__PURE__ */ new Map();
2624
+ dependencyGraph;
2625
+ enumZodSchemas = [];
2626
+ extractedEnumZodSchemaData = [];
2627
+ operationsByTag = {};
2628
+ operationNames = [];
2629
+ operationNameCounts = /* @__PURE__ */ new Map();
2630
+ operationContexts = [];
2631
+ validationErrors = [];
2632
+ get docSchemas() {
2633
+ return this.openApiDoc.components?.schemas ?? {};
2634
+ }
2635
+ constructor(openApiDoc, options, profiler) {
2636
+ this.openApiDoc = openApiDoc;
2637
+ this.options = options;
2638
+ this.profiler = profiler;
2639
+ this.schemaRefs = Object.keys(this.docSchemas).map(getSchemaRef);
2640
+ this.dependencyGraph = getOpenAPISchemaDependencyGraph(this.schemaRefs, this.getSchemaByRef.bind(this));
2641
+ this.enumZodSchemas = getEnumZodSchemasFromOpenAPIDoc(this);
2642
+ this.operationsByTag = getOperationsByTag(openApiDoc, options);
2643
+ this.operationNames = getUniqueOperationNamesWithoutSplitByTags(openApiDoc, this.operationsByTag, options);
2644
+ for (const name of this.operationNames) this.operationNameCounts.set(name, (this.operationNameCounts.get(name) ?? 0) + 1);
2645
+ this.initialize();
2646
+ }
2647
+ getSchemaByRef(ref) {
2648
+ const correctRef = autocorrectRef(ref);
2649
+ const cachedSchema = this.schemaByRef.get(correctRef);
2650
+ if (cachedSchema) return cachedSchema;
2651
+ const schema = this.docSchemas[getSchemaNameByRef(correctRef)];
2652
+ this.schemaByRef.set(correctRef, schema);
2653
+ return schema;
2654
+ }
2655
+ getSchemaDataByName(name) {
2656
+ return this.schemaDataByName.get(name);
2657
+ }
2658
+ getZodSchemaNameByRef(ref) {
2659
+ const zodSchemaName = this.getSchemaDataByRef(autocorrectRef(ref))?.zodSchemaName ?? this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === ref)?.zodSchemaName;
2660
+ if (!zodSchemaName) throw new Error(`Zod schema not found for ref: ${ref}`);
2661
+ return zodSchemaName;
2662
+ }
2663
+ getRefByZodSchemaName(zodSchemaName) {
2664
+ return this.refByZodSchemaName.get(zodSchemaName);
2665
+ }
2666
+ getTagByZodSchemaName(zodSchemaName) {
2667
+ if (!this.options.splitByTags) return this.options.defaultTag;
2668
+ if (this.options.modelsInCommon) return formatTag(this.options.defaultTag);
2669
+ const extractedEnumZodSchema = this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === zodSchemaName);
2670
+ if (extractedEnumZodSchema) return formatTag(extractedEnumZodSchema.tag ?? this.options.defaultTag);
2671
+ const schemaRef = this.getRefByZodSchemaName(zodSchemaName);
2672
+ const tags = getUniqueArray(schemaRef ? this.getSchemaDataByRef(schemaRef)?.tags ?? [] : [], this.zodSchemaDataByName.get(zodSchemaName)?.tags ?? []);
2673
+ return formatTag((tags.length === 1 ? tags[0] : this.options.defaultTag) ?? this.options.defaultTag);
2674
+ }
2675
+ getCodeByZodSchemaName(name) {
2676
+ return this.zodSchemaDataByName.get(name)?.code;
2677
+ }
2678
+ getZodSchemaNamesByCompositeCode(code) {
2679
+ return this.compositeByCode.get(code)?.zodSchemas.map((schema) => schema.zodSchemaName);
2680
+ }
2681
+ setZodSchema(name, code, tag) {
2682
+ const zodSchema = this.zodSchemaDataByName.get(name);
2683
+ if (zodSchema) {
2684
+ zodSchema.code = code;
2685
+ zodSchema.tags = (zodSchema.tags ?? []).concat(tag);
2686
+ } else {
2687
+ const newZodSchemaData = {
2688
+ zodSchemaName: name,
2689
+ code,
2690
+ tags: [tag]
2691
+ };
2692
+ this.zodSchemaData.push(newZodSchemaData);
2693
+ this.zodSchemaDataByName.set(name, newZodSchemaData);
2694
+ }
2695
+ }
2696
+ addZodSchemaForCompositeCode(code, zodSchema, zodSchemaName, schema) {
2697
+ const compositeZodSchema = {
2698
+ zodSchemaName,
2699
+ zodSchema,
2700
+ schema
2701
+ };
2702
+ const compositeData = this.compositeByCode.get(code);
2703
+ if (compositeData) compositeData.zodSchemas.push(compositeZodSchema);
2704
+ else {
2705
+ const newCompositeData = {
2706
+ code,
2707
+ zodSchemas: [compositeZodSchema]
2708
+ };
2709
+ this.compositeZodSchemaData.push(newCompositeData);
2710
+ this.compositeByCode.set(code, newCompositeData);
2711
+ }
2712
+ this.compositeSchemaByZodSchemaName.set(zodSchemaName, {
2713
+ zodSchema,
2714
+ schema
2715
+ });
2716
+ }
2717
+ getCompositeZodSchemaByZodSchemaName(zodSchemaName) {
2718
+ return this.compositeSchemaByZodSchemaName.get(zodSchemaName)?.zodSchema;
2719
+ }
2720
+ getSchemaByCompositeZodSchemaName(compositeZodSchemaName) {
2721
+ return this.compositeSchemaByZodSchemaName.get(compositeZodSchemaName)?.schema;
2722
+ }
2723
+ getEnumZodSchemaDataByCode(code) {
2724
+ return this.enumZodSchemas.find((data) => data.code === code);
2725
+ }
2726
+ getExtractedEnumZodSchemaDataByCode(code) {
2727
+ return this.extractedEnumZodSchemaData.find((data) => data.code === code);
2728
+ }
2729
+ getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef) {
2730
+ return this.extractedEnumZodSchemaData.reduce((acc, { zodSchemaName, meta }) => {
2731
+ if (zodSchemaName && meta.schemaRefs.includes(schemaRef)) return [...acc, zodSchemaName];
2732
+ return acc;
2733
+ }, []);
2734
+ }
2735
+ getZodSchemas() {
2736
+ const zodSchemas = {};
2737
+ for (const { zodSchemaName, code } of this.zodSchemaData) zodSchemas[zodSchemaName] = code;
2738
+ return zodSchemas;
2739
+ }
2740
+ getExtractedEnumZodSchemas() {
2741
+ const zodSchemas = {};
2742
+ for (const { zodSchemaName, code } of this.extractedEnumZodSchemaData) if (zodSchemaName) zodSchemas[zodSchemaName] = code;
2743
+ return zodSchemas;
2744
+ }
2745
+ resolveObject(obj) {
2746
+ return isReferenceObject(obj) ? this.getSchemaByRef(obj.$ref) : obj;
2747
+ }
2748
+ isSchemaCircular(ref) {
2749
+ return this.dependencyGraph.deepDependencyGraph[ref]?.has(ref);
2750
+ }
2751
+ getCircularSchemaChain(ref, currentRef = ref, chain = [], visited = []) {
2752
+ if (visited.includes(currentRef)) return [];
2753
+ visited.push(currentRef);
2754
+ if (this.dependencyGraph.refsDependencyGraph[currentRef]?.has(ref)) return [
2755
+ ...chain,
2756
+ currentRef,
2757
+ ref
2758
+ ];
2759
+ return Array.from(this.dependencyGraph.refsDependencyGraph[currentRef]?.values() ?? []).flatMap((childRef) => {
2760
+ const childChain = this.getCircularSchemaChain(ref, childRef, chain, visited);
2761
+ return childChain.length > 0 ? [currentRef, ...childChain] : childChain;
2762
+ });
2763
+ }
2764
+ getBaseUrl() {
2765
+ const serverUrl = this.openApiDoc.servers?.[0]?.url;
2766
+ if (this.options.baseUrl === "" && serverUrl) return serverUrl;
2767
+ return this.options.baseUrl;
2768
+ }
2769
+ isOperationNameUnique(operationName) {
2770
+ return (this.operationNameCounts.get(operationName) ?? 0) <= 1;
2771
+ }
2772
+ getOperationContexts() {
2773
+ return this.operationContexts;
2774
+ }
2775
+ getZodSchemaObj(zodSchemaName) {
2776
+ const ref = this.getRefByZodSchemaName(zodSchemaName);
2777
+ if (ref) return this.getSchemaByRef(ref);
2778
+ const schema = this.getSchemaByCompositeZodSchemaName(zodSchemaName);
2779
+ if (schema) return schema;
2780
+ const enumZodSchemaData = this.getExtractedEnumZodSchemaDataByName(zodSchemaName);
2781
+ if (enumZodSchemaData) {
2782
+ const schemaObject = {};
2783
+ for (const schema of enumZodSchemaData.meta.schemas) Object.assign(schemaObject, this.resolveObject(schema));
2784
+ return schemaObject;
2785
+ }
2786
+ }
2787
+ getSchemaDataByRef(ref) {
2788
+ return this.schemaDataByRef.get(ref);
2789
+ }
2790
+ getExtractedEnumZodSchemaDataByName(enumZodSchemaName) {
2791
+ return this.extractedEnumZodSchemaData.find(({ zodSchemaName }) => zodSchemaName === enumZodSchemaName);
2792
+ }
2793
+ initialize() {
2794
+ const p = this.profiler ?? new Profiler(false);
2795
+ p.runSync("resolver.init.seedSchemas", () => {
2796
+ this.schemaRefs.forEach((ref) => {
2797
+ const correctRef = autocorrectRef(ref);
2798
+ const name = getSchemaNameByRef(correctRef);
2799
+ const zodSchemaName = getZodSchemaName(name, this.options.schemaSuffix);
2800
+ const data = {
2801
+ ref: correctRef,
2802
+ name,
2803
+ zodSchemaName,
2804
+ tags: [],
2805
+ deepRefOperations: []
2806
+ };
2807
+ this.schemaData.push(data);
2808
+ this.schemaDataByRef.set(correctRef, data);
2809
+ this.schemaDataByName.set(name, data);
2810
+ this.refByZodSchemaName.set(zodSchemaName, correctRef);
2811
+ });
2812
+ });
2813
+ p.runSync("resolver.init.operationsLoop", () => {
2814
+ for (const path in this.openApiDoc.paths) {
2815
+ if (isPathExcluded(path, this.options)) continue;
2816
+ const pathItemObj = this.openApiDoc.paths[path];
2817
+ const pathParameters = this.getParameters(pathItemObj.parameters ?? []);
2818
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2819
+ for (const method in pathItem) {
2820
+ const operation = pathItem[method];
2821
+ if (!operation || isOperationExcluded(operation, this.options)) continue;
2822
+ const tag = getOperationTag(operation, this.options);
2823
+ const operationName = getUniqueOperationName({
2824
+ path,
2825
+ method,
2826
+ operation,
2827
+ operationsByTag: this.operationsByTag,
2828
+ options: this.options
2829
+ });
2830
+ const isUniqueOperationName = this.isOperationNameUnique(operationName);
2831
+ const parameters = p.runSync("resolver.init.parameters.mergeResolve", () => Object.entries({
2832
+ ...pathParameters,
2833
+ ...this.getParameters(operation.parameters ?? [])
2834
+ }).map(([, param]) => this.resolveObject(param)));
2835
+ const responses = p.runSync("resolver.init.responses.prepare", () => Object.entries(operation.responses).map(([statusCode, response]) => {
2836
+ const responseObj = this.resolveObject(response);
2837
+ const matchingMediaType = Object.keys(responseObj?.content ?? {}).find(isMediaTypeAllowed);
2838
+ return {
2839
+ statusCode,
2840
+ responseObj,
2841
+ matchingMediaType,
2842
+ schema: matchingMediaType ? responseObj.content?.[matchingMediaType]?.schema : void 0
2843
+ };
2844
+ }));
2845
+ const zodSchemaOperationName = snakeToCamel(getZodSchemaOperationName(operationName, isUniqueOperationName, tag));
2846
+ const schemaRefObjs = [];
2847
+ p.runSync("resolver.init.parameters.refs", () => {
2848
+ parameters.forEach((parameter) => {
2849
+ const parameterObject = this.resolveObject(parameter);
2850
+ const parameterSchema = parameterObject.schema;
2851
+ const schemaInfo = `Operation ${operation.operationId ?? path} parameter ${parameterObject.name}`;
2852
+ schemaRefObjs.push(...getSchemaRefObjs(this, parameterSchema, schemaInfo));
2853
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2854
+ resolver: this,
2855
+ schema: parameterSchema,
2856
+ schemaInfo,
2857
+ tags: [tag],
2858
+ nameSegments: [zodSchemaOperationName, parameterObject.name],
2859
+ includeSelf: true
2860
+ });
2861
+ });
2862
+ });
2863
+ p.runSync("resolver.init.requestBody.refs", () => {
2864
+ if (operation.requestBody) {
2865
+ const requestBodyObj = this.resolveObject(operation.requestBody);
2866
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
2867
+ if (matchingMediaType) {
2868
+ const matchingMediaSchema = requestBodyObj.content?.[matchingMediaType]?.schema;
2869
+ const schemaInfo = `Operation ${operation.operationId} request body`;
2870
+ schemaRefObjs.push(...getSchemaRefObjs(this, matchingMediaSchema, schemaInfo));
2871
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2872
+ resolver: this,
2873
+ schema: matchingMediaSchema,
2874
+ schemaInfo,
2875
+ tags: [tag],
2876
+ nameSegments: [getBodyZodSchemaName(zodSchemaOperationName)]
2877
+ });
2878
+ }
2879
+ }
2880
+ });
2881
+ p.runSync("resolver.init.responses.refs", () => {
2882
+ for (const responseData of responses) {
2883
+ if (!responseData.matchingMediaType) continue;
2884
+ const schemaInfo = `Operation ${operation.operationId} response body`;
2885
+ schemaRefObjs.push(...getSchemaRefObjs(this, responseData.schema, schemaInfo));
2886
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2887
+ resolver: this,
2888
+ schema: responseData.schema,
2889
+ schemaInfo,
2890
+ tags: [tag],
2891
+ nameSegments: [getResponseZodSchemaName({
2892
+ statusCode: responseData.statusCode,
2893
+ operationName,
2894
+ isUniqueOperationName,
2895
+ tag
2896
+ })]
2897
+ });
2898
+ }
2899
+ });
2900
+ const deepRefs = p.runSync("resolver.init.deepRefs", () => getDeepSchemaRefObjs(this, schemaRefObjs));
2901
+ const operationContext = {
2902
+ path,
2903
+ method,
2904
+ operation,
2905
+ tag,
2906
+ operationName,
2907
+ isUniqueOperationName,
2908
+ parameters,
2909
+ deepRefs,
2910
+ responses
2911
+ };
2912
+ this.operationContexts.push(operationContext);
2913
+ deepRefs.forEach((schemaRef) => {
2914
+ const schemaData = this.getSchemaDataByRef(schemaRef);
2915
+ if (schemaData) {
2916
+ schemaData.tags.push(tag);
2917
+ schemaData.deepRefOperations.push(operation);
2918
+ }
2919
+ });
2920
+ }
2921
+ }
2922
+ });
2923
+ if (this.options.extractEnums) p.runSync("resolver.init.enums.finalize", () => {
2924
+ this.schemaRefs.forEach((ref) => {
2925
+ const schemaRef = autocorrectRef(ref);
2926
+ updateExtractedEnumZodSchemaData({
2927
+ resolver: this,
2928
+ schema: this.getSchemaByRef(schemaRef),
2929
+ schemaRef,
2930
+ tags: this.getSchemaDataByRef(schemaRef)?.tags ?? [],
2931
+ nameSegments: [getSchemaNameByRef(schemaRef)]
2932
+ });
2933
+ });
2934
+ resolveExtractedEnumZodSchemaTags(this);
2935
+ this.handleDuplicateEnumZodSchemas();
2936
+ resolveExtractedEnumZodSchemaNames(this);
2937
+ });
2938
+ }
2939
+ handleDuplicateEnumZodSchemas() {
2940
+ const codes = new Set(this.enumZodSchemas.map(({ code }) => code));
2941
+ const duplicates = this.enumZodSchemas.filter(({ code }) => codes.has(code));
2942
+ this.schemaData.forEach((schemaData) => {
2943
+ const duplicateCode = duplicates.find(({ zodSchemaName }) => zodSchemaName === schemaData.zodSchemaName)?.code;
2944
+ if (!duplicateCode) return;
2945
+ const duplicate = this.extractedEnumZodSchemaData.find(({ code }) => code === duplicateCode);
2946
+ if (!duplicate || this.getEnumZodSchemaDataByCode(duplicate.code)?.zodSchemaName !== schemaData.zodSchemaName) return;
2947
+ schemaData.tags.push(...duplicate.meta.tags ?? []);
2948
+ duplicate.meta.schemaRefs.forEach((ref) => {
2949
+ if (!this.dependencyGraph.refsDependencyGraph[ref]) this.dependencyGraph.refsDependencyGraph[ref] = /* @__PURE__ */ new Set();
2950
+ this.dependencyGraph.refsDependencyGraph[ref].add(schemaData.ref);
2951
+ if (!this.dependencyGraph.deepDependencyGraph[ref]) this.dependencyGraph.deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
2952
+ this.dependencyGraph.deepDependencyGraph[ref].add(schemaData.ref);
2953
+ });
2954
+ });
2955
+ this.extractedEnumZodSchemaData.splice(0, this.extractedEnumZodSchemaData.length, ...this.extractedEnumZodSchemaData.filter(({ code }) => !codes.has(code)));
2956
+ }
2957
+ getParameters(parameters) {
2958
+ return Object.fromEntries((parameters ?? []).map((param) => [isReferenceObject(param) ? param.$ref : param.name, param]));
2959
+ }
2960
+ };
2961
+
2962
+ //#endregion
2963
+ //#region src/generators/utils/sort.utils.ts
2964
+ /** @see https://gist.github.com/RubyTuesdayDONO/5006455 */
2965
+ function topologicalSort(graph) {
2966
+ const sorted = [];
2967
+ const visited = {};
2968
+ function visit(name, ancestors) {
2969
+ if (!Array.isArray(ancestors)) ancestors = [];
2970
+ ancestors.push(name);
2971
+ visited[name] = true;
2972
+ if (graph[name]) graph[name].forEach((dep) => {
2973
+ if (ancestors.includes(dep)) return;
2974
+ if (visited[dep]) return;
2975
+ visit(dep, ancestors.slice(0));
2976
+ });
2977
+ if (!sorted.includes(name)) sorted.push(name);
2978
+ }
2979
+ Object.keys(graph).forEach((name) => visit(name, []));
2980
+ return sorted;
2981
+ }
2982
+ /** Sort object keys using a reference order array, sort keys not in reference order in lasts positions */
2983
+ function sortObjKeysFromArray(obj, orderedKeys) {
2984
+ const entries = Object.entries(obj);
2985
+ const sortedEntries = entries.filter(([key]) => orderedKeys.includes(key)).toSorted(([a], [b]) => orderedKeys.indexOf(a) - orderedKeys.indexOf(b)).concat(entries.filter(([key]) => !orderedKeys.includes(key)));
2986
+ return Object.fromEntries(sortedEntries);
2987
+ }
2988
+
2989
+ //#endregion
2990
+ //#region src/generators/core/zod/sortZodSchemasByTopology.ts
2991
+ function sortZodSchemasByTopology(resolver, zodSchemas) {
2992
+ return sortObjKeysFromArray(zodSchemas, topologicalSort(resolver.dependencyGraph.deepDependencyGraph).map((ref) => resolver.getZodSchemaNameByRef(ref)));
2993
+ }
2994
+
2995
+ //#endregion
2996
+ //#region src/generators/core/getDataFromOpenAPIDoc.ts
2997
+ function getDataFromOpenAPIDoc(openApiDoc, options, profiler) {
2998
+ const p = profiler ?? new Profiler(false);
2999
+ const resolver = p.runSync("data.resolver.init", () => new SchemaResolver(openApiDoc, options, p));
3000
+ const endpoints = p.runSync("data.endpoints.extract", () => getEndpointsFromOpenAPIDoc(resolver, p));
3001
+ const zodSchemasFromDocSchemas = p.runSync("data.zod.extract", () => getZodSchemasFromOpenAPIDoc(resolver, p));
3002
+ let zodSchemas = {
3003
+ ...zodSchemasFromDocSchemas.zodSchemas,
3004
+ ...resolver.getZodSchemas(),
3005
+ ...zodSchemasFromDocSchemas.enumZodSchemas
3006
+ };
3007
+ zodSchemas = p.runSync("data.zod.sortTopology", () => sortZodSchemasByTopology(resolver, zodSchemas));
3008
+ zodSchemas = {
3009
+ ...resolver.getExtractedEnumZodSchemas(),
3010
+ ...zodSchemas
3011
+ };
3012
+ return {
3013
+ resolver,
3014
+ data: p.runSync("data.splitByTags", () => splitDataByTags({
3015
+ resolver,
3016
+ endpoints,
3017
+ zodSchemas,
3018
+ options
3019
+ }))
3020
+ };
3021
+ }
3022
+ function splitDataByTags({ resolver, endpoints, zodSchemas, options }) {
3023
+ const data = /* @__PURE__ */ new Map();
3024
+ if (!options.splitByTags) {
3025
+ data.set(options.defaultTag, {
3026
+ endpoints,
3027
+ zodSchemas
3028
+ });
3029
+ return data;
3030
+ }
3031
+ endpoints.forEach((endpoint) => {
3032
+ getTagElement(getEndpointTag(endpoint, options), data).endpoints.push(endpoint);
3033
+ });
3034
+ Object.entries(zodSchemas).forEach(([zodSchemaName, zodSchemaCode]) => {
3035
+ const tag = options.modelsInCommon ? options.defaultTag : resolver.getTagByZodSchemaName(zodSchemaName);
3036
+ if (tag) getTagElement(tag, data).zodSchemas[zodSchemaName] = zodSchemaCode;
3037
+ });
3038
+ return data;
3039
+ }
3040
+ function getTagElement(tag, data) {
3041
+ if (!data.has(tag)) data.set(tag, {
3042
+ endpoints: [],
3043
+ zodSchemas: {}
3044
+ });
3045
+ return data.get(tag);
3046
+ }
3047
+
3048
+ //#endregion
3049
+ //#region src/generators/utils/file.utils.ts
3050
+ function getOutputFileName({ output, fileName }) {
3051
+ return `${output}/${fileName}`;
3052
+ }
3053
+ function hashString(input) {
3054
+ let hash = 2166136261;
3055
+ for (let i = 0; i < input.length; i += 1) {
3056
+ hash ^= input.charCodeAt(i);
3057
+ hash = Math.imul(hash, 16777619);
3058
+ }
3059
+ return (hash >>> 0).toString(16);
3060
+ }
3061
+ function writeFileWithDirSync(file, data) {
3062
+ const dir = path.dirname(file);
3063
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
3064
+ if (fs.existsSync(file)) {
3065
+ const existingData = fs.readFileSync(file, "utf-8");
3066
+ if (hashString(existingData) === hashString(data) && existingData === data) return;
3067
+ }
3068
+ fs.writeFileSync(file, data, "utf-8");
3069
+ }
3070
+ async function writeFile({ fileName, content }, options) {
3071
+ writeFileWithDirSync(fileName, options?.formatGeneratedFile ? await options.formatGeneratedFile({
3072
+ fileName,
3073
+ content
3074
+ }) : content);
3075
+ }
3076
+ async function writeGenerateFileData(filesData, options) {
3077
+ for (const file of filesData) await writeFile(file, options);
3078
+ }
3079
+
3080
+ //#endregion
3081
+ //#region src/generators/generate/generateAcl.ts
3082
+ function generateAcl({ resolver, data, tag }) {
3083
+ const aclData = getAclData({
3084
+ resolver,
3085
+ data,
3086
+ tag
3087
+ });
3088
+ if (!aclData) return;
3089
+ const { hasAdditionalAbilityImports, modelsImports, endpoints } = aclData;
3090
+ const caslAbilityTupleImport = {
3091
+ bindings: [...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject, CASL_ABILITY_BINDING.subject] : []],
3092
+ typeBindings: [CASL_ABILITY_BINDING.abilityTuple],
3093
+ from: CASL_ABILITY_IMPORT.from
3094
+ };
3095
+ const lines = [];
3096
+ lines.push(renderImport$4(caslAbilityTupleImport));
3097
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3098
+ lines.push("");
3099
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3100
+ type: GenerateType.Acl,
3101
+ tag,
3102
+ options: resolver.options
3103
+ })} {`);
3104
+ for (const endpoint of endpoints) {
3105
+ lines.push(renderAbilityFunction(endpoint));
3106
+ lines.push("");
3107
+ }
3108
+ if (resolver.options.tsNamespaces) lines.push("}");
3109
+ return lines.join("\n").trimEnd() + "\n";
3110
+ }
3111
+ function generateAppAcl({ resolver, data }) {
3112
+ const { appAbilitiesType, hasAdditionalAbilityImports, modelsImports } = getAppAbilitiesType({
3113
+ resolver,
3114
+ data
3115
+ });
3116
+ const caslAbilityTupleImport = {
3117
+ bindings: [],
3118
+ typeBindings: [
3119
+ CASL_ABILITY_BINDING.pureAbility,
3120
+ CASL_ABILITY_BINDING.abilityTuple,
3121
+ ...!appAbilitiesType ? [CASL_ABILITY_BINDING.subjectType] : [],
3122
+ ...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject] : []
3123
+ ],
3124
+ from: CASL_ABILITY_IMPORT.from,
3125
+ typeOnly: true
3126
+ };
3127
+ const lines = [];
3128
+ lines.push(renderImport$4(caslAbilityTupleImport));
3129
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3130
+ lines.push("");
3131
+ if (appAbilitiesType) {
3132
+ lines.push(`export type ${ACL_APP_ABILITIES} = `);
3133
+ for (const [action, subjects] of Object.entries(appAbilitiesType)) lines.push(`| ${CASL_ABILITY_BINDING.abilityTuple}<"${action}", ${subjects.join(" | ")}>`);
3134
+ } else lines.push(`export type ${ACL_APP_ABILITIES} = ${CASL_ABILITY_BINDING.abilityTuple}<string, ${CASL_ABILITY_BINDING.subjectType}>;`);
3135
+ lines.push("");
3136
+ lines.push(`export type AppAbility = PureAbility<${ACL_APP_ABILITIES}>;`);
3137
+ return lines.join("\n");
3138
+ }
3139
+ function renderImport$4(importData) {
3140
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
3141
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
3142
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
3143
+ }
3144
+ function renderAbilityFunction(endpoint) {
3145
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
3146
+ const hasConditions = hasAbilityConditions(endpoint);
3147
+ const lines = [];
3148
+ const abilityQuery = endpoint.method === "get" ? endpoint.mediaDownload ? `\`${getQueryName(endpoint)}\` query or \`${getQueryName(endpoint, true)}\` mutation` : `\`${getQueryName(endpoint)}\` query` : `\`${getQueryName(endpoint)}\` mutation`;
3149
+ lines.push("/**");
3150
+ lines.push(` * Use for ${abilityQuery} ability. ${hasConditions ? "For global ability, omit the object parameter." : ""}${getAbilityDescription(endpoint) ? "" : ""}`);
3151
+ if (getAbilityDescription(endpoint)) lines.push(` * @description ${getAbilityDescription(endpoint)}`);
3152
+ if (hasConditions) for (const propertyType of abilityConditionsTypes) lines.push(` * @param { ${(propertyType.type ?? "") + (propertyType.zodSchemaName ?? "")} } object.${propertyType.name} ${propertyType.name} from ${propertyType.info}`);
3153
+ lines.push(` * @returns { AbilityTuple } An ability tuple indicating the user's ability to use ${abilityQuery}`);
3154
+ lines.push(" */");
3155
+ lines.push(`export const ${getAbilityFunctionName(endpoint)} = (`);
3156
+ if (hasConditions) lines.push(` object?: { ${abilityConditionsTypes.map((propertyType) => `${propertyType.name}${propertyType.required ? "" : "?"}: ${(propertyType.type ?? "") + (propertyType.zodSchemaName ?? "")}, `).join("")} } `);
3157
+ lines.push(") => [");
3158
+ lines.push(` "${getAbilityAction(endpoint)}",`);
3159
+ lines.push(` ${hasConditions ? `object ? subject("${getAbilitySubject(endpoint)}", object) : "${getAbilitySubject(endpoint)}"` : `"${getAbilitySubject(endpoint)}"`}`);
3160
+ lines.push(`] as ${CASL_ABILITY_BINDING.abilityTuple}<"${getAbilityAction(endpoint)}", ${getAbilitySubjectTypes(endpoint).join(" | ")}>;`);
3161
+ return lines.join("\n");
3162
+ }
3163
+
3164
+ //#endregion
3165
+ //#region src/generators/const/buildConfigs.const.ts
3166
+ const BUILD_CONFIG_SUFFIX = "config";
3167
+
3168
+ //#endregion
3169
+ //#region src/generators/utils/generate/generate.configs.utils.ts
3170
+ function getBuilderConfigs({ data, tag, resolver }) {
3171
+ const endpoints = data.get(tag)?.endpoints;
3172
+ if (!endpoints || endpoints.length === 0) return {
3173
+ configs: [],
3174
+ hasZodImport: false,
3175
+ modelsImports: [],
3176
+ queriesImports: [],
3177
+ aclImports: []
3178
+ };
3179
+ const extendedEndpoints = endpoints.map((endpoint) => ({
3180
+ ...endpoint,
3181
+ pathSegments: getPathSegments(endpoint.path)
3182
+ }));
3183
+ const namedReadAllEndpoints = resolveBuilderConfigNames(extendedEndpoints.filter((endpoint) => isReadAllEndpoint(endpoint, resolver.options)));
3184
+ let hasZodImport = false;
3185
+ const importedZodSchemas = [];
3186
+ const importedEndpoints = [];
3187
+ const importedInfiniteEndpoints = [];
3188
+ const configs = Object.entries(namedReadAllEndpoints).map(([name, readAllEndpoint]) => {
3189
+ const columnsConfig = getColumnsConfig(resolver, readAllEndpoint);
3190
+ if (!columnsConfig) return;
3191
+ importedEndpoints.push(readAllEndpoint);
3192
+ importedInfiniteEndpoints.push(readAllEndpoint);
3193
+ if (columnsConfig.zodSchema) if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
3194
+ else hasZodImport = true;
3195
+ if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
3196
+ const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
3197
+ if (filter) importedZodSchemas.push(filter.zodSchema);
3198
+ const config = {
3199
+ name,
3200
+ title: capitalize(camelToSpaceSeparated(name.replace(/config$/i, ""))),
3201
+ readAll: {
3202
+ acl: getAclConfig(readAllEndpoint, resolver.options),
3203
+ paginated: getImportedQueryName(readAllEndpoint, resolver.options),
3204
+ infinite: resolver.options.infiniteQueries ? getImportedInfiniteQueryName(readAllEndpoint, resolver.options) : void 0,
3205
+ filters: getInputsConfig(resolver, filter),
3206
+ columns: columnsConfig.columns
3207
+ }
3208
+ };
3209
+ const readEndpoint = extendedEndpoints.find((endpoint) => isReadEndpoint(endpoint, readAllEndpoint));
3210
+ if (readEndpoint) {
3211
+ importedEndpoints.push(readEndpoint);
3212
+ let responseSchema = readEndpoint.response;
3213
+ if (isNamedZodSchema(responseSchema)) {
3214
+ importedZodSchemas.push(responseSchema);
3215
+ responseSchema = getImportedZodSchemaName(resolver, responseSchema);
3216
+ } else hasZodImport = true;
3217
+ config.read = {
3218
+ acl: getAclConfig(readEndpoint, resolver.options),
3219
+ schema: responseSchema,
3220
+ query: getImportedQueryName(readEndpoint, resolver.options)
3221
+ };
3222
+ }
3223
+ const createEndpoint = extendedEndpoints.find((endpoint) => isCreateEndpoint(endpoint, readAllEndpoint));
3224
+ if (createEndpoint) {
3225
+ importedEndpoints.push(createEndpoint);
3226
+ const body = getEndpointBody$1(createEndpoint);
3227
+ if (body) {
3228
+ importedZodSchemas.push(body.zodSchema);
3229
+ config.create = {
3230
+ acl: getAclConfig(createEndpoint, resolver.options),
3231
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
3232
+ mutation: createEndpoint,
3233
+ inputDefs: getInputsConfig(resolver, body)
3234
+ };
3235
+ }
3236
+ }
3237
+ const updateEndpoint = extendedEndpoints.find((endpoint) => isUpdateEndpoint(endpoint, readAllEndpoint));
3238
+ if (updateEndpoint) {
3239
+ importedEndpoints.push(updateEndpoint);
3240
+ const body = getEndpointBody$1(updateEndpoint);
3241
+ if (body) {
3242
+ importedZodSchemas.push(body.zodSchema);
3243
+ config.update = {
3244
+ acl: getAclConfig(updateEndpoint, resolver.options),
3245
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
3246
+ mutation: updateEndpoint,
3247
+ inputDefs: getInputsConfig(resolver, body)
3248
+ };
3249
+ }
3250
+ }
3251
+ const deleteEndpoint = extendedEndpoints.find((endpoint) => isDeleteEndpoint(endpoint, readAllEndpoint));
3252
+ if (deleteEndpoint) {
3253
+ importedEndpoints.push(deleteEndpoint);
3254
+ const body = getEndpointBody$1(deleteEndpoint);
3255
+ if (body) {
3256
+ importedZodSchemas.push(body.zodSchema);
3257
+ config.delete = {
3258
+ acl: getAclConfig(deleteEndpoint, resolver.options),
3259
+ mutation: deleteEndpoint
3260
+ };
3261
+ }
3262
+ }
3263
+ const bulkDeleteEndpoint = extendedEndpoints.find((endpoint) => isBulkDeleteEndpoint(endpoint, readAllEndpoint));
3264
+ if (bulkDeleteEndpoint) {
3265
+ importedEndpoints.push(bulkDeleteEndpoint);
3266
+ const body = getEndpointBody$1(bulkDeleteEndpoint);
3267
+ if (body) {
3268
+ importedZodSchemas.push(body.zodSchema);
3269
+ config.bulkDelete = {
3270
+ acl: getAclConfig(bulkDeleteEndpoint, resolver.options),
3271
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
3272
+ mutation: bulkDeleteEndpoint,
3273
+ inputDefs: getInputsConfig(resolver, body)
3274
+ };
3275
+ }
3276
+ }
3277
+ return config;
3278
+ });
3279
+ const modelsImports = getModelsImports({
3280
+ resolver,
3281
+ tag,
3282
+ zodSchemas: importedZodSchemas
3283
+ });
3284
+ const queriesImports = getQueriesImports({
3285
+ tag,
3286
+ endpoints: importedEndpoints,
3287
+ options: resolver.options
3288
+ });
3289
+ const infiniteQueriesImports = resolver.options.infiniteQueries ? getInfiniteQueriesImports({
3290
+ tag,
3291
+ endpoints: importedInfiniteEndpoints,
3292
+ options: resolver.options
3293
+ }) : [];
3294
+ const aclImports = getAclImports({
3295
+ tag,
3296
+ endpoints: importedEndpoints.filter((endpoint) => endpoint.acl),
3297
+ options: resolver.options
3298
+ });
3299
+ return {
3300
+ configs: configs.filter(Boolean),
3301
+ hasZodImport,
3302
+ modelsImports,
3303
+ queriesImports: mergeImports(resolver.options, queriesImports, infiniteQueriesImports),
3304
+ aclImports
3305
+ };
3306
+ }
3307
+ function resolveBuilderConfigNames(endpoints) {
3308
+ const sortedEndpoints = endpoints.map((endpoint) => ({
3309
+ ...endpoint,
3310
+ namePathSegments: endpoint.pathSegments.filter((segment) => !isPathSegmentParam(segment))
3311
+ })).toSorted((a, b) => a.namePathSegments.length - b.namePathSegments.length);
3312
+ const namedEndpoints = {};
3313
+ for (const endpoint of sortedEndpoints) {
3314
+ const namePathSegments = endpoint.namePathSegments;
3315
+ let name = namePathSegments.length > 0 ? `${kebabToCamel(namePathSegments.pop())}${capitalize(BUILD_CONFIG_SUFFIX)}` : BUILD_CONFIG_SUFFIX;
3316
+ while (namedEndpoints[name]) {
3317
+ if (namePathSegments.length === 0) throw new Error(`Can't uniquely resolve builder config name: ${name}`);
3318
+ name = `${kebabToCamel(namePathSegments.pop())}${capitalize(name)}`;
3319
+ }
3320
+ namedEndpoints[name] = endpoint;
3321
+ }
3322
+ return namedEndpoints;
3323
+ }
3324
+ function getAclConfig(endpoint, options) {
3325
+ return options.acl && endpoint.acl ? getImportedAbilityFunctionName(endpoint, options) : void 0;
3326
+ }
3327
+ function getInputsConfig(resolver, endpointParameter) {
3328
+ if (!endpointParameter) return;
3329
+ let schema;
3330
+ if (endpointParameter.type === "Body") schema = endpointParameter.bodyObject?.content?.[JSON_APPLICATION_FORMAT]?.schema;
3331
+ else schema = endpointParameter.parameterObject?.schema;
3332
+ if (!schema) return;
3333
+ const schemaObj = resolver.resolveObject(schema);
3334
+ const inputs = Object.keys(schemaObj?.properties ?? {}).reduce((acc, key) => ({
3335
+ ...acc,
3336
+ [key]: true
3337
+ }), {});
3338
+ return {
3339
+ schema: getImportedZodSchemaName(resolver, endpointParameter.zodSchema),
3340
+ options: { inputs }
3341
+ };
3342
+ }
3343
+ function getColumnsConfig(resolver, endpoint) {
3344
+ const endpointResponse = endpoint.responseObject;
3345
+ if (!endpointResponse) return;
3346
+ const schema = endpointResponse.content?.[JSON_APPLICATION_FORMAT]?.schema;
3347
+ if (!schema) return;
3348
+ const properties = getSchemaProperties(resolver, schema);
3349
+ const arrayPropertyKeys = Object.keys(properties).filter((key) => resolver.resolveObject(properties[key]).type === "array");
3350
+ arrayPropertyKeys.sort((a, b) => {
3351
+ const aIndex = resolver.options.dataResponseParamNames.indexOf(a);
3352
+ const bIndex = resolver.options.dataResponseParamNames.indexOf(b);
3353
+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
3354
+ if (aIndex !== -1) return -1;
3355
+ if (bIndex !== -1) return 1;
3356
+ return a.localeCompare(b);
3357
+ });
3358
+ const propertyKey = arrayPropertyKeys[0];
3359
+ if (!propertyKey) return;
3360
+ const dataSchemaObj = resolver.resolveObject(properties[propertyKey]);
3361
+ if (!dataSchemaObj || dataSchemaObj.type !== "array") return;
3362
+ const itemSchema = dataSchemaObj.items;
3363
+ const itemSchemaObj = resolver.resolveObject(itemSchema);
3364
+ if (!itemSchemaObj) return;
3365
+ const zodSchema = isReferenceObject(itemSchema) ? resolver.getZodSchemaNameByRef(itemSchema.$ref) : ANY_SCHEMA;
3366
+ const columns = Object.keys(itemSchemaObj?.properties ?? {}).reduce((acc, key) => ({
3367
+ ...acc,
3368
+ [key]: true
3369
+ }), {});
3370
+ const sortableEnumSchemaName = endpoint.parameters.find((param) => param.parameterObject && isSortingParameterObject(param.parameterObject))?.parameterSortingEnumSchemaName;
3371
+ return {
3372
+ columns: {
3373
+ schema: getImportedZodSchemaName(resolver, zodSchema),
3374
+ options: {
3375
+ columns,
3376
+ sortable: sortableEnumSchemaName ? getImportedZodSchemaName(resolver, sortableEnumSchemaName) : void 0
3377
+ }
3378
+ },
3379
+ zodSchema,
3380
+ sortableEnumSchemaName
3381
+ };
3382
+ }
3383
+ function getSchemaProperties(resolver, schema) {
3384
+ const schemaObj = resolver.resolveObject(schema);
3385
+ if (schemaObj.properties) return schemaObj.properties;
3386
+ else if ("allOf" in schemaObj && schemaObj.allOf) return schemaObj.allOf.reduce((acc, cur) => ({
3387
+ ...acc,
3388
+ ...getSchemaProperties(resolver, cur)
3389
+ }), {});
3390
+ return {};
3391
+ }
3392
+
3393
+ //#endregion
3394
+ //#region src/generators/const/queries.const.ts
3395
+ const QUERY_HOOKS = {
3396
+ query: "useQuery",
3397
+ infiniteQuery: "useInfiniteQuery",
3398
+ mutation: "useMutation"
3399
+ };
3400
+ const QUERY_IMPORT = {
3401
+ bindings: [
3402
+ QUERY_HOOKS.query,
3403
+ QUERY_HOOKS.infiniteQuery,
3404
+ QUERY_HOOKS.mutation
3405
+ ],
3406
+ from: "@tanstack/react-query"
3407
+ };
3408
+ const QUERIES_MODULE_NAME = "moduleName";
3409
+
3410
+ //#endregion
3411
+ //#region src/generators/generate/generateConfigs.ts
3412
+ function generateConfigs(generateTypeParams) {
3413
+ const { configs, hasZodImport, modelsImports, aclImports } = getBuilderConfigs(generateTypeParams);
3414
+ if (configs.length === 0) return;
3415
+ const { resolver, tag } = generateTypeParams;
3416
+ const endpoints = configs.flatMap((config) => [
3417
+ config.create?.mutation,
3418
+ config.update?.mutation,
3419
+ config.delete?.mutation,
3420
+ config.bulkDelete?.mutation
3421
+ ]).filter((m) => typeof m !== "string" && m !== void 0);
3422
+ const hasMutation = endpoints.length > 0;
3423
+ resolver.options.checkAcl && endpoints.some((e) => e.acl);
3424
+ const hasMutationEffects = resolver.options.mutationEffects && hasMutation;
3425
+ const hasWorkspaceContext = resolver.options.workspaceContext && endpoints.some((e) => resolver.options.workspaceContext);
3426
+ const endpointsImports = getEndpointsImports({
3427
+ tag,
3428
+ endpoints,
3429
+ options: resolver.options
3430
+ });
3431
+ const queryImport = {
3432
+ bindings: [QUERY_HOOKS.mutation],
3433
+ from: "@tanstack/react-query"
3434
+ };
3435
+ const queryTypesImport = {
3436
+ bindings: ["OpenApiQueryConfig"],
3437
+ typeBindings: [QUERY_OPTIONS_TYPES.mutation],
3438
+ from: getQueryTypesImportPath(resolver.options)
3439
+ };
3440
+ const mutationEffectsImport = {
3441
+ bindings: [MUTATION_EFFECTS.hookName],
3442
+ typeBindings: [MUTATION_EFFECTS.optionsType],
3443
+ from: PACKAGE_IMPORT_PATH
3444
+ };
3445
+ const queryModulesImport = {
3446
+ bindings: [QUERY_MODULE_ENUM],
3447
+ from: getQueryModulesImportPath(resolver.options)
3448
+ };
3449
+ const aclCheckImport = {
3450
+ bindings: [ACL_CHECK_HOOK],
3451
+ from: ACL_PACKAGE_IMPORT_PATH
3452
+ };
3453
+ const workspaceContextImport = {
3454
+ bindings: ["OpenApiWorkspaceContext"],
3455
+ from: PACKAGE_IMPORT_PATH
3456
+ };
3457
+ const hasDynamicInputsImport = configs.some((config) => config.readAll.filters || config.create?.inputDefs || config.update?.inputDefs);
3458
+ const dynamicInputsImport = {
3459
+ bindings: [BUILDERS_UTILS.dynamicInputs],
3460
+ from: resolver.options.dynamicInputsImportPath
3461
+ };
3462
+ const hasDynamicColumnsImport = configs.some((config) => config.readAll.columns);
3463
+ const dynamicColumnsImport = {
3464
+ bindings: [BUILDERS_UTILS.dynamicColumns],
3465
+ from: resolver.options.dynamicColumnsImportPath
3466
+ };
3467
+ const lines = [];
3468
+ if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
3469
+ if (hasDynamicInputsImport) lines.push(renderImport$3(dynamicInputsImport));
3470
+ if (hasDynamicColumnsImport) lines.push(renderImport$3(dynamicColumnsImport));
3471
+ for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
3472
+ for (const endpointsImport of endpointsImports) lines.push(renderImport$3(endpointsImport));
3473
+ if (hasMutation) {
3474
+ lines.push(renderImport$3(queryImport));
3475
+ lines.push(renderImport$3(queryTypesImport));
3476
+ if (hasMutationEffects) {
3477
+ lines.push(renderImport$3(queryModulesImport));
3478
+ lines.push(renderImport$3(mutationEffectsImport));
3479
+ }
3480
+ lines.push(renderImport$3(aclCheckImport));
3481
+ if (hasWorkspaceContext) lines.push(renderImport$3(workspaceContextImport));
3482
+ }
3483
+ for (const aclImport of aclImports) lines.push(renderImport$3(aclImport));
3484
+ lines.push("");
3485
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3486
+ type: GenerateType.Configs,
3487
+ tag,
3488
+ options: resolver.options
3489
+ })} {`);
3490
+ for (const config of configs) {
3491
+ lines.push(renderBuilderConfig(config, generateTypeParams));
3492
+ lines.push("");
3493
+ }
3494
+ if (resolver.options.tsNamespaces) lines.push("}");
3495
+ return lines.join("\n").trimEnd() + "\n";
3496
+ }
3497
+ function renderImport$3(importData) {
3498
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
3499
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
3500
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
3501
+ }
3502
+ function renderInputsConfig(inputsConfig) {
3503
+ const lines = [];
3504
+ lines.push("{");
3505
+ lines.push(` schema: ${inputsConfig.schema},`);
3506
+ lines.push(" options: {");
3507
+ lines.push(" inputs: {");
3508
+ for (const key of Object.keys(inputsConfig.options.inputs)) lines.push(` ${key}: true,`);
3509
+ lines.push(" },");
3510
+ lines.push(" },");
3511
+ lines.push("}");
3512
+ return lines.join("\n");
3513
+ }
3514
+ function renderColumnsConfig(columnsConfig) {
3515
+ const lines = [];
3516
+ lines.push("{");
3517
+ lines.push(` schema: ${columnsConfig.schema},`);
3518
+ lines.push(" options: {");
3519
+ lines.push(" columns: {");
3520
+ for (const key of Object.keys(columnsConfig.options.columns)) lines.push(` ${key}: true,`);
3521
+ lines.push(" },");
3522
+ if (columnsConfig.options.sortable) lines.push(` sortable: ${columnsConfig.options.sortable},`);
3523
+ lines.push(" },");
3524
+ lines.push("}");
3525
+ return lines.join("\n");
3526
+ }
3527
+ function renderMutationContent(resolver, endpoint, tag) {
3528
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
3529
+ const hasMutationEffects = resolver.options.mutationEffects;
3530
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3531
+ const endpointTag = getEndpointTag(endpoint, resolver.options);
3532
+ const endpointParams = mapEndpointParamsToFunctionParams(resolver, endpoint, {
3533
+ includeFileParam: true,
3534
+ modelNamespaceTag: endpointTag
3535
+ });
3536
+ const endpointParamsStr = endpointParams.map((p) => `${p.name}${p.required ? "" : "?"}: ${p.type}`).join("; ");
3537
+ const destructuredMutationArgs = endpointParams.map((p) => p.name).join(", ");
3538
+ const endpointFunction = getImportedEndpointName(endpoint, resolver.options);
3539
+ const mutationVariablesType = endpoint.mediaUpload ? `{ ${endpointParamsStr}${endpointParamsStr ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void }` : `{ ${endpointParamsStr} }`;
3540
+ const lines = [];
3541
+ lines.push(`(options?: AppMutationOptions<typeof ${endpointFunction}, ${mutationVariablesType}>${hasAxiosRequestConfig ? `, config?: AxiosRequestConfig` : ""}) => {`);
3542
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
3543
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<typeof ${QUERY_MODULE_ENUM}.${endpointTag}>({ currentModule: ${QUERY_MODULE_ENUM}.${tag} });`);
3544
+ lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
3545
+ lines.push("");
3546
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
3547
+ const mutationFnArg = destructuredMutationArgs ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
3548
+ lines.push(` mutationFn: (${mutationFnArg}) => {`);
3549
+ if (hasAclCheck) lines.push(` checkAcl(${getNamespaceName({
3550
+ type: GenerateType.Acl,
3551
+ tag: endpointTag,
3552
+ options: resolver.options
3553
+ })}.canUse${capitalize(snakeToCamel(endpoint.operationName))}({ ${destructuredMutationArgs} }));`);
3554
+ lines.push(` return ${endpointFunction}(${destructuredMutationArgs}${hasAxiosRequestConfig ? `${destructuredMutationArgs ? ", " : ""}config` : ""});`);
3555
+ lines.push(" },");
3556
+ if (hasMutationEffects) {
3557
+ lines.push(" onSuccess: async (...args) => {");
3558
+ lines.push(" await runMutationEffects();");
3559
+ lines.push(" await options?.onSuccess?.(...args);");
3560
+ lines.push(" },");
3561
+ }
3562
+ lines.push(" ...options,");
3563
+ lines.push(" });");
3564
+ lines.push("}");
3565
+ return lines.map((line) => " " + line).join("\n").trimStart();
3566
+ }
3567
+ function renderBuilderConfig(config, params) {
3568
+ const { resolver, tag } = params;
3569
+ const lines = [];
3570
+ lines.push(`export const ${config.name} = {`);
3571
+ lines.push(" meta: {");
3572
+ lines.push(` title: "${config.title}",`);
3573
+ lines.push(" },");
3574
+ lines.push(" readAll: {");
3575
+ if (config.readAll.acl) lines.push(` acl: ${config.readAll.acl},`);
3576
+ lines.push(` schema: ${config.readAll.columns.schema},`);
3577
+ lines.push(` paginated: ${config.readAll.paginated},`);
3578
+ if (config.readAll.infinite) lines.push(` infinite: ${config.readAll.infinite},`);
3579
+ if (config.readAll.filters) {
3580
+ lines.push(" filters: {");
3581
+ lines.push(` schema: ${config.readAll.filters.schema},`);
3582
+ lines.push(` filterDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.readAll.filters)})`);
3583
+ lines.push(" },");
3584
+ }
3585
+ lines.push(` columns: ${BUILDERS_UTILS.dynamicColumns}(${renderColumnsConfig(config.readAll.columns)}),`);
3586
+ lines.push(" },");
3587
+ if (config.read) {
3588
+ lines.push(" read: {");
3589
+ if (config.read.acl) lines.push(` acl: ${config.read.acl},`);
3590
+ lines.push(` schema: ${config.read.schema},`);
3591
+ lines.push(` query: ${config.read.query},`);
3592
+ lines.push(" },");
3593
+ }
3594
+ if (config.create) {
3595
+ lines.push(" create: {");
3596
+ if (config.create.acl) lines.push(` acl: ${config.create.acl},`);
3597
+ if (config.create.schema) lines.push(` schema: ${config.create.schema},`);
3598
+ lines.push(` mutation: ${typeof config.create.mutation === "string" ? config.create.mutation : renderMutationContent(resolver, config.create.mutation, tag)},`);
3599
+ if (config.create.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.create.inputDefs)})`);
3600
+ lines.push(" },");
3601
+ }
3602
+ if (config.update) {
3603
+ lines.push(" update: {");
3604
+ if (config.update.acl) lines.push(` acl: ${config.update.acl},`);
3605
+ if (config.update.schema) lines.push(` schema: ${config.update.schema},`);
3606
+ lines.push(` mutation: ${typeof config.update.mutation === "string" ? config.update.mutation : renderMutationContent(resolver, config.update.mutation, tag)},`);
3607
+ if (config.update.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.update.inputDefs)})`);
3608
+ lines.push(" },");
3609
+ }
3610
+ if (config.delete) {
3611
+ lines.push(" delete: {");
3612
+ if (config.delete.acl) lines.push(` acl: ${config.delete.acl},`);
3613
+ lines.push(` mutation: ${typeof config.delete.mutation === "string" ? config.delete.mutation : renderMutationContent(resolver, config.delete.mutation, tag)},`);
3614
+ lines.push(" },");
3615
+ }
3616
+ if (config.bulkDelete) {
3617
+ lines.push(" bulkDelete: {");
3618
+ if (config.bulkDelete.acl) lines.push(` acl: ${config.bulkDelete.acl},`);
3619
+ if (config.bulkDelete.schema) lines.push(` schema: ${config.bulkDelete.schema},`);
3620
+ lines.push(` mutation: ${typeof config.bulkDelete.mutation === "string" ? config.bulkDelete.mutation : renderMutationContent(resolver, config.bulkDelete.mutation, tag)},`);
3621
+ if (config.bulkDelete.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.bulkDelete.inputDefs)})`);
3622
+ lines.push(" },");
3623
+ }
3624
+ lines.push("};");
3625
+ return lines.join("\n");
3626
+ }
3627
+
3628
+ //#endregion
3629
+ //#region src/generators/generate/generateEndpoints.ts
3630
+ function generateEndpoints({ resolver, data, tag }) {
3631
+ if (shouldInlineEndpointsForTag(tag, resolver.options)) return;
3632
+ const endpoints = data.get(tag)?.endpoints;
3633
+ if (!endpoints || endpoints.length === 0) return;
3634
+ const appRestClientImport = {
3635
+ bindings: [APP_REST_CLIENT_NAME],
3636
+ from: getAppRestClientImportPath(resolver.options)
3637
+ };
3638
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3639
+ const hasAxiosImport = hasAxiosRequestConfig;
3640
+ const axiosImport = {
3641
+ bindings: [],
3642
+ typeBindings: hasAxiosRequestConfig ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
3643
+ from: AXIOS_IMPORT.from
3644
+ };
3645
+ const generateParse = resolver.options.parseRequestParams;
3646
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
3647
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
3648
+ const zodSchemas = getUniqueArray([...endpoints.map((endpoint) => endpoint.response), ...generateParse ? endpointParamsParseSchemas : []]);
3649
+ const hasZodImport = zodSchemas.some((schema) => !isNamedZodSchema(schema));
3650
+ const hasZodExtendedImport = resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
3651
+ const zodExtendedImport = {
3652
+ bindings: [ZOD_EXTENDED.namespace],
3653
+ from: ZOD_PACKAGE_IMPORT_PATH
3654
+ };
3655
+ const modelsImports = getModelsImports({
3656
+ resolver,
3657
+ tag,
3658
+ zodSchemas: zodSchemas.filter(isNamedZodSchema),
3659
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
3660
+ });
3661
+ const lines = [];
3662
+ lines.push(renderImport$2(appRestClientImport));
3663
+ if (hasAxiosImport) lines.push(renderImport$2(axiosImport));
3664
+ if (hasZodImport) lines.push(renderImport$2(ZOD_IMPORT));
3665
+ if (hasZodExtendedImport) lines.push(renderImport$2(zodExtendedImport));
3666
+ for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
3667
+ lines.push("");
3668
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3669
+ type: GenerateType.Endpoints,
3670
+ tag,
3671
+ options: resolver.options
3672
+ })} {`);
3673
+ for (const endpoint of endpoints) {
3674
+ const endpointParamOptions = { modelNamespaceTag: tag };
3675
+ const endpointParams = renderEndpointParams$1(resolver, endpoint, endpointParamOptions);
3676
+ renderEndpointArgs$1(resolver, endpoint, endpointParamOptions);
3677
+ const endpointBody = getEndpointBody$1(endpoint);
3678
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
3679
+ const endpointConfig = renderEndpointConfig(resolver, endpoint, tag);
3680
+ lines.push(`export const ${getEndpointName(endpoint)} = (${endpointParams}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
3681
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
3682
+ lines.push(` { resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} },`);
3683
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
3684
+ if (endpointBody) lines.push(` ${generateParse ? renderEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
3685
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
3686
+ lines.push(` ${endpointConfig}`);
3687
+ lines.push(" )");
3688
+ lines.push("};");
3689
+ }
3690
+ if (resolver.options.tsNamespaces) lines.push("}");
3691
+ return lines.join("\n").trimEnd() + "\n";
3692
+ }
3693
+ function renderImport$2(importData) {
3694
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
3695
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
3696
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
3697
+ }
3698
+ function renderEndpointParams$1(resolver, endpoint, options) {
3699
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}, `).join("");
3700
+ }
3701
+ function renderEndpointArgs$1(resolver, endpoint, options) {
3702
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => param.name).join(", ");
3703
+ }
3704
+ function renderEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
3705
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
3706
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${addOptional ? ".optional()" : ""}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
3707
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
3708
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
3709
+ }
3710
+ function renderEndpointConfig(resolver, endpoint, modelNamespaceTag) {
3711
+ const endpointConfig = getEndpointConfig(endpoint);
3712
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3713
+ if (Object.keys(endpointConfig).length === 0) return hasAxiosRequestConfig ? AXIOS_REQUEST_CONFIG_NAME : "";
3714
+ const lines = [];
3715
+ lines.push("{");
3716
+ if (hasAxiosRequestConfig) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
3717
+ if (endpointConfig.params) {
3718
+ lines.push(" params: {");
3719
+ for (const param of endpointConfig.params) {
3720
+ const value = resolver.options.parseRequestParams ? renderEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
3721
+ lines.push(` ${param.name}: ${value},`);
3722
+ }
3723
+ lines.push(" },");
3724
+ }
3725
+ if (endpointConfig.headers) {
3726
+ lines.push(" headers: {");
3727
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
3728
+ lines.push(" },");
3729
+ }
3730
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
3731
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
3732
+ lines.push("}");
3733
+ return lines.join("\n ");
3734
+ }
3735
+
3736
+ //#endregion
3737
+ //#region src/generators/generate/generateModels.ts
3738
+ function generateModels({ resolver, data, tag }) {
3739
+ if (resolver.options.modelsInCommon && resolver.options.splitByTags && tag !== resolver.options.defaultTag) return renderModelsProxy({
3740
+ resolver,
3741
+ data,
3742
+ tag
3743
+ });
3744
+ const zodSchemas = data.get(tag)?.zodSchemas;
3745
+ if (!zodSchemas || Object.keys(zodSchemas).length === 0) return;
3746
+ const refZodSchemas = [];
3747
+ for (const zodSchema of Object.keys(zodSchemas)) {
3748
+ const refs = getZodSchemaRefs(resolver, zodSchema);
3749
+ for (const ref of refs) if (!zodSchemas[ref]) refZodSchemas.push(ref);
3750
+ }
3751
+ const modelsImports = getModelsImports({
3752
+ resolver,
3753
+ tag,
3754
+ zodSchemas: refZodSchemas
3755
+ });
3756
+ const zodSchemasData = {};
3757
+ for (const [key, code] of Object.entries(zodSchemas)) {
3758
+ const schemaRef = resolver.getRefByZodSchemaName(key);
3759
+ zodSchemasData[key] = {
3760
+ code,
3761
+ isCiruclar: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
3762
+ isEnum: isEnumZodSchema(code),
3763
+ schemaObj: resolver.getZodSchemaObj(key)
3764
+ };
3765
+ }
3766
+ const lines = [];
3767
+ lines.push(renderImport$1(ZOD_IMPORT));
3768
+ for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
3769
+ lines.push("");
3770
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3771
+ type: GenerateType.Models,
3772
+ tag,
3773
+ options: resolver.options
3774
+ })} {`);
3775
+ for (const [name, zodSchema] of Object.entries(zodSchemasData)) {
3776
+ lines.push(renderModelJsDocs({
3777
+ name,
3778
+ zodSchema,
3779
+ tag,
3780
+ resolver
3781
+ }));
3782
+ lines.push(`export const ${name} = ${zodSchema.code};`);
3783
+ lines.push(`export type ${getZodSchemaInferedTypeName(name, resolver.options)} = z.infer<typeof ${name}>;`);
3784
+ if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
3785
+ lines.push("");
3786
+ }
3787
+ if (resolver.options.tsNamespaces) lines.push("}");
3788
+ return lines.join("\n").trimEnd() + "\n";
3789
+ }
3790
+ function renderModelsProxy({ resolver, data, tag }) {
3791
+ const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
3792
+ const schemaNames = getUsedSchemaNames({
3793
+ resolver,
3794
+ endpoints: data.get(tag)?.endpoints ?? []
3795
+ }).filter((schemaName) => Boolean(commonZodSchemas[schemaName]));
3796
+ if (schemaNames.length === 0) return;
3797
+ const modelsNamespace = getNamespaceName({
3798
+ type: GenerateType.Models,
3799
+ tag,
3800
+ options: resolver.options
3801
+ });
3802
+ const commonNamespace = getNamespaceName({
3803
+ type: GenerateType.Models,
3804
+ tag: resolver.options.defaultTag,
3805
+ options: resolver.options
3806
+ });
3807
+ const commonModelsPath = `${getImportPath(resolver.options)}${getTagImportPath({
3808
+ type: GenerateType.Models,
3809
+ tag: resolver.options.defaultTag,
3810
+ includeTagDir: true,
3811
+ options: resolver.options
3812
+ })}`;
3813
+ const inferredTypeNames = schemaNames.map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
3814
+ const enumInferredTypeNames = schemaNames.filter((schemaName) => isEnumZodSchema(commonZodSchemas[schemaName] ?? "")).map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
3815
+ if (resolver.options.tsNamespaces) {
3816
+ const lines = [];
3817
+ lines.push(`import { ${commonNamespace} } from "${commonModelsPath}";`);
3818
+ lines.push("");
3819
+ lines.push(`export namespace ${modelsNamespace} {`);
3820
+ for (const schemaName of schemaNames) lines.push(` export const ${schemaName} = ${commonNamespace}.${schemaName};`);
3821
+ for (const typeName of inferredTypeNames) lines.push(` export type ${typeName} = ${commonNamespace}.${typeName};`);
3822
+ for (const enumName of enumInferredTypeNames) lines.push(` export const ${enumName} = ${commonNamespace}.${enumName};`);
3823
+ lines.push("}");
3824
+ lines.push("");
3825
+ return lines.join("\n");
3826
+ }
3827
+ const valueExports = getUniqueArray([...schemaNames, ...enumInferredTypeNames]);
3828
+ const lines = [];
3829
+ if (valueExports.length > 0) lines.push(`export { ${valueExports.join(", ")} } from "${commonModelsPath}";`);
3830
+ if (inferredTypeNames.length > 0) lines.push(`export type { ${inferredTypeNames.join(", ")} } from "${commonModelsPath}";`);
3831
+ return lines.join("\n") + "\n";
3832
+ }
3833
+ function getUsedSchemaNames({ resolver, endpoints }) {
3834
+ const usedSchemaNames = /* @__PURE__ */ new Set();
3835
+ const queue = [];
3836
+ const enqueue = (schemaName) => {
3837
+ if (!schemaName || !isNamedZodSchema(schemaName) || usedSchemaNames.has(schemaName)) return;
3838
+ usedSchemaNames.add(schemaName);
3839
+ queue.push(schemaName);
3840
+ };
3841
+ for (const endpoint of endpoints) {
3842
+ enqueue(endpoint.response);
3843
+ for (const error of endpoint.errors) enqueue(error.zodSchema);
3844
+ for (const param of endpoint.parameters) {
3845
+ enqueue(param.zodSchema);
3846
+ enqueue(param.parameterSortingEnumSchemaName);
3847
+ }
3848
+ }
3849
+ while (queue.length > 0) {
3850
+ const schemaName = queue.shift();
3851
+ if (!schemaName) continue;
3852
+ const refs = getZodSchemaRefs(resolver, schemaName);
3853
+ for (const ref of refs) enqueue(ref);
3854
+ }
3855
+ return Array.from(usedSchemaNames);
3856
+ }
3857
+ function renderImport$1(importData) {
3858
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
3859
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
3860
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
3861
+ }
3862
+ function renderModelJsDocs({ name, zodSchema, tag, resolver }) {
3863
+ const lines = [
3864
+ `/** `,
3865
+ ` * ${name} `,
3866
+ ` * @type { ${getZodSchemaType(zodSchema)} }`
3867
+ ];
3868
+ const description = getZodSchemaDescription(zodSchema);
3869
+ if (description) lines.push(` * @description ${description.replace(/\n/g, "\n *")}`);
3870
+ const propertyDescriptions = getZodSchemaPropertyDescriptions(resolver, zodSchema, tag);
3871
+ if (propertyDescriptions) for (const [property, info] of Object.entries(propertyDescriptions)) lines.push(` * @property { ${info.type} } ${property} ${info.description.replace(/\n/g, "\n *")} `);
3872
+ lines.push(" */");
3873
+ return lines.join("\n");
3874
+ }
3875
+
3876
+ //#endregion
3877
+ //#region src/generators/generate/generateQueries.ts
3878
+ const endpointParamMappingCache = /* @__PURE__ */ new WeakMap();
3879
+ function generateQueries(params) {
3880
+ const { resolver, data, tag } = params;
3881
+ const inlineEndpoints = shouldInlineEndpointsForTag(tag, resolver.options);
3882
+ const endpoints = data.get(tag)?.endpoints;
3883
+ if (!endpoints || endpoints.length === 0) return;
3884
+ const endpointGroups = groupEndpoints(endpoints, resolver);
3885
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3886
+ const hasAxiosDefaultImport = endpoints.some(({ mediaUpload }) => mediaUpload);
3887
+ const hasAxiosImport = hasAxiosRequestConfig || hasAxiosDefaultImport;
3888
+ const axiosImport = {
3889
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
3890
+ bindings: [],
3891
+ typeBindings: hasAxiosRequestConfig ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
3892
+ from: AXIOS_IMPORT.from
3893
+ };
3894
+ const { queryEndpoints, infiniteQueryEndpoints, mutationEndpoints, aclEndpoints } = endpointGroups;
3895
+ const queryImport = {
3896
+ bindings: [
3897
+ ...resolver.options.prefetchQueries && queryEndpoints.length > 0 ? ["QueryClient"] : [],
3898
+ ...queryEndpoints.length > 0 ? [QUERY_HOOKS.query] : [],
3899
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_HOOKS.infiniteQuery] : [],
3900
+ ...mutationEndpoints.length > 0 ? [QUERY_HOOKS.mutation] : []
3901
+ ],
3902
+ from: QUERY_IMPORT.from
3903
+ };
3904
+ const hasMutationEffects = resolver.options.mutationEffects;
3905
+ const queryModulesImport = {
3906
+ bindings: [QUERY_MODULE_ENUM],
3907
+ from: getQueryModulesImportPath(resolver.options)
3908
+ };
3909
+ const hasMutationEffectsImport = hasMutationEffects && mutationEndpoints.length > 0;
3910
+ const mutationEffectsImport = {
3911
+ bindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.hookName] : []],
3912
+ typeBindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.optionsType] : []],
3913
+ from: PACKAGE_IMPORT_PATH
3914
+ };
3915
+ const hasAclCheck = resolver.options.checkAcl && aclEndpoints.length > 0;
3916
+ const aclCheckImport = {
3917
+ bindings: [ACL_CHECK_HOOK],
3918
+ from: ACL_PACKAGE_IMPORT_PATH
3919
+ };
3920
+ const queryTypesImport = {
3921
+ bindings: [...mutationEndpoints.length > 0 ? ["OpenApiQueryConfig"] : []],
3922
+ typeBindings: [
3923
+ ...queryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.query] : [],
3924
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.infiniteQuery] : [],
3925
+ ...mutationEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.mutation] : []
3926
+ ],
3927
+ from: getQueryTypesImportPath(resolver.options)
3928
+ };
3929
+ const hasWorkspaceContext = resolver.options.workspaceContext && endpoints.some((endpoint) => getWorkspaceParamNames(resolver, endpoint).length > 0);
3930
+ const workspaceContextImport = {
3931
+ bindings: ["OpenApiWorkspaceContext"],
3932
+ from: PACKAGE_IMPORT_PATH
3933
+ };
3934
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
3935
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
3936
+ const endpointRuntimeSchemas = getUniqueArray([...endpoints.map((endpoint) => endpoint.response), ...resolver.options.parseRequestParams ? endpointParamsParseSchemas : []]);
3937
+ const hasZodImport = inlineEndpoints && endpointRuntimeSchemas.some((schema) => !isNamedZodSchema(schema));
3938
+ const hasZodExtendedImport = inlineEndpoints && resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
3939
+ const appRestClientImport = {
3940
+ bindings: [APP_REST_CLIENT_NAME],
3941
+ from: getAppRestClientImportPath(resolver.options)
3942
+ };
3943
+ const zodExtendedImport = {
3944
+ bindings: [ZOD_EXTENDED.namespace],
3945
+ from: ZOD_PACKAGE_IMPORT_PATH
3946
+ };
3947
+ const modelsImports = getModelsImports({
3948
+ resolver,
3949
+ tag,
3950
+ zodSchemas: inlineEndpoints ? endpointRuntimeSchemas.filter(isNamedZodSchema) : [],
3951
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
3952
+ });
3953
+ const endpointsImports = inlineEndpoints ? [] : getEndpointsImports({
3954
+ tag,
3955
+ endpoints,
3956
+ options: resolver.options
3957
+ });
3958
+ const aclImports = getAclImports({
3959
+ tag,
3960
+ endpoints: aclEndpoints,
3961
+ options: resolver.options
3962
+ });
3963
+ const namespace = getNamespaceName({
3964
+ type: GenerateType.Queries,
3965
+ tag,
3966
+ options: resolver.options
3967
+ });
3968
+ const lines = [];
3969
+ if (hasAxiosImport) lines.push(renderImport(axiosImport));
3970
+ if (inlineEndpoints) {
3971
+ lines.push(renderImport(appRestClientImport));
3972
+ if (hasZodImport) lines.push(renderImport(ZOD_IMPORT));
3973
+ if (hasZodExtendedImport) lines.push(renderImport(zodExtendedImport));
3974
+ }
3975
+ lines.push(renderImport(queryImport));
3976
+ if (hasMutationEffects) lines.push(renderImport(queryModulesImport));
3977
+ if (hasMutationEffectsImport) lines.push(renderImport(mutationEffectsImport));
3978
+ if (hasAclCheck) {
3979
+ lines.push(renderImport(aclCheckImport));
3980
+ for (const aclImport of aclImports) lines.push(renderImport(aclImport));
3981
+ }
3982
+ lines.push(renderImport(queryTypesImport));
3983
+ if (hasWorkspaceContext) lines.push(renderImport(workspaceContextImport));
3984
+ for (const modelsImport of modelsImports) lines.push(renderImport(modelsImport));
3985
+ for (const endpointsImport of endpointsImports) lines.push(renderImport(endpointsImport));
3986
+ lines.push("");
3987
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${namespace} {`);
3988
+ if (inlineEndpoints) {
3989
+ lines.push(...renderInlineEndpoints({
3990
+ resolver,
3991
+ endpoints,
3992
+ tag
3993
+ }));
3994
+ lines.push("");
3995
+ }
3996
+ lines.push(`export const ${QUERIES_MODULE_NAME} = ${hasMutationEffects ? `${QUERY_MODULE_ENUM}.${tag}` : `"${namespace}"`};`);
3997
+ lines.push("");
3998
+ lines.push(renderQueryKeys({
3999
+ resolver,
4000
+ queryEndpoints,
4001
+ tag
4002
+ }));
4003
+ lines.push("");
4004
+ for (const endpoint of endpoints) {
4005
+ const endpointInfo = endpointGroups.infoByEndpoint.get(endpoint);
4006
+ if (endpointInfo?.query) {
4007
+ lines.push(renderQueryOptions({
4008
+ resolver,
4009
+ endpoint,
4010
+ inlineEndpoints
4011
+ }));
4012
+ lines.push("");
4013
+ lines.push(renderQuery({
4014
+ resolver,
4015
+ endpoint,
4016
+ inlineEndpoints
4017
+ }));
4018
+ lines.push("");
4019
+ if (resolver.options.prefetchQueries) {
4020
+ lines.push(renderPrefetchQuery({
4021
+ resolver,
4022
+ endpoint
4023
+ }));
4024
+ lines.push("");
4025
+ }
4026
+ }
4027
+ if (endpointInfo?.mutation) {
4028
+ lines.push(renderMutation({
4029
+ resolver,
4030
+ endpoint,
4031
+ inlineEndpoints,
4032
+ precomputed: endpointGroups.mutationDataByEndpoint.get(endpoint)
4033
+ }));
4034
+ lines.push("");
4035
+ }
4036
+ if (endpointInfo?.infiniteQuery) {
4037
+ lines.push(renderInfiniteQueryOptions({
4038
+ resolver,
4039
+ endpoint,
4040
+ inlineEndpoints
4041
+ }));
4042
+ lines.push("");
4043
+ lines.push(renderInfiniteQuery({
4044
+ resolver,
4045
+ endpoint,
4046
+ inlineEndpoints
4047
+ }));
4048
+ lines.push("");
4049
+ if (resolver.options.prefetchQueries) {
4050
+ lines.push(renderPrefetchInfiniteQuery({
4051
+ resolver,
4052
+ endpoint
4053
+ }));
4054
+ lines.push("");
4055
+ }
4056
+ }
4057
+ }
4058
+ if (resolver.options.tsNamespaces) lines.push("}");
4059
+ return lines.join("\n").trimEnd() + "\n";
4060
+ }
4061
+ function getEndpointParamMapping(resolver, endpoint, options) {
4062
+ let resolverCache = endpointParamMappingCache.get(resolver);
4063
+ if (!resolverCache) {
4064
+ resolverCache = /* @__PURE__ */ new WeakMap();
4065
+ endpointParamMappingCache.set(resolver, resolverCache);
4066
+ }
4067
+ let endpointCache = resolverCache.get(endpoint);
4068
+ if (!endpointCache) {
4069
+ endpointCache = /* @__PURE__ */ new Map();
4070
+ resolverCache.set(endpoint, endpointCache);
4071
+ }
4072
+ const key = JSON.stringify(Object.entries(options ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([optionName, optionValue]) => [optionName, Boolean(optionValue)]));
4073
+ const cached = endpointCache.get(key);
4074
+ if (cached) return cached;
4075
+ const computed = mapEndpointParamsToFunctionParams(resolver, endpoint, options);
4076
+ endpointCache.set(key, computed);
4077
+ return computed;
4078
+ }
4079
+ function renderImport(importData) {
4080
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
4081
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
4082
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
4083
+ }
4084
+ function renderEndpointParams(resolver, endpoint, options) {
4085
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}`).join(", ");
4086
+ }
4087
+ function renderEndpointArgs(resolver, endpoint, options, replacements) {
4088
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => replacements?.[param.name] ?? param.name).join(", ");
4089
+ }
4090
+ function renderEndpointParamDescription(endpointParam) {
4091
+ const strs = [`${endpointParam.paramType} parameter`];
4092
+ const description = endpointParam.parameterObject?.description || endpointParam.bodyObject?.description;
4093
+ if (description) strs.push(description);
4094
+ let schema = void 0;
4095
+ let mediaTypeObject = void 0;
4096
+ if (endpointParam.parameterObject?.schema && isSchemaObject(endpointParam.parameterObject.schema)) schema = endpointParam.parameterObject?.schema;
4097
+ if (endpointParam.bodyObject?.content) {
4098
+ const matchingMediaType = Object.keys(endpointParam.bodyObject.content ?? {}).find(isParamMediaTypeAllowed);
4099
+ if (matchingMediaType) {
4100
+ mediaTypeObject = endpointParam.bodyObject.content[matchingMediaType];
4101
+ if (mediaTypeObject.schema && isSchemaObject(mediaTypeObject.schema)) schema = mediaTypeObject.schema;
4102
+ }
4103
+ }
4104
+ if (schema) strs.push(...getSchemaDescriptions(schema));
4105
+ if (mediaTypeObject?.example) strs.push(`Example: \`${mediaTypeObject.example}\``);
4106
+ return strs.join(". ");
4107
+ }
4108
+ function getWorkspaceParamNames(resolver, endpoint) {
4109
+ const endpointParams = getEndpointParamMapping(resolver, endpoint, {});
4110
+ const endpointParamNames = new Set(endpointParams.map((param) => param.name));
4111
+ const workspaceParamNames = endpointParams.filter((param) => param.paramType === "Path").map((param) => param.name);
4112
+ const aclParamNames = (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => invalidVariableNameCharactersToCamel(condition.name)).filter((name) => endpointParamNames.has(name));
4113
+ return getUniqueArray([...workspaceParamNames, ...aclParamNames]);
4114
+ }
4115
+ function getWorkspaceParamReplacements(resolver, endpoint) {
4116
+ return Object.fromEntries(getWorkspaceParamNames(resolver, endpoint).map((name) => [name, `${name}FromWorkspace`]));
4117
+ }
4118
+ function renderWorkspaceParamResolutions({ replacements, indent }) {
4119
+ const workspaceParamNames = Object.keys(replacements);
4120
+ if (workspaceParamNames.length === 0) return [];
4121
+ const lines = [`${indent}const workspaceContext = OpenApiWorkspaceContext.useContext();`];
4122
+ for (const paramName of workspaceParamNames) lines.push(`${indent}const ${replacements[paramName]} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
4123
+ return lines;
4124
+ }
4125
+ function renderAclCheckCall(resolver, endpoint, replacements, indent = "") {
4126
+ const checkParams = getAbilityConditionsTypes(endpoint)?.map((condition) => invalidVariableNameCharactersToCamel(condition.name));
4127
+ const paramNames = new Set(endpoint.parameters.map((param) => invalidVariableNameCharactersToCamel(param.name)));
4128
+ const hasAllCheckParams = checkParams?.every((param) => paramNames.has(param));
4129
+ const args = hasAbilityConditions(endpoint) && hasAllCheckParams ? `{ ${(checkParams ?? []).map((param) => {
4130
+ const resolvedParam = replacements?.[param] ?? param;
4131
+ return resolvedParam === param ? param : `${param}: ${resolvedParam}`;
4132
+ }).join(", ")} } ` : "";
4133
+ return `${indent}checkAcl(${getImportedAbilityFunctionName(endpoint, resolver.options)}(${args}));`;
4134
+ }
4135
+ function addAsteriskAfterNewLine(str) {
4136
+ return str.replace(/\n/g, "\n *");
4137
+ }
4138
+ function renderQueryJsDocs({ resolver, endpoint, mode, tag }) {
4139
+ const lines = ["/** "];
4140
+ if (mode === "infiniteQuery") lines.push(` * Infinite query \`${getInfiniteQueryName(endpoint)}${endpoint.summary ? "" : ""}`);
4141
+ else if (mode === "query") lines.push(` * Query \`${getQueryName(endpoint)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should be cached" : ""}`);
4142
+ else lines.push(` * Mutation \`${getQueryName(endpoint, true)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should not be cached" : ""}`);
4143
+ if (endpoint.summary) lines.push(` * @summary ${addAsteriskAfterNewLine(endpoint.summary)}`);
4144
+ if (endpoint.description) lines.push(` * @description ${addAsteriskAfterNewLine(endpoint.description)}`);
4145
+ if (endpoint.acl) lines.push(` * @permission Requires \`${getAbilityFunctionName(endpoint)}\` ability `);
4146
+ const params = getEndpointParamMapping(resolver, endpoint, {
4147
+ ...mode !== "infiniteQuery" ? { includeFileParam: true } : {},
4148
+ modelNamespaceTag: tag
4149
+ });
4150
+ for (const endpointParam of params) lines.push(` * @param { ${endpointParam.type} } ${endpointParam.name} ${renderEndpointParamDescription(endpointParam)}`);
4151
+ if (mode === "query") lines.push(" * @param { AppQueryOptions } options Query options");
4152
+ else if (mode === "mutation") lines.push(` * @param { AppMutationOptions${resolver.options.mutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""} } options Mutation options`);
4153
+ else lines.push(" * @param { AppInfiniteQueryOptions } options Infinite query options");
4154
+ const withAxiosResponse = endpoint.mediaDownload && mode !== "infiniteQuery";
4155
+ const resultType = `${withAxiosResponse ? "AxiosResponse<" : ""}${getImportedZodSchemaInferedTypeName(resolver, endpoint.response, void 0, tag)}${withAxiosResponse ? ">" : ""}`;
4156
+ if (mode === "query") lines.push(` * @returns { UseQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
4157
+ else if (mode === "mutation") lines.push(` * @returns { UseMutationResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
4158
+ else lines.push(` * @returns { UseInfiniteQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
4159
+ lines.push(` * @statusCodes [${endpoint.responseStatusCodes.join(", ")}]`);
4160
+ lines.push(" */");
4161
+ return lines.join("\n");
4162
+ }
4163
+ function renderQueryKeys({ resolver, queryEndpoints, tag }) {
4164
+ if (queryEndpoints.length === 0) return "";
4165
+ const lines = [];
4166
+ lines.push("export const keys = {");
4167
+ lines.push(` all: [${QUERIES_MODULE_NAME}] as const,`);
4168
+ for (const endpoint of queryEndpoints) {
4169
+ lines.push(` ${getEndpointName(endpoint)}: (${renderEndpointParams(resolver, endpoint, {
4170
+ pathParamsRequiredOnly: true,
4171
+ modelNamespaceTag: tag
4172
+ })}) => [...keys.all, "${endpoint.path}", ${renderEndpointArgs(resolver, endpoint, {})}] as const,`);
4173
+ if (resolver.options.infiniteQueries && isInfiniteQuery(endpoint, resolver.options)) lines.push(` ${getEndpointName(endpoint)}Infinite: (${renderEndpointParams(resolver, endpoint, {
4174
+ excludePageParam: true,
4175
+ pathParamsRequiredOnly: true,
4176
+ modelNamespaceTag: tag
4177
+ })}) => [...keys.all, "${endpoint.path}", "infinite", ${renderEndpointArgs(resolver, endpoint, { excludePageParam: true })}] as const,`);
4178
+ }
4179
+ lines.push("};");
4180
+ return lines.join("\n");
4181
+ }
4182
+ function renderInlineEndpoints({ resolver, endpoints, tag }) {
4183
+ const lines = [];
4184
+ for (const endpoint of endpoints) {
4185
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: tag });
4186
+ const endpointBody = getEndpointBody$1(endpoint);
4187
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
4188
+ const endpointConfig = renderInlineEndpointConfig(resolver, endpoint, tag);
4189
+ lines.push(`const ${getEndpointName(endpoint)} = (${endpointParams}${resolver.options.axiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4190
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
4191
+ lines.push(` { resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} },`);
4192
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
4193
+ if (endpointBody) lines.push(` ${resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
4194
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
4195
+ lines.push(` ${endpointConfig}`);
4196
+ lines.push(" );");
4197
+ lines.push("};");
4198
+ lines.push("");
4199
+ }
4200
+ return lines;
4201
+ }
4202
+ function renderInlineEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
4203
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
4204
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${addOptional ? ".optional()" : ""}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
4205
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
4206
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
4207
+ }
4208
+ function renderInlineEndpointConfig(resolver, endpoint, modelNamespaceTag) {
4209
+ const endpointConfig = getEndpointConfig(endpoint);
4210
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4211
+ if (Object.keys(endpointConfig).length === 0) return hasAxiosRequestConfig ? AXIOS_REQUEST_CONFIG_NAME : "";
4212
+ const lines = [];
4213
+ lines.push("{");
4214
+ if (hasAxiosRequestConfig) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
4215
+ if (endpointConfig.params) {
4216
+ lines.push(" params: {");
4217
+ for (const param of endpointConfig.params) {
4218
+ const value = resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
4219
+ lines.push(` ${param.name}: ${value},`);
4220
+ }
4221
+ lines.push(" },");
4222
+ }
4223
+ if (endpointConfig.headers) {
4224
+ lines.push(" headers: {");
4225
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
4226
+ lines.push(" },");
4227
+ }
4228
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
4229
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
4230
+ lines.push(" }");
4231
+ return lines.join("\n");
4232
+ }
4233
+ function renderQueryOptions({ resolver, endpoint, inlineEndpoints }) {
4234
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4235
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
4236
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4237
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4238
+ const lines = [];
4239
+ lines.push(`const ${getQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => ({`);
4240
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}(${endpointArgs}),`);
4241
+ lines.push(` queryFn: () => ${endpointFunction}(${endpointArgs}${hasAxiosRequestConfig ? `${endpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}),`);
4242
+ lines.push("});");
4243
+ return lines.join("\n");
4244
+ }
4245
+ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
4246
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4247
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4248
+ excludePageParam: true,
4249
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
4250
+ });
4251
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4252
+ const endpointArgsWithPage = renderEndpointArgs(resolver, endpoint, { replacePageParam: true });
4253
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4254
+ const lines = [];
4255
+ lines.push(`const ${getInfiniteQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => ({`);
4256
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}Infinite(${endpointArgsWithoutPage}),`);
4257
+ lines.push(` queryFn: ({ pageParam }: { pageParam: number }) => ${endpointFunction}(${endpointArgsWithPage}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}` : ""}),`);
4258
+ lines.push(" initialPageParam: 1,");
4259
+ lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }) => {`);
4260
+ lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
4261
+ lines.push(` return pageParam * limitParam < ${resolver.options.infiniteQueryResponseParamNames.totalItems} ? pageParam + 1 : null;`);
4262
+ lines.push(" },");
4263
+ lines.push("});");
4264
+ return lines.join("\n");
4265
+ }
4266
+ function renderPrefetchQuery({ resolver, endpoint }) {
4267
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4268
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
4269
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4270
+ const lines = [];
4271
+ lines.push(`export const ${getPrefetchQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}: ${AXIOS_REQUEST_CONFIG_TYPE}, ` : ""}options?: Omit<Parameters<QueryClient["prefetchQuery"]>[0], "queryKey" | "queryFn">): void => {`);
4272
+ lines.push(` void queryClient.prefetchQuery({ ...${getQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options });`);
4273
+ lines.push("};");
4274
+ return lines.join("\n");
4275
+ }
4276
+ function renderPrefetchInfiniteQuery({ resolver, endpoint }) {
4277
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4278
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4279
+ excludePageParam: true,
4280
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
4281
+ });
4282
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4283
+ const lines = [];
4284
+ lines.push(`export const ${getPrefetchInfiniteQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}: ${AXIOS_REQUEST_CONFIG_TYPE}, ` : ""}options?: Omit<Parameters<QueryClient["prefetchInfiniteQuery"]>[0], "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam">): void => {`);
4285
+ lines.push(` void queryClient.prefetchInfiniteQuery({ ...${getInfiniteQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options });`);
4286
+ lines.push("};");
4287
+ return lines.join("\n");
4288
+ }
4289
+ function renderQuery({ resolver, endpoint, inlineEndpoints }) {
4290
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4291
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4292
+ const tag = getEndpointTag(endpoint, resolver.options);
4293
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4294
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4295
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
4296
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4297
+ optionalPathParams: resolver.options.workspaceContext,
4298
+ modelNamespaceTag: tag
4299
+ });
4300
+ const queryOptionsName = getQueryOptionsName(endpoint);
4301
+ const hasQueryFnOverride = hasAclCheck;
4302
+ const queryOptionsArgs = `${resolvedEndpointArgs ? `{ ${resolvedEndpointArgs} }` : ""}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
4303
+ const lines = [];
4304
+ lines.push(renderQueryJsDocs({
4305
+ resolver,
4306
+ endpoint,
4307
+ mode: "query",
4308
+ tag
4309
+ }));
4310
+ lines.push(`export const ${getQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: AppQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4311
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4312
+ lines.push(...renderWorkspaceParamResolutions({
4313
+ replacements: workspaceParamReplacements,
4314
+ indent: " "
4315
+ }));
4316
+ lines.push(" ");
4317
+ lines.push(` return ${QUERY_HOOKS.query}({`);
4318
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
4319
+ if (hasQueryFnOverride) {
4320
+ lines.push(" queryFn: async () => {");
4321
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4322
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn();`);
4323
+ lines.push(" },");
4324
+ }
4325
+ lines.push(" ...options,");
4326
+ lines.push(" });");
4327
+ lines.push("};");
4328
+ return lines.join("\n");
4329
+ }
4330
+ function renderMutation({ resolver, endpoint, inlineEndpoints, precomputed }) {
4331
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4332
+ const hasMutationEffects = resolver.options.mutationEffects;
4333
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4334
+ const tag = getEndpointTag(endpoint, resolver.options);
4335
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4336
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4337
+ includeFileParam: true,
4338
+ optionalPathParams: resolver.options.workspaceContext,
4339
+ modelNamespaceTag: tag
4340
+ });
4341
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
4342
+ const destructuredMutationArgs = renderEndpointArgs(resolver, endpoint, { includeFileParam: true });
4343
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4344
+ const updateQueryEndpoints = precomputed?.updateQueryEndpoints ?? [];
4345
+ const destructuredVariables = precomputed?.destructuredVariables ?? getDestructuredVariables(resolver, endpoint, updateQueryEndpoints);
4346
+ const hasMutationFnBody = endpoint.mediaUpload || hasAclCheck || Object.keys(workspaceParamReplacements).length > 0;
4347
+ const mutationVariablesType = endpoint.mediaUpload ? `${endpointParams}${endpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : endpointParams;
4348
+ const lines = [];
4349
+ lines.push(renderQueryJsDocs({
4350
+ resolver,
4351
+ endpoint,
4352
+ mode: "mutation",
4353
+ tag
4354
+ }));
4355
+ lines.push(`export const ${getQueryName(endpoint, true)} = (options?: AppMutationOptions<typeof ${endpointFunction}, { ${mutationVariablesType} }>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4356
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
4357
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4358
+ if (Object.keys(workspaceParamReplacements).length > 0) lines.push(" const workspaceContext = OpenApiWorkspaceContext.useContext();");
4359
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<typeof ${QUERY_MODULE_ENUM}.${tag}>({ currentModule: ${QUERIES_MODULE_NAME} });`);
4360
+ lines.push("");
4361
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
4362
+ const mutationFnArg = endpointParams ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
4363
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => ${hasMutationFnBody ? "{ " : ""}`);
4364
+ for (const [paramName, resolvedParamName] of Object.entries(workspaceParamReplacements)) lines.push(` const ${resolvedParamName} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
4365
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4366
+ if (endpoint.mediaUpload) {
4367
+ lines.push(` const uploadInstructions = await ${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""});`);
4368
+ lines.push(" ");
4369
+ lines.push(" if (file && uploadInstructions.url) {");
4370
+ lines.push(" const method = (data?.method?.toLowerCase() ?? \"put\") as \"put\" | \"post\";");
4371
+ lines.push(" let dataToSend: File | FormData = file;");
4372
+ lines.push(" if (method === \"post\") {");
4373
+ lines.push(" dataToSend = new FormData();");
4374
+ lines.push(" if (uploadInstructions.fields) {");
4375
+ lines.push(" for (const [key, value] of uploadInstructions.fields) {");
4376
+ lines.push(" dataToSend.append(key, value);");
4377
+ lines.push(" }");
4378
+ lines.push(" }");
4379
+ lines.push(" dataToSend.append(\"file\", file);");
4380
+ lines.push(" }");
4381
+ lines.push(" await axios[method](uploadInstructions.url, dataToSend, {");
4382
+ lines.push(" headers: {");
4383
+ lines.push(" \"Content-Type\": file.type,");
4384
+ lines.push(" },");
4385
+ lines.push(" signal: abortController?.signal,");
4386
+ lines.push(" onUploadProgress: onUploadProgress");
4387
+ lines.push(" ? (progressEvent) => onUploadProgress({ loaded: progressEvent.loaded, total: progressEvent.total ?? 0 })");
4388
+ lines.push(" : undefined,");
4389
+ lines.push(" });");
4390
+ lines.push(" }");
4391
+ lines.push(" ");
4392
+ lines.push(" return uploadInstructions;");
4393
+ } else lines.push(` ${hasMutationFnBody ? "return " : ""}${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""})`);
4394
+ if (hasMutationFnBody) lines.push(" },");
4395
+ else lines.push(",");
4396
+ lines.push(" ...options,");
4397
+ lines.push(" onError: options?.onError ?? queryConfig.onError,");
4398
+ if (hasMutationEffects) {
4399
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
4400
+ if (updateQueryEndpoints.length > 0) {
4401
+ if (destructuredVariables.length > 0) lines.push(` const { ${destructuredVariables.join(", ")} } = variables;`);
4402
+ for (const [paramName, resolvedParamName] of Object.entries(workspaceParamReplacements)) lines.push(` const ${resolvedParamName} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
4403
+ lines.push(` const updateKeys = [${updateQueryEndpoints.map((e) => `keys.${getEndpointName(e)}(${renderEndpointArgs(resolver, e, { includeOnlyRequiredParams: true }, workspaceParamReplacements)})`).join(", ")}];`);
4404
+ lines.push(` await runMutationEffects(resData, variables, options, updateKeys);`);
4405
+ } else lines.push(" await runMutationEffects(resData, variables, options);");
4406
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
4407
+ lines.push(" },");
4408
+ }
4409
+ lines.push(" });");
4410
+ lines.push("};");
4411
+ return lines.join("\n");
4412
+ }
4413
+ function groupEndpoints(endpoints, resolver) {
4414
+ const queryEndpoints = [];
4415
+ const mutationEndpoints = [];
4416
+ const infiniteQueryEndpoints = [];
4417
+ const aclEndpoints = [];
4418
+ const infoByEndpoint = /* @__PURE__ */ new Map();
4419
+ const mutationDataByEndpoint = /* @__PURE__ */ new Map();
4420
+ for (const endpoint of endpoints) {
4421
+ const query = isQuery(endpoint);
4422
+ const mutation = isMutation(endpoint);
4423
+ const infiniteQuery = Boolean(resolver.options.infiniteQueries && query && isInfiniteQuery(endpoint, resolver.options));
4424
+ if (query) queryEndpoints.push(endpoint);
4425
+ if (mutation) mutationEndpoints.push(endpoint);
4426
+ if (infiniteQuery) infiniteQueryEndpoints.push(endpoint);
4427
+ if (endpoint.acl) aclEndpoints.push(endpoint);
4428
+ infoByEndpoint.set(endpoint, {
4429
+ query,
4430
+ mutation,
4431
+ infiniteQuery
4432
+ });
4433
+ }
4434
+ for (const endpoint of mutationEndpoints) {
4435
+ const updateQueryEndpoints = queryEndpoints.filter((queryEndpoint) => queryEndpoint.parameters.filter((param) => param.parameterObject?.required).every((pathParam) => endpoint.parameters.some((param) => param.name === pathParam.name)) && queryEndpoint.response === endpoint.response);
4436
+ mutationDataByEndpoint.set(endpoint, {
4437
+ updateQueryEndpoints,
4438
+ destructuredVariables: getDestructuredVariables(resolver, endpoint, updateQueryEndpoints)
4439
+ });
4440
+ }
4441
+ return {
4442
+ queryEndpoints,
4443
+ mutationEndpoints,
4444
+ infiniteQueryEndpoints,
4445
+ aclEndpoints,
4446
+ infoByEndpoint,
4447
+ mutationDataByEndpoint
4448
+ };
4449
+ }
4450
+ function renderInfiniteQuery({ resolver, endpoint, inlineEndpoints }) {
4451
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4452
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4453
+ const tag = getEndpointTag(endpoint, resolver.options);
4454
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4455
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4456
+ excludePageParam: true,
4457
+ optionalPathParams: resolver.options.workspaceContext,
4458
+ modelNamespaceTag: tag
4459
+ });
4460
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4461
+ const resolvedEndpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true }, workspaceParamReplacements);
4462
+ const queryOptionsName = getInfiniteQueryOptionsName(endpoint);
4463
+ const queryOptionsArgs = `${resolvedEndpointArgsWithoutPage ? `{ ${resolvedEndpointArgsWithoutPage} }` : ""}${hasAxiosRequestConfig ? `${resolvedEndpointArgsWithoutPage ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
4464
+ const hasQueryFnOverride = hasAclCheck;
4465
+ const lines = [];
4466
+ lines.push(renderQueryJsDocs({
4467
+ resolver,
4468
+ endpoint,
4469
+ mode: "infiniteQuery",
4470
+ tag
4471
+ }));
4472
+ lines.push(`export const ${getInfiniteQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }, ` : ""}options?: AppInfiniteQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4473
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4474
+ lines.push(...renderWorkspaceParamResolutions({
4475
+ replacements: workspaceParamReplacements,
4476
+ indent: " "
4477
+ }));
4478
+ lines.push("");
4479
+ lines.push(` return ${QUERY_HOOKS.infiniteQuery}({`);
4480
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
4481
+ if (hasQueryFnOverride) {
4482
+ lines.push(" queryFn: async ({ pageParam }) => {");
4483
+ lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4484
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ pageParam });`);
4485
+ lines.push(" },");
4486
+ }
4487
+ lines.push(" ...options,");
4488
+ lines.push(" });");
4489
+ lines.push("};");
4490
+ return lines.join("\n");
4491
+ }
4492
+
4493
+ //#endregion
4494
+ //#region src/generators/generate/generateAppRestClient.ts
4495
+ function generateAppRestClient(resolver) {
4496
+ return `import { RestClient } from "${PACKAGE_IMPORT_PATH}";
4497
+
4498
+ export const ${APP_REST_CLIENT_NAME} = new RestClient({
4499
+ config: {
4500
+ baseURL: "${resolver.getBaseUrl()}"
4501
+ },
4502
+ });
4503
+ `;
4504
+ }
4505
+
4506
+ //#endregion
4507
+ //#region src/generators/generate/generateQueryModules.ts
4508
+ function generateQueryModules({ resolver, data }) {
4509
+ const modules = [];
4510
+ data.forEach((_, tag) => {
4511
+ const endpoints = data.get(tag)?.endpoints;
4512
+ if (!endpoints || endpoints.length === 0) return;
4513
+ modules.push({
4514
+ tag,
4515
+ namespace: getNamespaceName({
4516
+ type: GenerateType.Queries,
4517
+ tag,
4518
+ options: resolver.options
4519
+ })
4520
+ });
4521
+ });
4522
+ const lines = [];
4523
+ lines.push("export const enum QueryModule {");
4524
+ for (const module of modules) lines.push(` ${module.tag} = "${module.namespace}",`);
4525
+ lines.push("}");
4526
+ return lines.join("\n");
4527
+ }
4528
+
4529
+ //#endregion
4530
+ //#region src/generators/utils/generate-files.utils.ts
4531
+ function getAclFiles(data, resolver) {
4532
+ if (!resolver.options.acl) return [];
4533
+ return [{
4534
+ fileName: getOutputFileName({
4535
+ output: resolver.options.output,
4536
+ fileName: getFileNameWithExtension(ACL_APP_ABILITY_FILE)
4537
+ }),
4538
+ content: generateAppAcl({
4539
+ resolver,
4540
+ data
4541
+ })
4542
+ }];
4543
+ }
4544
+ function getMutationEffectsFiles(data, resolver) {
4545
+ if (!resolver.options.mutationEffects) return [];
4546
+ return [{
4547
+ fileName: getOutputFileName({
4548
+ output: resolver.options.output,
4549
+ fileName: getFileNameWithExtension(QUERY_MODULES_FILE)
4550
+ }),
4551
+ content: generateQueryModules({
4552
+ resolver,
4553
+ data
4554
+ })
4555
+ }];
4556
+ }
4557
+ function getZodExtendedFiles(_data, _resolver) {
4558
+ return [];
4559
+ }
4560
+ function getAppRestClientFiles(resolver) {
4561
+ if (resolver.options.restClientImportPath !== DEFAULT_GENERATE_OPTIONS.restClientImportPath) return [];
4562
+ return [{
4563
+ fileName: getOutputFileName({
4564
+ output: resolver.options.output,
4565
+ fileName: getFileNameWithExtension(APP_REST_CLIENT_FILE)
4566
+ }),
4567
+ content: generateAppRestClient(resolver)
4568
+ }];
4569
+ }
4570
+
4571
+ //#endregion
4572
+ //#region src/generators/generateCodeFromOpenAPIDoc.ts
4573
+ function generateCodeFromOpenAPIDoc(openApiDoc, options, profiler) {
4574
+ const p = profiler ?? new Profiler(false);
4575
+ const importPath = options.standalone && options.importPath === "ts" ? "relative" : options.importPath;
4576
+ const { resolver, data } = p.runSync("data.extract", () => getDataFromOpenAPIDoc(openApiDoc, {
4577
+ ...options,
4578
+ importPath
4579
+ }, p));
4580
+ const generateFilesData = [];
4581
+ const appAclTags = [];
4582
+ const modelsOnly = Boolean(resolver.options.modelsOnly);
4583
+ const shouldGenerateEndpoints = !modelsOnly && Array.from(data.keys()).some((tag) => !shouldInlineEndpointsForTag(tag, resolver.options));
4584
+ const generateTypes = modelsOnly ? [GenerateType.Models] : [
4585
+ GenerateType.Models,
4586
+ ...shouldGenerateEndpoints ? [GenerateType.Endpoints] : [],
4587
+ GenerateType.Queries,
4588
+ ...resolver.options.acl ? [GenerateType.Acl] : [],
4589
+ ...resolver.options.builderConfigs ? [GenerateType.Configs] : []
4590
+ ];
4591
+ const generateFunctions = {
4592
+ [GenerateType.Models]: generateModels,
4593
+ [GenerateType.Endpoints]: generateEndpoints,
4594
+ [GenerateType.Queries]: generateQueries,
4595
+ [GenerateType.Acl]: generateAcl,
4596
+ [GenerateType.Configs]: generateConfigs
4597
+ };
4598
+ data.forEach((_, tag) => {
4599
+ generateTypes.forEach((type) => {
4600
+ const content = p.runSync(`render.${type}`, () => generateFunctions[type]({
4601
+ resolver,
4602
+ data,
4603
+ tag
4604
+ }));
4605
+ if (content) {
4606
+ const fileName = getOutputFileName({
4607
+ output: options.output,
4608
+ fileName: getTagFileName({
4609
+ tag,
4610
+ type,
4611
+ options
4612
+ })
4613
+ });
4614
+ generateFilesData.push({
4615
+ fileName,
4616
+ content
4617
+ });
4618
+ if (type === GenerateType.Acl) appAclTags.push(tag);
4619
+ }
4620
+ });
4621
+ });
4622
+ if (!modelsOnly) generateFilesData.push(...p.runSync("render.AclShared", () => getAclFiles(data, resolver)), ...p.runSync("render.MutationEffects", () => getMutationEffectsFiles(data, resolver)), ...p.runSync("render.ZodExtended", () => getZodExtendedFiles(data, resolver)), ...p.runSync("render.Standalone", () => getAppRestClientFiles(resolver)));
4623
+ return generateFilesData;
4624
+ }
4625
+
4626
+ //#endregion
4627
+ export { VALIDATION_ERROR_TYPE_TITLE as S, isMediaTypeAllowed as _, deepMerge as a, formatTag as b, getSchemaTsMetaType as c, getTagImportPath as d, getQueryName as f, groupByType as g, GenerateType as h, getDataFromOpenAPIDoc as i, getTsTypeBase as l, getNamespaceName as m, getOutputFileName as n, isMutation as o, DEFAULT_GENERATE_OPTIONS as p, writeGenerateFileData as r, isQuery as s, generateCodeFromOpenAPIDoc as t, getTagFileName as u, isParamMediaTypeAllowed as v, Profiler as x, invalidVariableNameCharactersToCamel as y };