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

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