@povio/openapi-codegen-cli 2.0.8-rc.1 → 2.0.8-rc.11

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