@povio/openapi-codegen-cli 2.0.8-rc.2 → 2.0.8-rc.21

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