@povio/openapi-codegen-cli 3.1.1 → 3.2.0-rc.10

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 (69) hide show
  1. package/README.md +63 -15
  2. package/dist/AuthGuard-GbtTDXs0.d.mts +32 -0
  3. package/dist/AuthGuard-qpAtHaBz.mjs +24 -0
  4. package/dist/acl.d.mts +6 -20
  5. package/dist/acl.mjs +8 -13
  6. package/dist/{auth.context-Bu5KW2sI.mjs → auth.context-COWO6ssl.mjs} +1 -21
  7. package/dist/auth.d.mts +2 -0
  8. package/dist/auth.mjs +3 -0
  9. package/dist/axios.d.mts +2 -0
  10. package/dist/axios.mjs +2 -0
  11. package/dist/{config-BU7wVf7U.d.mts → config-DgrOddSC.d.mts} +1 -2
  12. package/dist/config.d.mts +4 -0
  13. package/dist/config.mjs +5 -0
  14. package/dist/{error-handling-DSI86D3u.mjs → error-handling-BeydPL7s.mjs} +21 -51
  15. package/dist/{error-handling-D-mHJ60d.d.mts → error-handling-LPEPQV1V.d.mts} +3 -42
  16. package/dist/errors.d.mts +3 -0
  17. package/dist/errors.mjs +2 -0
  18. package/dist/generate.runner-CD7mlcJ4.mjs +184 -0
  19. package/dist/generate.utils-CT-LA-gX.cjs +2267 -0
  20. package/dist/generateCodeFromOpenAPIDoc-D9W5BtAt.mjs +2097 -0
  21. package/dist/{generateCodeFromOpenAPIDoc-DseBECa-.mjs → generateCodeFromOpenAPIDoc-DhI7CHeh.cjs} +1349 -2344
  22. package/dist/generator.d.mts +3 -10
  23. package/dist/generator.mjs +9 -9
  24. package/dist/getDataFromOpenAPIDoc-D8w0QElH.mjs +2011 -0
  25. package/dist/i18n-B_brQh4X.d.mts +38 -0
  26. package/dist/i18n-D-FesqFb.mjs +36 -0
  27. package/dist/index.d.mts +12 -200
  28. package/dist/index.mjs +12 -264
  29. package/dist/metro.cjs +114 -4959
  30. package/dist/metro.d.mts +3 -4
  31. package/dist/metro.mjs +4 -9
  32. package/dist/native-bindings-BTQGSGhU.mjs +1480 -0
  33. package/dist/native-rest-interceptor-CAWR8H5Y.mjs +208 -0
  34. package/dist/native-rest-interceptor-Cz6saoq5.d.mts +46 -0
  35. package/dist/native.d.mts +3 -0
  36. package/dist/native.mjs +3 -0
  37. package/dist/openapi-codegen-native-darwin-arm64.node +0 -0
  38. package/dist/openapi-codegen-native-linux-x64.node +0 -0
  39. package/dist/openapi-codegen-native-win32-x64.node +0 -0
  40. package/dist/{openapi-codegen.runner-Co_bG00_.mjs → openapi-codegen.runner-C4TIXQNx.mjs} +4 -5
  41. package/dist/{openapi-source.runner-wLs5vqw6.mjs → openapi-source.runner-BZ6ZLgRO.mjs} +19 -10
  42. package/dist/{openapi-source.runner-BSIrB6ny.d.mts → openapi-source.runner-ykstqlPC.d.mts} +2 -8
  43. package/dist/{options-CE4Koxof.d.mts → options-KPf-Fti5.d.mts} +6 -1
  44. package/dist/query.d.mts +3 -0
  45. package/dist/query.mjs +3 -0
  46. package/dist/queryConfig.context-CRJOgf19.d.mts +22 -0
  47. package/dist/queryConfig.context-CldQ5YL9.mjs +34 -0
  48. package/dist/rest-client-CQyFvqYC.d.mts +55 -0
  49. package/dist/rest-interceptor-D5NCNTm1.mjs +115 -0
  50. package/dist/rest-transport.types-DM5-qyOJ.d.mts +66 -0
  51. package/dist/rest-transport.types-DxitRtsB.mjs +11 -0
  52. package/dist/rest.d.mts +2 -0
  53. package/dist/rest.mjs +2 -0
  54. package/dist/rest.utils-rezWAIYL.d.mts +10 -0
  55. package/dist/router.context-EPlMBk3G.mjs +21 -0
  56. package/dist/sh.d.mts +1 -1
  57. package/dist/sh.mjs +41 -71
  58. package/dist/tiny.d.mts +1 -3
  59. package/dist/tiny.mjs +2 -3
  60. package/dist/useMutationEffects-DIdL8tlx.d.mts +29 -0
  61. package/dist/useMutationEffects-PB1fvKWM.mjs +68 -0
  62. package/dist/vite.d.mts +3 -4
  63. package/dist/vite.mjs +6 -10
  64. package/dist/workspace.context-XWvQ_7Hg.mjs +26 -0
  65. package/dist/workspace.context-isVY9ves.d.mts +23 -0
  66. package/dist/zod.d.mts +2 -7
  67. package/dist/zod.mjs +2 -4
  68. package/package.json +73 -26
  69. package/dist/generate.runner-C1HrS_9G.mjs +0 -90
@@ -0,0 +1,2097 @@
1
+ import { r as getZodSchemaRefs, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-D8w0QElH.mjs";
2
+ import { $ as getImportedAbilityFunctionName, A as getEndpointsImports, An as NATIVE_RESPONSE_TYPE, At as APP_REST_CLIENT_NAME, B as getPrefetchInfiniteQueryName, Bt as PACKAGE_IMPORT_PATH, C as getAppRestClientImportPath, Cn as ZOD_IMPORT, D as getTagFileName, Dn as AXIOS_REQUEST_CONFIG_TYPE, Dt as isEnumZodSchema, E as getQueryTypesImportPath, En as AXIOS_REQUEST_CONFIG_NAME, F as mergeImports, Ft as QUERY_MODULE_ENUM, G as getAbilityConditionType, H as getQueryName, Ht as getNamespaceName, I as getImportedInfiniteQueryName, In as shouldInlineEndpointsForTag, It as QUERY_OPTIONS_TYPES, J as getAbilityFunctionName, K as getAbilityConditionsTypes, L as getImportedQueryName, Ln as camelToSpaceSeparated, Lt as ZOD_EXTENDED, M as getInfiniteQueriesImports, Mt as DOMAIN_ERRORS_FILE, N as getModelsImports, Nn as getEndpointTag, Nt as MUTATION_EFFECTS, O as getTagImportPath, Ot as isNamedZodSchema, P as getQueriesImports, Pt as QUERY_MODULES_FILE, Q as getAppAbilitiesType, R as getInfiniteQueryName, Rn as capitalize, Rt as CONFIG_PACKAGE_IMPORT_PATH, T as getQueryModulesImportPath, Tn as AXIOS_IMPORT, U as getQueryOptionsName, V as getPrefetchQueryName, Vn as kebabToCamel, Vt as REST_PACKAGE_IMPORT_PATH, W as getAbilityAction, Wn as Profiler, X as getAbilitySubjectTypes, Y as getAbilitySubject, Z as getAclData, Zt as isParamMediaTypeAllowed, _ as hasEndpointConfig, _t as isReadAllEndpoint, an as wrapWithQuotesIfNeeded, at as getZodSchemaInferedTypeName, b as requiresBody, bt as invalidVariableNameCharactersToCamel, c as getDestructuredVariables, cn as isReferenceObject, ct as getSchemaDescriptions, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, et as hasAbilityConditions, f as getEndpointBody, fn as ANY_SCHEMA, ft as getPathSegments, g as getImportedEndpointName, gt as isPathSegmentParam, h as getEndpointPath, ht as isDeleteEndpoint, it as getZodSchemaDescription, j as getImportPath, jn as getRequestConfigTypeName, jt as BUILDERS_UTILS, k as getAclImports, kn as JSON_APPLICATION_FORMAT, kt as APP_REST_CLIENT_FILE, l as isInfiniteQuery, ln as isSchemaObject, m as getEndpointName, mt as isCreateEndpoint, n as shouldUseNativeCodegen, nt as getImportedZodSchemaInferedTypeName, ot as getZodSchemaPropertyDescriptions, p as getEndpointConfig, pt as isBulkDeleteEndpoint, q as getAbilityDescription, r as getOutputFileName, rt as getImportedZodSchemaName, st as getZodSchemaType, t as compileNativeData, tt as renderAclCheckCall, u as isMutation, ut as getUniqueArray, v as mapEndpointParamsToFunctionParams, vt as isReadEndpoint, w as getFileNameWithExtension, wn as AXIOS_DEFAULT_IMPORT_NAME, y as renderMediaUploadMutationBody, yt as isUpdateEndpoint, z as getInfiniteQueryOptionsName, zt as NATIVE_PACKAGE_IMPORT_PATH } from "./native-bindings-BTQGSGhU.mjs";
3
+ import "node:module";
4
+ //#region \0rolldown/runtime.js
5
+ var __defProp = Object.defineProperty;
6
+ var __exportAll = (all, no_symbols) => {
7
+ let target = {};
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
13
+ return target;
14
+ };
15
+ //#endregion
16
+ //#region src/generators/const/acl.const.ts
17
+ const ACL_APP_ABILITY_FILE = {
18
+ fileName: "acl/app.ability",
19
+ extension: "ts"
20
+ };
21
+ const ACL_APP_ABILITIES = "AppAbilities";
22
+ const ACL_CHECK_HOOK = "useAclCheck";
23
+ const CASL_ABILITY_BINDING = {
24
+ abilityTuple: "AbilityTuple",
25
+ pureAbility: "PureAbility",
26
+ forcedSubject: "ForcedSubject",
27
+ subjectType: "Subject",
28
+ subject: "subject"
29
+ };
30
+ const CASL_ABILITY_IMPORT = {
31
+ bindings: [
32
+ CASL_ABILITY_BINDING.abilityTuple,
33
+ CASL_ABILITY_BINDING.pureAbility,
34
+ CASL_ABILITY_BINDING.forcedSubject,
35
+ CASL_ABILITY_BINDING.subjectType,
36
+ CASL_ABILITY_BINDING.subject
37
+ ],
38
+ from: "@casl/ability"
39
+ };
40
+ //#endregion
41
+ //#region src/generators/generate/generateAcl.ts
42
+ function generateAcl({ resolver, data, tag }) {
43
+ const nativeContent = resolver.getNativeRenderedAcl?.(tag);
44
+ if (nativeContent) return nativeContent;
45
+ const aclData = getAclData({
46
+ resolver,
47
+ data,
48
+ tag
49
+ });
50
+ if (!aclData) return;
51
+ const { hasAdditionalAbilityImports, modelsImports, endpoints } = aclData;
52
+ const hasWorkspaceContext = endpoints.some((endpoint) => getWorkspaceConditionNames(resolver, endpoint).length > 0);
53
+ const caslAbilityTupleImport = {
54
+ bindings: [...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject, CASL_ABILITY_BINDING.subject] : []],
55
+ typeBindings: [CASL_ABILITY_BINDING.abilityTuple],
56
+ from: CASL_ABILITY_IMPORT.from
57
+ };
58
+ const workspaceContextImport = {
59
+ bindings: ["useWorkspaceContext"],
60
+ from: CONFIG_PACKAGE_IMPORT_PATH
61
+ };
62
+ const lines = [];
63
+ lines.push(renderImport$4(caslAbilityTupleImport));
64
+ if (hasWorkspaceContext) lines.push(renderImport$4(workspaceContextImport));
65
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
66
+ lines.push("");
67
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
68
+ type: "acl",
69
+ tag,
70
+ options: resolver.options
71
+ })} {`);
72
+ for (const endpoint of endpoints) {
73
+ lines.push(renderAbilityFunction({
74
+ resolver,
75
+ endpoint
76
+ }));
77
+ lines.push("");
78
+ }
79
+ if (resolver.options.tsNamespaces) lines.push("}");
80
+ return lines.join("\n").trimEnd() + "\n";
81
+ }
82
+ function generateAppAcl({ resolver, data }) {
83
+ const nativeContent = resolver.getNativeRenderedShared?.("appAcl");
84
+ if (nativeContent) return nativeContent;
85
+ const { appAbilitiesType, hasAdditionalAbilityImports, modelsImports } = getAppAbilitiesType({
86
+ resolver,
87
+ data
88
+ });
89
+ const caslAbilityTupleImport = {
90
+ bindings: [],
91
+ typeBindings: [
92
+ CASL_ABILITY_BINDING.pureAbility,
93
+ CASL_ABILITY_BINDING.abilityTuple,
94
+ ...!appAbilitiesType ? [CASL_ABILITY_BINDING.subjectType] : [],
95
+ ...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject] : []
96
+ ],
97
+ from: CASL_ABILITY_IMPORT.from,
98
+ typeOnly: true
99
+ };
100
+ const lines = [];
101
+ lines.push(renderImport$4(caslAbilityTupleImport));
102
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
103
+ lines.push("");
104
+ if (appAbilitiesType) {
105
+ lines.push(`export type ${ACL_APP_ABILITIES} = `);
106
+ for (const [action, subjects] of Object.entries(appAbilitiesType)) lines.push(`| ${CASL_ABILITY_BINDING.abilityTuple}<"${action}", ${subjects.join(" | ")}>`);
107
+ } else lines.push(`export type ${ACL_APP_ABILITIES} = ${CASL_ABILITY_BINDING.abilityTuple}<string, ${CASL_ABILITY_BINDING.subjectType}>;`);
108
+ lines.push("");
109
+ lines.push(`export type AppAbility = PureAbility<${ACL_APP_ABILITIES}>;`);
110
+ return lines.join("\n");
111
+ }
112
+ function renderImport$4(importData) {
113
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
114
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
115
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
116
+ }
117
+ function getWorkspaceContextAllowList$1(workspaceContext) {
118
+ return new Set(workspaceContext);
119
+ }
120
+ function getWorkspaceConditionNames(resolver, endpoint) {
121
+ const allowList = getWorkspaceContextAllowList$1(resolver.options.workspaceContext);
122
+ return (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => condition.name).filter((name) => allowList.has(name));
123
+ }
124
+ function renderWorkspaceAclHook({ resolver, endpoint }) {
125
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
126
+ const workspaceConditionNames = getWorkspaceConditionNames(resolver, endpoint);
127
+ if (workspaceConditionNames.length === 0) return;
128
+ const workspaceConditionNameSet = new Set(workspaceConditionNames);
129
+ const objectRequired = abilityConditionsTypes.some((propertyType) => propertyType.required && !workspaceConditionNameSet.has(propertyType.name));
130
+ const objectParams = abilityConditionsTypes.map((propertyType) => {
131
+ const isWorkspaceCondition = workspaceConditionNameSet.has(propertyType.name);
132
+ return `${propertyType.name}${propertyType.required && !isWorkspaceCondition ? "" : "?"}: ${renderConditionType(resolver, endpoint, propertyType)}, `;
133
+ }).join("");
134
+ const contextType = abilityConditionsTypes.filter((propertyType) => workspaceConditionNameSet.has(propertyType.name)).map((propertyType) => `${propertyType.name}?: ${renderConditionType(resolver, endpoint, propertyType)}`).join("; ");
135
+ const contextBindings = workspaceConditionNames.map((name) => `${name}: ${name}Workspace`).join(", ");
136
+ const lines = [];
137
+ lines.push(`export const use${capitalize(getAbilityFunctionName(endpoint))} = (`);
138
+ lines.push(` object${objectRequired ? "" : "?"}: { ${objectParams} } `);
139
+ lines.push(") => {");
140
+ lines.push(` const { ${contextBindings} } = useWorkspaceContext<{ ${contextType} }>();`);
141
+ for (const conditionName of workspaceConditionNames) {
142
+ const resolvedName = `normalize${capitalize(conditionName)}`;
143
+ lines.push(` const ${resolvedName} = object?.${conditionName} ?? ${conditionName}Workspace;`);
144
+ lines.push(` if (!${resolvedName}) {`);
145
+ lines.push(` throw Error(\`${capitalize(conditionName)} not provided\`);`);
146
+ lines.push(" }");
147
+ }
148
+ lines.push(` return ${getAbilityFunctionName(endpoint)}({ ...object, ${workspaceConditionNames.map((conditionName) => `${conditionName}: normalize${capitalize(conditionName)}`).join(", ")} });`);
149
+ lines.push("};");
150
+ return lines.join("\n");
151
+ }
152
+ function renderAbilityFunction({ resolver, endpoint }) {
153
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
154
+ const hasConditions = hasAbilityConditions(endpoint);
155
+ const lines = [];
156
+ const abilityQuery = endpoint.method === "get" ? endpoint.mediaDownload ? `\`${getQueryName(endpoint)}\` query or \`${getQueryName(endpoint, true)}\` mutation` : `\`${getQueryName(endpoint)}\` query` : `\`${getQueryName(endpoint)}\` mutation`;
157
+ lines.push("/**");
158
+ lines.push(` * Use for ${abilityQuery} ability. ${hasConditions ? "For global ability, omit the object parameter." : ""}${getAbilityDescription(endpoint) ? "" : ""}`);
159
+ if (getAbilityDescription(endpoint)) lines.push(` * @description ${getAbilityDescription(endpoint)}`);
160
+ if (hasConditions) for (const propertyType of abilityConditionsTypes) lines.push(` * @param { ${renderConditionType(resolver, endpoint, propertyType)} } object.${propertyType.name} ${propertyType.name} from ${propertyType.info}`);
161
+ lines.push(` * @returns { AbilityTuple } An ability tuple indicating the user's ability to use ${abilityQuery}`);
162
+ lines.push(" */");
163
+ lines.push(`export const ${getAbilityFunctionName(endpoint)} = (`);
164
+ if (hasConditions) lines.push(` object?: { ${abilityConditionsTypes.map((propertyType) => `${propertyType.name}${propertyType.required ? "" : "?"}: ${renderConditionType(resolver, endpoint, propertyType)}, `).join("")} } `);
165
+ lines.push(") => [");
166
+ lines.push(` "${getAbilityAction(endpoint)}",`);
167
+ lines.push(` ${hasConditions ? `object ? subject("${getAbilitySubject(endpoint)}", object) : "${getAbilitySubject(endpoint)}"` : `"${getAbilitySubject(endpoint)}"`}`);
168
+ lines.push(`] as ${CASL_ABILITY_BINDING.abilityTuple}<"${getAbilityAction(endpoint)}", ${getAbilitySubjectTypes(endpoint, resolver, getEndpointTag(endpoint, resolver.options)).join(" | ")}>;`);
169
+ const workspaceAclHook = renderWorkspaceAclHook({
170
+ resolver,
171
+ endpoint
172
+ });
173
+ if (workspaceAclHook) {
174
+ lines.push("");
175
+ lines.push(workspaceAclHook);
176
+ }
177
+ return lines.join("\n");
178
+ }
179
+ function renderConditionType(resolver, endpoint, propertyType) {
180
+ return getAbilityConditionType(propertyType, resolver, getEndpointTag(endpoint, resolver.options));
181
+ }
182
+ //#endregion
183
+ //#region src/generators/const/buildConfigs.const.ts
184
+ const BUILD_CONFIG_SUFFIX = "config";
185
+ //#endregion
186
+ //#region src/generators/utils/generate/generate.configs.utils.ts
187
+ function getBuilderConfigs({ data, tag, resolver }) {
188
+ const endpoints = data.get(tag)?.endpoints;
189
+ if (!endpoints || endpoints.length === 0) return {
190
+ configs: [],
191
+ hasZodImport: false,
192
+ modelsImports: [],
193
+ queriesImports: [],
194
+ aclImports: []
195
+ };
196
+ const extendedEndpoints = endpoints.map((endpoint) => ({
197
+ ...endpoint,
198
+ pathSegments: getPathSegments(endpoint.path)
199
+ }));
200
+ const namedReadAllEndpoints = resolveBuilderConfigNames(extendedEndpoints.filter((endpoint) => isReadAllEndpoint(endpoint, resolver.options)));
201
+ let hasZodImport = false;
202
+ const importedZodSchemas = [];
203
+ const importedEndpoints = [];
204
+ const importedInfiniteEndpoints = [];
205
+ const configs = Object.entries(namedReadAllEndpoints).map(([name, readAllEndpoint]) => {
206
+ const columnsConfig = getColumnsConfig(resolver, readAllEndpoint);
207
+ if (!columnsConfig) return;
208
+ importedEndpoints.push(readAllEndpoint);
209
+ importedInfiniteEndpoints.push(readAllEndpoint);
210
+ if (columnsConfig.zodSchema) if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
211
+ else hasZodImport = true;
212
+ if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
213
+ const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
214
+ if (filter) importedZodSchemas.push(filter.zodSchema);
215
+ const config = {
216
+ name,
217
+ title: capitalize(camelToSpaceSeparated(name.replace(/config$/i, ""))),
218
+ readAll: {
219
+ acl: getAclConfig(readAllEndpoint, resolver.options),
220
+ paginated: getImportedQueryName(readAllEndpoint, resolver.options),
221
+ infinite: resolver.options.infiniteQueries ? getImportedInfiniteQueryName(readAllEndpoint, resolver.options) : void 0,
222
+ filters: getInputsConfig(resolver, filter),
223
+ columns: columnsConfig.columns
224
+ }
225
+ };
226
+ const readEndpoint = extendedEndpoints.find((endpoint) => isReadEndpoint(endpoint, readAllEndpoint));
227
+ if (readEndpoint) {
228
+ importedEndpoints.push(readEndpoint);
229
+ let responseSchema = readEndpoint.response;
230
+ if (isNamedZodSchema(responseSchema)) {
231
+ importedZodSchemas.push(responseSchema);
232
+ responseSchema = getImportedZodSchemaName(resolver, responseSchema);
233
+ } else hasZodImport = true;
234
+ config.read = {
235
+ acl: getAclConfig(readEndpoint, resolver.options),
236
+ schema: responseSchema,
237
+ query: getImportedQueryName(readEndpoint, resolver.options)
238
+ };
239
+ }
240
+ const createEndpoint = extendedEndpoints.find((endpoint) => isCreateEndpoint(endpoint, readAllEndpoint));
241
+ if (createEndpoint) {
242
+ importedEndpoints.push(createEndpoint);
243
+ const body = getEndpointBody(createEndpoint);
244
+ if (body) {
245
+ importedZodSchemas.push(body.zodSchema);
246
+ config.create = {
247
+ acl: getAclConfig(createEndpoint, resolver.options),
248
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
249
+ mutation: createEndpoint,
250
+ inputDefs: getInputsConfig(resolver, body)
251
+ };
252
+ }
253
+ }
254
+ const updateEndpoint = extendedEndpoints.find((endpoint) => isUpdateEndpoint(endpoint, readAllEndpoint));
255
+ if (updateEndpoint) {
256
+ importedEndpoints.push(updateEndpoint);
257
+ const body = getEndpointBody(updateEndpoint);
258
+ if (body) {
259
+ importedZodSchemas.push(body.zodSchema);
260
+ config.update = {
261
+ acl: getAclConfig(updateEndpoint, resolver.options),
262
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
263
+ mutation: updateEndpoint,
264
+ inputDefs: getInputsConfig(resolver, body)
265
+ };
266
+ }
267
+ }
268
+ const deleteEndpoint = extendedEndpoints.find((endpoint) => isDeleteEndpoint(endpoint, readAllEndpoint));
269
+ if (deleteEndpoint) {
270
+ importedEndpoints.push(deleteEndpoint);
271
+ const body = getEndpointBody(deleteEndpoint);
272
+ if (body) {
273
+ importedZodSchemas.push(body.zodSchema);
274
+ config.delete = {
275
+ acl: getAclConfig(deleteEndpoint, resolver.options),
276
+ mutation: deleteEndpoint
277
+ };
278
+ }
279
+ }
280
+ const bulkDeleteEndpoint = extendedEndpoints.find((endpoint) => isBulkDeleteEndpoint(endpoint, readAllEndpoint));
281
+ if (bulkDeleteEndpoint) {
282
+ importedEndpoints.push(bulkDeleteEndpoint);
283
+ const body = getEndpointBody(bulkDeleteEndpoint);
284
+ if (body) {
285
+ importedZodSchemas.push(body.zodSchema);
286
+ config.bulkDelete = {
287
+ acl: getAclConfig(bulkDeleteEndpoint, resolver.options),
288
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
289
+ mutation: bulkDeleteEndpoint,
290
+ inputDefs: getInputsConfig(resolver, body)
291
+ };
292
+ }
293
+ }
294
+ return config;
295
+ });
296
+ const modelsImports = getModelsImports({
297
+ resolver,
298
+ tag,
299
+ zodSchemas: importedZodSchemas
300
+ });
301
+ const queriesImports = getQueriesImports({
302
+ tag,
303
+ endpoints: importedEndpoints,
304
+ options: resolver.options
305
+ });
306
+ const infiniteQueriesImports = resolver.options.infiniteQueries ? getInfiniteQueriesImports({
307
+ tag,
308
+ endpoints: importedInfiniteEndpoints,
309
+ options: resolver.options
310
+ }) : [];
311
+ const aclImports = getAclImports({
312
+ tag,
313
+ endpoints: importedEndpoints.filter((endpoint) => endpoint.acl),
314
+ options: resolver.options
315
+ });
316
+ return {
317
+ configs: configs.filter(Boolean),
318
+ hasZodImport,
319
+ modelsImports,
320
+ queriesImports: mergeImports(resolver.options, queriesImports, infiniteQueriesImports),
321
+ aclImports
322
+ };
323
+ }
324
+ function resolveBuilderConfigNames(endpoints) {
325
+ const sortedEndpoints = endpoints.map((endpoint) => ({
326
+ ...endpoint,
327
+ namePathSegments: endpoint.pathSegments.filter((segment) => !isPathSegmentParam(segment))
328
+ })).toSorted((a, b) => a.namePathSegments.length - b.namePathSegments.length);
329
+ const namedEndpoints = {};
330
+ for (const endpoint of sortedEndpoints) {
331
+ const namePathSegments = endpoint.namePathSegments;
332
+ let name = namePathSegments.length > 0 ? `${kebabToCamel(namePathSegments.pop())}${capitalize(BUILD_CONFIG_SUFFIX)}` : BUILD_CONFIG_SUFFIX;
333
+ while (namedEndpoints[name]) {
334
+ if (namePathSegments.length === 0) throw new Error(`Can't uniquely resolve builder config name: ${name}`);
335
+ name = `${kebabToCamel(namePathSegments.pop())}${capitalize(name)}`;
336
+ }
337
+ namedEndpoints[name] = endpoint;
338
+ }
339
+ return namedEndpoints;
340
+ }
341
+ function getAclConfig(endpoint, options) {
342
+ return options.acl && endpoint.acl ? getImportedAbilityFunctionName(endpoint, options) : void 0;
343
+ }
344
+ function getInputsConfig(resolver, endpointParameter) {
345
+ if (!endpointParameter) return;
346
+ let schema;
347
+ if (endpointParameter.type === "Body") schema = endpointParameter.bodyObject?.content?.[JSON_APPLICATION_FORMAT]?.schema;
348
+ else schema = endpointParameter.parameterObject?.schema;
349
+ if (!schema) return;
350
+ const schemaObj = resolver.resolveObject(schema);
351
+ const inputs = Object.keys(schemaObj?.properties ?? {}).reduce((acc, key) => ({
352
+ ...acc,
353
+ [key]: true
354
+ }), {});
355
+ return {
356
+ schema: getImportedZodSchemaName(resolver, endpointParameter.zodSchema),
357
+ options: { inputs }
358
+ };
359
+ }
360
+ function resolveReadAllItemZodSchema(resolver, endpoint, itemSchema, itemsPropertyKey) {
361
+ if (isReferenceObject(itemSchema)) return resolver.getZodSchemaNameByRef(itemSchema.$ref);
362
+ if (isNamedZodSchema(endpoint.response)) return `${getImportedZodSchemaName(resolver, endpoint.response)}.shape.${itemsPropertyKey}.element`;
363
+ return ANY_SCHEMA;
364
+ }
365
+ function getColumnsConfig(resolver, endpoint) {
366
+ const endpointResponse = endpoint.responseObject;
367
+ if (!endpointResponse) return;
368
+ const schema = endpointResponse.content?.[JSON_APPLICATION_FORMAT]?.schema;
369
+ if (!schema) return;
370
+ const properties = getSchemaProperties(resolver, schema);
371
+ const arrayPropertyKeys = Object.keys(properties).filter((key) => resolver.resolveObject(properties[key]).type === "array");
372
+ arrayPropertyKeys.sort((a, b) => {
373
+ const aIndex = resolver.options.dataResponseParamNames.indexOf(a);
374
+ const bIndex = resolver.options.dataResponseParamNames.indexOf(b);
375
+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
376
+ if (aIndex !== -1) return -1;
377
+ if (bIndex !== -1) return 1;
378
+ return a.localeCompare(b);
379
+ });
380
+ const propertyKey = arrayPropertyKeys[0];
381
+ if (!propertyKey) return;
382
+ const dataSchemaObj = resolver.resolveObject(properties[propertyKey]);
383
+ if (!dataSchemaObj || dataSchemaObj.type !== "array") return;
384
+ const itemSchema = dataSchemaObj.items;
385
+ const itemSchemaObj = resolver.resolveObject(itemSchema);
386
+ if (!itemSchemaObj) return;
387
+ const zodSchema = resolveReadAllItemZodSchema(resolver, endpoint, itemSchema, propertyKey);
388
+ const columns = Object.keys(itemSchemaObj?.properties ?? {}).reduce((acc, key) => ({
389
+ ...acc,
390
+ [key]: true
391
+ }), {});
392
+ const sortableEnumSchemaName = endpoint.parameters.find((param) => param.parameterSortingEnumSchemaName)?.parameterSortingEnumSchemaName;
393
+ return {
394
+ columns: {
395
+ schema: getImportedZodSchemaName(resolver, zodSchema),
396
+ options: {
397
+ columns,
398
+ sortable: sortableEnumSchemaName ? getImportedZodSchemaName(resolver, sortableEnumSchemaName) : void 0
399
+ }
400
+ },
401
+ zodSchema,
402
+ sortableEnumSchemaName
403
+ };
404
+ }
405
+ function getSchemaProperties(resolver, schema) {
406
+ const schemaObj = resolver.resolveObject(schema);
407
+ if (schemaObj.properties) return schemaObj.properties;
408
+ else if ("allOf" in schemaObj && schemaObj.allOf) return schemaObj.allOf.reduce((acc, cur) => ({
409
+ ...acc,
410
+ ...getSchemaProperties(resolver, cur)
411
+ }), {});
412
+ return {};
413
+ }
414
+ //#endregion
415
+ //#region src/generators/const/queries.const.ts
416
+ const QUERY_HOOKS = {
417
+ query: "useQuery",
418
+ infiniteQuery: "useInfiniteQuery",
419
+ mutation: "useMutation"
420
+ };
421
+ const QUERY_IMPORT = {
422
+ bindings: [
423
+ QUERY_HOOKS.query,
424
+ QUERY_HOOKS.infiniteQuery,
425
+ QUERY_HOOKS.mutation
426
+ ],
427
+ from: "@tanstack/react-query"
428
+ };
429
+ const QUERIES_MODULE_NAME = "moduleName";
430
+ //#endregion
431
+ //#region src/generators/generate/generateConfigs.ts
432
+ function generateConfigs(generateTypeParams) {
433
+ const { configs, hasZodImport, modelsImports, queriesImports, aclImports } = getBuilderConfigs(generateTypeParams);
434
+ if (configs.length === 0) return;
435
+ const { resolver, tag } = generateTypeParams;
436
+ const endpoints = configs.flatMap((config) => [
437
+ config.create?.mutation,
438
+ config.update?.mutation,
439
+ config.delete?.mutation,
440
+ config.bulkDelete?.mutation
441
+ ]).filter((m) => typeof m !== "string" && m !== void 0);
442
+ const hasMutation = endpoints.length > 0;
443
+ const hasAclCheck = resolver.options.checkAcl && endpoints.some((e) => e.acl);
444
+ const hasMutationEffects = resolver.options.mutationEffects && hasMutation;
445
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError && hasMutation;
446
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
447
+ const nativeClient = resolver.options.restClient === "native";
448
+ const hasAxiosDefaultImport = !nativeClient && endpoints.some((e) => e.mediaUpload);
449
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasAxiosDefaultImport);
450
+ const axiosImport = {
451
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
452
+ bindings: [],
453
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
454
+ from: "axios"
455
+ };
456
+ const nativeImport = {
457
+ bindings: [],
458
+ typeBindings: nativeClient && hasAxiosRequestConfig ? [getRequestConfigTypeName("native")] : [],
459
+ from: REST_PACKAGE_IMPORT_PATH
460
+ };
461
+ const appRestClientImport = {
462
+ bindings: [APP_REST_CLIENT_NAME],
463
+ from: getAppRestClientImportPath(resolver.options)
464
+ };
465
+ const endpointsImports = getEndpointsImports({
466
+ tag,
467
+ endpoints,
468
+ options: resolver.options
469
+ });
470
+ const queryImport = {
471
+ bindings: [QUERY_HOOKS.mutation],
472
+ from: "@tanstack/react-query"
473
+ };
474
+ const queryTypesImport = {
475
+ bindings: [...hasMutationDefaultOnError ? ["OpenApiQueryConfig"] : []],
476
+ typeBindings: [QUERY_OPTIONS_TYPES.mutation],
477
+ from: getQueryTypesImportPath(resolver.options)
478
+ };
479
+ const mutationEffectsImport = {
480
+ bindings: [MUTATION_EFFECTS.hookName],
481
+ typeBindings: [MUTATION_EFFECTS.optionsType],
482
+ from: resolver.options.mutationEffectsImportPath
483
+ };
484
+ const queryModulesImport = {
485
+ bindings: [QUERY_MODULE_ENUM],
486
+ from: getQueryModulesImportPath(resolver.options)
487
+ };
488
+ const aclCheckImport = {
489
+ bindings: [ACL_CHECK_HOOK],
490
+ from: resolver.options.aclCheckImportPath
491
+ };
492
+ const hasDynamicInputsImport = configs.some((config) => config.readAll.filters || config.create?.inputDefs || config.update?.inputDefs);
493
+ const dynamicInputsImport = {
494
+ bindings: [BUILDERS_UTILS.dynamicInputs],
495
+ from: resolver.options.dynamicInputsImportPath
496
+ };
497
+ const hasDynamicColumnsImport = configs.some((config) => config.readAll.columns);
498
+ const dynamicColumnsImport = {
499
+ bindings: [BUILDERS_UTILS.dynamicColumns],
500
+ from: resolver.options.dynamicColumnsImportPath
501
+ };
502
+ const lines = [];
503
+ if (hasAxiosImport) lines.push(renderImport$3(axiosImport));
504
+ if (nativeImport.typeBindings?.length) lines.push(renderImport$3(nativeImport));
505
+ if (nativeClient && endpoints.some((endpoint) => endpoint.mediaUpload)) lines.push(renderImport$3(appRestClientImport));
506
+ if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
507
+ if (hasDynamicInputsImport) lines.push(renderImport$3(dynamicInputsImport));
508
+ if (hasDynamicColumnsImport) lines.push(renderImport$3(dynamicColumnsImport));
509
+ for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
510
+ for (const queriesImport of queriesImports) lines.push(renderImport$3(queriesImport));
511
+ for (const endpointsImport of endpointsImports) lines.push(renderImport$3(endpointsImport));
512
+ if (hasMutation) {
513
+ lines.push(renderImport$3(queryImport));
514
+ lines.push(renderImport$3(queryTypesImport));
515
+ if (hasMutationEffects) {
516
+ lines.push(renderImport$3(queryModulesImport));
517
+ lines.push(renderImport$3(mutationEffectsImport));
518
+ }
519
+ if (hasAclCheck) lines.push(renderImport$3(aclCheckImport));
520
+ }
521
+ for (const aclImport of aclImports) lines.push(renderImport$3(aclImport));
522
+ lines.push("");
523
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
524
+ type: "configs",
525
+ tag,
526
+ options: resolver.options
527
+ })} {`);
528
+ for (const config of configs) {
529
+ lines.push(renderBuilderConfig(config, generateTypeParams));
530
+ lines.push("");
531
+ }
532
+ if (resolver.options.tsNamespaces) lines.push("}");
533
+ return lines.join("\n").trimEnd() + "\n";
534
+ }
535
+ function renderImport$3(importData) {
536
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
537
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
538
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
539
+ }
540
+ function renderInputsConfig(inputsConfig) {
541
+ const lines = [];
542
+ lines.push("{");
543
+ lines.push(` schema: ${inputsConfig.schema},`);
544
+ lines.push(" options: {");
545
+ lines.push(" inputs: {");
546
+ for (const key of Object.keys(inputsConfig.options.inputs)) lines.push(` ${key}: true,`);
547
+ lines.push(" },");
548
+ lines.push(" },");
549
+ lines.push("}");
550
+ return lines.join("\n");
551
+ }
552
+ function renderColumnsConfig(columnsConfig) {
553
+ const lines = [];
554
+ lines.push("{");
555
+ lines.push(` schema: ${columnsConfig.schema},`);
556
+ lines.push(" options: {");
557
+ lines.push(" columns: {");
558
+ for (const key of Object.keys(columnsConfig.options.columns)) lines.push(` ${key}: true,`);
559
+ lines.push(" },");
560
+ if (columnsConfig.options.sortable) lines.push(` sortable: ${columnsConfig.options.sortable},`);
561
+ lines.push(" },");
562
+ lines.push("}");
563
+ return lines.join("\n");
564
+ }
565
+ function renderMutationContent(resolver, endpoint, tag) {
566
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
567
+ const hasMutationEffects = resolver.options.mutationEffects;
568
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError;
569
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
570
+ const endpointTag = getEndpointTag(endpoint, resolver.options);
571
+ const endpointParams = mapEndpointParamsToFunctionParams(resolver, endpoint, {
572
+ includeFileParam: true,
573
+ modelNamespaceTag: endpointTag
574
+ });
575
+ const endpointParamsStr = endpointParams.map((p) => `${p.name}${p.required ? "" : "?"}: ${p.type}`).join("; ");
576
+ const destructuredMutationArgs = endpointParams.map((p) => p.name).join(", ");
577
+ const resolvedEndpointArgs = mapEndpointParamsToFunctionParams(resolver, endpoint, { modelNamespaceTag: endpointTag }).map((p) => p.name).join(", ");
578
+ const endpointFunction = getImportedEndpointName(endpoint, resolver.options);
579
+ const mutationVariablesType = endpoint.mediaUpload ? `{ ${endpointParamsStr}${endpointParamsStr ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void }` : `{ ${endpointParamsStr} }`;
580
+ const lines = [];
581
+ lines.push(`(options?: AppMutationOptions<typeof ${endpointFunction}, ${mutationVariablesType}>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, config?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
582
+ if (hasMutationDefaultOnError) lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
583
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<${QUERY_MODULE_ENUM}.${endpointTag}>({ currentModule: ${QUERY_MODULE_ENUM}.${tag} });`);
584
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
585
+ lines.push("");
586
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
587
+ const mutationFnArg = destructuredMutationArgs ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
588
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => {`);
589
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, void 0, " "));
590
+ if (endpoint.mediaUpload) lines.push(...renderMediaUploadMutationBody({
591
+ resolver,
592
+ endpointFunction,
593
+ resolvedEndpointArgs
594
+ }).map((line) => ` ${line}`));
595
+ else lines.push(` return ${endpointFunction}(${destructuredMutationArgs}${hasAxiosRequestConfig ? `${destructuredMutationArgs ? ", " : ""}config` : ""});`);
596
+ lines.push(" },");
597
+ lines.push(" ...options,");
598
+ if (hasMutationDefaultOnError) lines.push(" onError: options?.onError ?? queryConfig.onError,");
599
+ if (hasMutationEffects) {
600
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
601
+ lines.push(" await runMutationEffects(resData, variables, options);");
602
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
603
+ lines.push(" },");
604
+ }
605
+ lines.push(" });");
606
+ lines.push("}");
607
+ return lines.map((line) => " " + line).join("\n").trimStart();
608
+ }
609
+ function renderBuilderConfig(config, params) {
610
+ const { resolver, tag } = params;
611
+ const lines = [];
612
+ lines.push(`export const ${config.name} = {`);
613
+ lines.push(" meta: {");
614
+ lines.push(` title: "${config.title}",`);
615
+ lines.push(" },");
616
+ lines.push(" readAll: {");
617
+ if (config.readAll.acl) lines.push(` acl: ${config.readAll.acl},`);
618
+ lines.push(` schema: ${config.readAll.columns.schema},`);
619
+ lines.push(` paginated: ${config.readAll.paginated},`);
620
+ if (config.readAll.infinite) lines.push(` infinite: ${config.readAll.infinite},`);
621
+ if (config.readAll.filters) {
622
+ lines.push(" filters: {");
623
+ lines.push(` schema: ${config.readAll.filters.schema},`);
624
+ lines.push(` filterDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.readAll.filters)})`);
625
+ lines.push(" },");
626
+ }
627
+ lines.push(` columns: ${BUILDERS_UTILS.dynamicColumns}(${renderColumnsConfig(config.readAll.columns)}),`);
628
+ lines.push(" },");
629
+ if (config.read) {
630
+ lines.push(" read: {");
631
+ if (config.read.acl) lines.push(` acl: ${config.read.acl},`);
632
+ lines.push(` schema: ${config.read.schema},`);
633
+ lines.push(` query: ${config.read.query},`);
634
+ lines.push(" },");
635
+ }
636
+ if (config.create) {
637
+ lines.push(" create: {");
638
+ if (config.create.acl) lines.push(` acl: ${config.create.acl},`);
639
+ if (config.create.schema) lines.push(` schema: ${config.create.schema},`);
640
+ lines.push(` mutation: ${typeof config.create.mutation === "string" ? config.create.mutation : renderMutationContent(resolver, config.create.mutation, tag)},`);
641
+ if (config.create.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.create.inputDefs)})`);
642
+ lines.push(" },");
643
+ }
644
+ if (config.update) {
645
+ lines.push(" update: {");
646
+ if (config.update.acl) lines.push(` acl: ${config.update.acl},`);
647
+ if (config.update.schema) lines.push(` schema: ${config.update.schema},`);
648
+ lines.push(` mutation: ${typeof config.update.mutation === "string" ? config.update.mutation : renderMutationContent(resolver, config.update.mutation, tag)},`);
649
+ if (config.update.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.update.inputDefs)})`);
650
+ lines.push(" },");
651
+ }
652
+ if (config.delete) {
653
+ lines.push(" delete: {");
654
+ if (config.delete.acl) lines.push(` acl: ${config.delete.acl},`);
655
+ lines.push(` mutation: ${typeof config.delete.mutation === "string" ? config.delete.mutation : renderMutationContent(resolver, config.delete.mutation, tag)},`);
656
+ lines.push(" },");
657
+ }
658
+ if (config.bulkDelete) {
659
+ lines.push(" bulkDelete: {");
660
+ if (config.bulkDelete.acl) lines.push(` acl: ${config.bulkDelete.acl},`);
661
+ if (config.bulkDelete.schema) lines.push(` schema: ${config.bulkDelete.schema},`);
662
+ lines.push(` mutation: ${typeof config.bulkDelete.mutation === "string" ? config.bulkDelete.mutation : renderMutationContent(resolver, config.bulkDelete.mutation, tag)},`);
663
+ if (config.bulkDelete.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.bulkDelete.inputDefs)})`);
664
+ lines.push(" },");
665
+ }
666
+ lines.push("};");
667
+ return lines.join("\n");
668
+ }
669
+ //#endregion
670
+ //#region src/generators/generate/generateEndpoints.ts
671
+ function generateEndpoints({ resolver, data, tag }) {
672
+ const nativeContent = resolver.getNativeRenderedEndpoints?.(tag);
673
+ if (nativeContent) return nativeContent;
674
+ if (shouldInlineEndpointsForTag(tag, resolver.options)) return;
675
+ const endpoints = data.get(tag)?.endpoints;
676
+ if (!endpoints || endpoints.length === 0) return;
677
+ const appRestClientImport = {
678
+ bindings: [APP_REST_CLIENT_NAME],
679
+ from: getAppRestClientImportPath(resolver.options)
680
+ };
681
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
682
+ const hasGetEndpoints = endpoints.some((endpoint) => endpoint.method === "get");
683
+ const nativeClient = resolver.options.restClient === "native";
684
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasGetEndpoints);
685
+ const axiosImport = {
686
+ bindings: [],
687
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
688
+ from: AXIOS_IMPORT.from
689
+ };
690
+ const nativeImport = {
691
+ bindings: [],
692
+ typeBindings: nativeClient && (hasAxiosRequestConfig || hasGetEndpoints) ? [getRequestConfigTypeName("native")] : [],
693
+ from: REST_PACKAGE_IMPORT_PATH
694
+ };
695
+ const generateParse = resolver.options.parseRequestParams;
696
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
697
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
698
+ const endpointResponseSchemas = endpoints.map((endpoint) => endpoint.response);
699
+ const zodSchemas = getUniqueArray([...endpointResponseSchemas, ...generateParse ? endpointParamsParseSchemas : []]);
700
+ const hasZodImport = zodSchemas.some((schema) => !isNamedZodSchema(schema));
701
+ const hasZodExtendedImport = resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
702
+ const zodExtendedImport = {
703
+ bindings: [ZOD_EXTENDED.namespace],
704
+ from: resolver.options.zodImportPath
705
+ };
706
+ const modelsImports = getModelsImports({
707
+ resolver,
708
+ tag,
709
+ zodSchemas: zodSchemas.filter(isNamedZodSchema),
710
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
711
+ });
712
+ const lines = [];
713
+ lines.push(renderImport$2(appRestClientImport));
714
+ if (hasAxiosImport) lines.push(renderImport$2(axiosImport));
715
+ if (nativeImport.typeBindings?.length) lines.push(renderImport$2(nativeImport));
716
+ if (hasZodImport) lines.push(renderImport$2(ZOD_IMPORT));
717
+ if (hasZodExtendedImport) lines.push(renderImport$2(zodExtendedImport));
718
+ for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
719
+ lines.push("");
720
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
721
+ type: "endpoints",
722
+ tag,
723
+ options: resolver.options
724
+ })} {`);
725
+ for (const endpoint of endpoints) {
726
+ const endpointParamOptions = { modelNamespaceTag: tag };
727
+ const endpointParams = renderEndpointParams$1(resolver, endpoint, endpointParamOptions);
728
+ renderEndpointArgs$1(resolver, endpoint, endpointParamOptions);
729
+ const endpointBody = getEndpointBody(endpoint);
730
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
731
+ const endpointConfig = renderEndpointConfig(resolver, endpoint, tag);
732
+ const hasRequestConfigParam = hasAxiosRequestConfig || endpoint.method === "get";
733
+ lines.push(`export const ${getEndpointName(endpoint)} = (${endpointParams}${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType$1(resolver)}` : ""}) => {`);
734
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
735
+ lines.push(` ${renderRequestInfo(resolver, endpoint, tag)},`);
736
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
737
+ if (endpointBody) lines.push(` ${generateParse ? renderEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
738
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
739
+ lines.push(` ${endpointConfig}`);
740
+ lines.push(" )");
741
+ lines.push("};");
742
+ }
743
+ if (resolver.options.tsNamespaces) lines.push("}");
744
+ return lines.join("\n").trimEnd() + "\n";
745
+ }
746
+ function renderRequestInfo(resolver, endpoint, tag) {
747
+ return `{ resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, (resolver.options.modelsInCommon || resolver.options.modelsInModules) && resolver.options.splitByTags ? tag : void 0)} }`;
748
+ }
749
+ function getRequestConfigType$1(resolver) {
750
+ return `${getRequestConfigTypeName(resolver.options.restClient)} & { allowInvalidResponseData?: boolean }`;
751
+ }
752
+ function renderImport$2(importData) {
753
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
754
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
755
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
756
+ }
757
+ function renderEndpointParams$1(resolver, endpoint, options) {
758
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}, `).join("");
759
+ }
760
+ function renderEndpointArgs$1(resolver, endpoint, options) {
761
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => param.name).join(", ");
762
+ }
763
+ function renderEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
764
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
765
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${getSortingPresenceChain$1(resolver, param)}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
766
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
767
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
768
+ }
769
+ function getSortingPresenceChain$1(resolver, param) {
770
+ const zodSchemaCode = resolver.getCodeByZodSchemaName(param.zodSchema) ?? param.zodSchema;
771
+ if (zodSchemaCode.includes(".nullish()")) return ".nullish()";
772
+ if (zodSchemaCode.includes(".nullable()")) return ".nullable()";
773
+ return !(param.parameterObject ?? param.bodyObject)?.required ? ".optional()" : "";
774
+ }
775
+ function renderEndpointConfig(resolver, endpoint, modelNamespaceTag) {
776
+ const endpointConfig = getEndpointConfig(endpoint);
777
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
778
+ const needsBlobConfig = endpoint.mediaDownload || endpoint.response === "z.instanceof(Blob)";
779
+ if (Object.keys(endpointConfig).length === 0 && !needsBlobConfig) return hasRequestConfigParam ? AXIOS_REQUEST_CONFIG_NAME : "";
780
+ const lines = [];
781
+ lines.push("{");
782
+ if (hasRequestConfigParam) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
783
+ if (endpointConfig.params) {
784
+ lines.push(" params: {");
785
+ for (const param of endpointConfig.params) {
786
+ const value = resolver.options.parseRequestParams ? renderEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
787
+ lines.push(` ${param.name}: ${value},`);
788
+ }
789
+ lines.push(" },");
790
+ }
791
+ if (endpointConfig.headers) {
792
+ lines.push(" headers: {");
793
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
794
+ lines.push(" },");
795
+ }
796
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
797
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
798
+ lines.push("}");
799
+ return lines.join("\n ");
800
+ }
801
+ //#endregion
802
+ //#region src/generators/generate/generateModels.ts
803
+ function generateModels({ resolver, data, tag }) {
804
+ const nativeContent = resolver.getNativeRenderedModels?.(tag);
805
+ if (nativeContent) return nativeContent;
806
+ if (resolver.options.modelsInCommon && resolver.options.splitByTags && tag !== resolver.options.defaultTag) return renderModelsProxy({
807
+ resolver,
808
+ data,
809
+ tag
810
+ });
811
+ const zodSchemas = data.get(tag)?.zodSchemas;
812
+ if (!zodSchemas || Object.keys(zodSchemas).length === 0) return;
813
+ const refZodSchemas = [];
814
+ for (const zodSchema of Object.keys(zodSchemas)) {
815
+ const refs = getZodSchemaRefs(resolver, zodSchema);
816
+ for (const ref of refs) if (!zodSchemas[ref]) refZodSchemas.push(ref);
817
+ }
818
+ const modelsImports = getModelsImports({
819
+ resolver,
820
+ tag,
821
+ zodSchemas: refZodSchemas
822
+ });
823
+ const zodSchemasData = {};
824
+ for (const [key, code] of Object.entries(zodSchemas)) {
825
+ const schemaRef = resolver.getRefByZodSchemaName(key);
826
+ zodSchemasData[key] = {
827
+ code,
828
+ isCircular: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
829
+ isEnum: isEnumZodSchema(code),
830
+ schemaObj: resolver.getZodSchemaObj(key)
831
+ };
832
+ }
833
+ const lines = [];
834
+ lines.push(renderImport$1(ZOD_IMPORT));
835
+ for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
836
+ lines.push("");
837
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
838
+ type: "models",
839
+ tag,
840
+ options: resolver.options
841
+ })} {`);
842
+ for (const [name, zodSchema] of Object.entries(zodSchemasData)) {
843
+ lines.push(renderModelJsDocs({
844
+ name,
845
+ zodSchema,
846
+ tag,
847
+ resolver
848
+ }));
849
+ const inferredTypeName = getZodSchemaInferedTypeName(name, resolver.options);
850
+ if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
851
+ const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
852
+ lines.push(`export const ${name}${typeAnnotation} = ${zodSchema.code};`);
853
+ if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
854
+ if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
855
+ lines.push("");
856
+ }
857
+ if (resolver.options.tsNamespaces) lines.push("}");
858
+ return lines.join("\n").trimEnd() + "\n";
859
+ }
860
+ function renderSchemaType(schema, resolver) {
861
+ if (isReferenceObject(schema)) {
862
+ const schemaName = resolver.getZodSchemaNameByRef(schema.$ref);
863
+ return schemaName ? getZodSchemaInferedTypeName(schemaName, resolver.options) : "unknown";
864
+ }
865
+ const composite = schema.allOf ?? schema.oneOf ?? schema.anyOf;
866
+ if (composite?.length) {
867
+ const separator = schema.allOf ? " & " : " | ";
868
+ return addNullable(schema, composite.map((part) => renderSchemaType(part, resolver)).join(separator));
869
+ }
870
+ if (schema.enum?.length) return addNullable(schema, schema.enum.map((value) => JSON.stringify(value)).join(" | "));
871
+ if (schema.type === "array") return addNullable(schema, `Array<${schema.items ? renderSchemaType(schema.items, resolver) : "unknown"}>`);
872
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
873
+ const properties = Object.entries(schema.properties ?? {}).map(([name, property]) => {
874
+ const isRequired = resolver.options.withImplicitRequiredProps || schema.required?.includes(name);
875
+ const hasDefault = !isReferenceObject(property) && property.default !== void 0;
876
+ const optional = isRequired || hasDefault ? "" : "?";
877
+ const propertyType = renderSchemaType(property, resolver);
878
+ const outputType = resolver.options.replaceOptionalWithNullish && optional && (isReferenceObject(property) || !property.nullable) ? `${propertyType} | null` : propertyType;
879
+ return `${wrapWithQuotesIfNeeded(name)}${optional}: ${outputType}`;
880
+ });
881
+ if (schema.additionalProperties) {
882
+ const valueType = typeof schema.additionalProperties === "object" ? renderSchemaType(schema.additionalProperties, resolver) : "unknown";
883
+ properties.push(`[key: string]: ${valueType}`);
884
+ }
885
+ return addNullable(schema, `{ ${properties.join("; ")} }`);
886
+ }
887
+ const primitiveType = schema.type;
888
+ return addNullable(schema, primitiveType === "string" ? "string" : primitiveType === "number" || primitiveType === "integer" ? "number" : primitiveType === "boolean" ? "boolean" : primitiveType === "null" ? "null" : "unknown");
889
+ }
890
+ function addNullable(schema, type) {
891
+ return schema.nullable && type !== "null" ? `${type} | null` : type;
892
+ }
893
+ function renderModelsProxy({ resolver, data, tag }) {
894
+ const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
895
+ const schemaNames = getUsedSchemaNames({
896
+ resolver,
897
+ endpoints: data.get(tag)?.endpoints ?? []
898
+ }).filter((schemaName) => Boolean(commonZodSchemas[schemaName]));
899
+ if (schemaNames.length === 0) return;
900
+ const modelsNamespace = getNamespaceName({
901
+ type: "models",
902
+ tag,
903
+ options: resolver.options
904
+ });
905
+ const commonNamespace = getNamespaceName({
906
+ type: "models",
907
+ tag: resolver.options.defaultTag,
908
+ options: resolver.options
909
+ });
910
+ const commonModelsPath = `${getImportPath(resolver.options)}${getTagImportPath({
911
+ type: "models",
912
+ tag: resolver.options.defaultTag,
913
+ includeTagDir: true,
914
+ options: resolver.options
915
+ })}`;
916
+ const inferredTypeNames = schemaNames.map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
917
+ const enumInferredTypeNames = schemaNames.filter((schemaName) => isEnumZodSchema(commonZodSchemas[schemaName] ?? "")).map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
918
+ if (resolver.options.tsNamespaces) {
919
+ const lines = [];
920
+ lines.push(`import { ${commonNamespace} } from "${commonModelsPath}";`);
921
+ lines.push("");
922
+ lines.push(`export namespace ${modelsNamespace} {`);
923
+ for (const schemaName of schemaNames) lines.push(` export const ${schemaName} = ${commonNamespace}.${schemaName};`);
924
+ for (const typeName of inferredTypeNames) lines.push(` export type ${typeName} = ${commonNamespace}.${typeName};`);
925
+ for (const enumName of enumInferredTypeNames) lines.push(` export const ${enumName} = ${commonNamespace}.${enumName};`);
926
+ lines.push("}");
927
+ lines.push("");
928
+ return lines.join("\n");
929
+ }
930
+ const valueExports = getUniqueArray([...schemaNames, ...enumInferredTypeNames]);
931
+ const lines = [];
932
+ if (valueExports.length > 0) lines.push(`export { ${valueExports.join(", ")} } from "${commonModelsPath}";`);
933
+ if (inferredTypeNames.length > 0) lines.push(`export type { ${inferredTypeNames.join(", ")} } from "${commonModelsPath}";`);
934
+ return lines.join("\n") + "\n";
935
+ }
936
+ function getUsedSchemaNames({ resolver, endpoints }) {
937
+ const usedSchemaNames = /* @__PURE__ */ new Set();
938
+ const queue = [];
939
+ const enqueue = (schemaName) => {
940
+ if (!schemaName || !isNamedZodSchema(schemaName) || usedSchemaNames.has(schemaName)) return;
941
+ usedSchemaNames.add(schemaName);
942
+ queue.push(schemaName);
943
+ };
944
+ for (const endpoint of endpoints) {
945
+ enqueue(endpoint.response);
946
+ for (const error of endpoint.errors) enqueue(error.zodSchema);
947
+ for (const param of endpoint.parameters) {
948
+ enqueue(param.zodSchema);
949
+ enqueue(param.parameterSortingEnumSchemaName);
950
+ }
951
+ }
952
+ let queueIndex = 0;
953
+ while (queueIndex < queue.length) {
954
+ const schemaName = queue[queueIndex++];
955
+ if (!schemaName) continue;
956
+ const refs = getZodSchemaRefs(resolver, schemaName);
957
+ for (const ref of refs) enqueue(ref);
958
+ }
959
+ return Array.from(usedSchemaNames);
960
+ }
961
+ function renderImport$1(importData) {
962
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
963
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
964
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
965
+ }
966
+ function renderModelJsDocs({ name, zodSchema, tag, resolver }) {
967
+ const lines = [
968
+ `/** `,
969
+ ` * ${name} `,
970
+ ` * @type { ${getZodSchemaType(zodSchema)} }`
971
+ ];
972
+ const description = getZodSchemaDescription(zodSchema);
973
+ if (description) lines.push(` * @description ${description.replace(/\n/g, "\n *")}`);
974
+ const propertyDescriptions = getZodSchemaPropertyDescriptions(resolver, zodSchema, tag);
975
+ if (propertyDescriptions) for (const [property, info] of Object.entries(propertyDescriptions)) lines.push(` * @property { ${info.type} } ${property} ${info.description.replace(/\n/g, "\n *")} `);
976
+ lines.push(" */");
977
+ return lines.join("\n");
978
+ }
979
+ //#endregion
980
+ //#region src/generators/generate/generateQueries.ts
981
+ const endpointParamMappingCache = /* @__PURE__ */ new WeakMap();
982
+ const workspaceParamNamesCache = /* @__PURE__ */ new WeakMap();
983
+ const endpointParamDescriptionCache = /* @__PURE__ */ new WeakMap();
984
+ function generateQueries(params) {
985
+ const { resolver, data, tag } = params;
986
+ const nativeContent = resolver.getNativeRenderedQueries?.(tag);
987
+ if (nativeContent) return nativeContent;
988
+ const mutationScopeOption = resolver.options.mutationScope;
989
+ if (mutationScopeOption && typeof mutationScopeOption === "object") {
990
+ if ("include" in mutationScopeOption && "exclude" in mutationScopeOption) throw new Error("mutationScope cannot specify both 'include' and 'exclude'");
991
+ }
992
+ const inlineEndpoints = shouldInlineEndpointsForTag(tag, resolver.options);
993
+ const endpoints = data.get(tag)?.endpoints;
994
+ if (!endpoints || endpoints.length === 0) return;
995
+ const endpointGroups = groupEndpoints(endpoints, resolver);
996
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
997
+ const nativeClient = resolver.options.restClient === "native";
998
+ const hasNativeMediaUpload = nativeClient && endpoints.some(({ mediaUpload }) => mediaUpload);
999
+ const requestConfigType = getRequestConfigTypeName(resolver.options.restClient);
1000
+ const hasAxiosDefaultImport = !nativeClient && endpoints.some(({ mediaUpload }) => mediaUpload);
1001
+ const hasGetEndpoints = endpoints.some((endpoint) => endpoint.method === "get");
1002
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasAxiosDefaultImport || hasGetEndpoints);
1003
+ const axiosImport = {
1004
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
1005
+ bindings: [],
1006
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
1007
+ from: AXIOS_IMPORT.from
1008
+ };
1009
+ const nativeTransportImport = {
1010
+ bindings: [],
1011
+ typeBindings: nativeClient ? [...hasAxiosRequestConfig || hasGetEndpoints ? [requestConfigType] : [], ...endpoints.some(({ mediaDownload }) => mediaDownload) ? [NATIVE_RESPONSE_TYPE] : []] : [],
1012
+ from: REST_PACKAGE_IMPORT_PATH
1013
+ };
1014
+ const { queryEndpoints, infiniteQueryEndpoints, mutationEndpoints, aclEndpoints } = endpointGroups;
1015
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError && mutationEndpoints.length > 0;
1016
+ const queryImport = {
1017
+ bindings: [
1018
+ ...resolver.options.prefetchQueries && queryEndpoints.length > 0 ? ["QueryClient"] : [],
1019
+ ...queryEndpoints.length > 0 ? [QUERY_HOOKS.query] : [],
1020
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_HOOKS.infiniteQuery] : [],
1021
+ ...mutationEndpoints.length > 0 ? [QUERY_HOOKS.mutation] : []
1022
+ ],
1023
+ from: QUERY_IMPORT.from
1024
+ };
1025
+ const hasMutationEffects = resolver.options.mutationEffects;
1026
+ const queryModulesImport = {
1027
+ bindings: [QUERY_MODULE_ENUM],
1028
+ from: getQueryModulesImportPath(resolver.options)
1029
+ };
1030
+ const hasMutationEffectsImport = hasMutationEffects && mutationEndpoints.length > 0;
1031
+ const mutationEffectsImport = {
1032
+ bindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.hookName] : []],
1033
+ typeBindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.optionsType] : []],
1034
+ from: resolver.options.mutationEffectsImportPath
1035
+ };
1036
+ const hasAclCheck = resolver.options.checkAcl && aclEndpoints.length > 0;
1037
+ const aclCheckImport = {
1038
+ bindings: [ACL_CHECK_HOOK],
1039
+ from: resolver.options.aclCheckImportPath
1040
+ };
1041
+ const queryTypesImport = {
1042
+ bindings: [...queryEndpoints.length > 0 || infiniteQueryEndpoints.length > 0 || hasMutationDefaultOnError ? ["OpenApiQueryConfig"] : []],
1043
+ typeBindings: [
1044
+ ...queryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.query] : [],
1045
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.infiniteQuery] : [],
1046
+ ...mutationEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.mutation] : []
1047
+ ],
1048
+ from: getQueryTypesImportPath(resolver.options)
1049
+ };
1050
+ const hasWorkspaceContext = resolver.options.workspaceContext && endpoints.some((endpoint) => getWorkspaceParamNames(resolver, endpoint).length > 0);
1051
+ const workspaceContextImport = {
1052
+ bindings: ["useWorkspaceContext"],
1053
+ from: CONFIG_PACKAGE_IMPORT_PATH
1054
+ };
1055
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
1056
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
1057
+ const endpointResponseSchemas = endpoints.map((endpoint) => endpoint.response);
1058
+ const endpointRuntimeSchemas = getUniqueArray([...endpointResponseSchemas, ...resolver.options.parseRequestParams ? endpointParamsParseSchemas : []]);
1059
+ const hasZodImport = inlineEndpoints && endpointRuntimeSchemas.some((schema) => !isNamedZodSchema(schema));
1060
+ const hasZodExtendedImport = inlineEndpoints && resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
1061
+ const appRestClientImport = {
1062
+ bindings: [APP_REST_CLIENT_NAME],
1063
+ from: getAppRestClientImportPath(resolver.options)
1064
+ };
1065
+ const zodExtendedImport = {
1066
+ bindings: [ZOD_EXTENDED.namespace],
1067
+ from: resolver.options.zodImportPath
1068
+ };
1069
+ const modelsImports = getModelsImports({
1070
+ resolver,
1071
+ tag,
1072
+ zodSchemas: inlineEndpoints ? endpointRuntimeSchemas.filter(isNamedZodSchema) : [],
1073
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
1074
+ });
1075
+ const endpointsImports = inlineEndpoints ? [] : getEndpointsImports({
1076
+ tag,
1077
+ endpoints,
1078
+ options: resolver.options
1079
+ });
1080
+ const aclImports = getAclImports({
1081
+ tag,
1082
+ endpoints: aclEndpoints,
1083
+ options: resolver.options
1084
+ });
1085
+ const namespace = getNamespaceName({
1086
+ type: "queries",
1087
+ tag,
1088
+ options: resolver.options
1089
+ });
1090
+ const lines = [];
1091
+ if (hasAxiosImport) lines.push(renderImport(axiosImport));
1092
+ if (nativeTransportImport.typeBindings?.length) lines.push(renderImport(nativeTransportImport));
1093
+ if (inlineEndpoints || hasNativeMediaUpload) lines.push(renderImport(appRestClientImport));
1094
+ if (inlineEndpoints) {
1095
+ if (hasZodImport) lines.push(renderImport(ZOD_IMPORT));
1096
+ if (hasZodExtendedImport) lines.push(renderImport(zodExtendedImport));
1097
+ }
1098
+ lines.push(renderImport(queryImport));
1099
+ if (hasMutationEffects) lines.push(renderImport(queryModulesImport));
1100
+ if (hasMutationEffectsImport) lines.push(renderImport(mutationEffectsImport));
1101
+ if (hasAclCheck) {
1102
+ lines.push(renderImport(aclCheckImport));
1103
+ for (const aclImport of aclImports) lines.push(renderImport(aclImport));
1104
+ }
1105
+ lines.push(renderImport(queryTypesImport));
1106
+ if (hasWorkspaceContext) lines.push(renderImport(workspaceContextImport));
1107
+ for (const modelsImport of modelsImports) lines.push(renderImport(modelsImport));
1108
+ for (const endpointsImport of endpointsImports) lines.push(renderImport(endpointsImport));
1109
+ lines.push("");
1110
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${namespace} {`);
1111
+ if (inlineEndpoints) {
1112
+ lines.push(...renderInlineEndpoints({
1113
+ resolver,
1114
+ endpoints,
1115
+ tag
1116
+ }));
1117
+ lines.push("");
1118
+ }
1119
+ lines.push(`export const ${QUERIES_MODULE_NAME} = ${hasMutationEffects ? `${QUERY_MODULE_ENUM}.${tag}` : `"${namespace}"`};`);
1120
+ lines.push("");
1121
+ lines.push(renderQueryKeys({
1122
+ resolver,
1123
+ queryEndpoints,
1124
+ tag
1125
+ }));
1126
+ lines.push("");
1127
+ for (const endpoint of endpoints) {
1128
+ const endpointInfo = endpointGroups.infoByEndpoint.get(endpoint);
1129
+ if (endpointInfo?.query) {
1130
+ lines.push(renderQueryOptions({
1131
+ resolver,
1132
+ endpoint,
1133
+ inlineEndpoints
1134
+ }));
1135
+ lines.push("");
1136
+ lines.push(renderQuery({
1137
+ resolver,
1138
+ endpoint,
1139
+ inlineEndpoints
1140
+ }));
1141
+ lines.push("");
1142
+ if (resolver.options.prefetchQueries) {
1143
+ lines.push(renderPrefetchQuery({
1144
+ resolver,
1145
+ endpoint
1146
+ }));
1147
+ lines.push("");
1148
+ }
1149
+ }
1150
+ if (endpointInfo?.mutation) {
1151
+ lines.push(renderMutation({
1152
+ resolver,
1153
+ endpoint,
1154
+ inlineEndpoints,
1155
+ precomputed: endpointGroups.mutationDataByEndpoint.get(endpoint)
1156
+ }));
1157
+ lines.push("");
1158
+ }
1159
+ if (endpointInfo?.infiniteQuery) {
1160
+ lines.push(renderInfiniteQueryOptions({
1161
+ resolver,
1162
+ endpoint,
1163
+ inlineEndpoints
1164
+ }));
1165
+ lines.push("");
1166
+ lines.push(renderInfiniteQuery({
1167
+ resolver,
1168
+ endpoint,
1169
+ inlineEndpoints
1170
+ }));
1171
+ lines.push("");
1172
+ if (resolver.options.prefetchQueries) {
1173
+ lines.push(renderPrefetchInfiniteQuery({
1174
+ resolver,
1175
+ endpoint
1176
+ }));
1177
+ lines.push("");
1178
+ }
1179
+ }
1180
+ }
1181
+ if (resolver.options.tsNamespaces) lines.push("}");
1182
+ return lines.join("\n").trimEnd() + "\n";
1183
+ }
1184
+ function getEndpointParamMapping(resolver, endpoint, options) {
1185
+ let resolverCache = endpointParamMappingCache.get(resolver);
1186
+ if (!resolverCache) {
1187
+ resolverCache = /* @__PURE__ */ new WeakMap();
1188
+ endpointParamMappingCache.set(resolver, resolverCache);
1189
+ }
1190
+ let endpointCache = resolverCache.get(endpoint);
1191
+ if (!endpointCache) {
1192
+ endpointCache = /* @__PURE__ */ new Map();
1193
+ resolverCache.set(endpoint, endpointCache);
1194
+ }
1195
+ const key = JSON.stringify([
1196
+ options?.excludeBodyParam,
1197
+ options?.excludePageParam,
1198
+ options?.replacePageParam,
1199
+ options?.includeFileParam,
1200
+ options?.includeOnlyRequiredParams,
1201
+ options?.pathParamsRequiredOnly,
1202
+ options?.optionalPathParams,
1203
+ options?.modelNamespaceTag,
1204
+ options?.excludePathParams
1205
+ ]);
1206
+ const cached = endpointCache.get(key);
1207
+ if (cached) return cached;
1208
+ const computed = mapEndpointParamsToFunctionParams(resolver, endpoint, options);
1209
+ endpointCache.set(key, computed);
1210
+ return computed;
1211
+ }
1212
+ function getWorkspaceContextAllowList(workspaceContext) {
1213
+ return new Set(workspaceContext);
1214
+ }
1215
+ function renderImport(importData) {
1216
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
1217
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
1218
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
1219
+ }
1220
+ function renderEndpointParams(resolver, endpoint, options) {
1221
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}`).join(", ");
1222
+ }
1223
+ function renderEndpointArgs(resolver, endpoint, options, replacements) {
1224
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => replacements?.[param.name] ?? param.name).join(", ");
1225
+ }
1226
+ function renderEndpointObjectArgs(resolver, endpoint, options, replacements) {
1227
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => {
1228
+ const replacement = replacements?.[param.name];
1229
+ return replacement && replacement !== param.name ? `${param.name}: ${replacement}` : param.name;
1230
+ }).join(", ");
1231
+ }
1232
+ function renderEndpointParamDescription(endpointParam) {
1233
+ const cached = endpointParamDescriptionCache.get(endpointParam);
1234
+ if (cached !== void 0) return cached;
1235
+ const strs = [`${endpointParam.paramType} parameter`];
1236
+ const description = endpointParam.parameterObject?.description || endpointParam.bodyObject?.description;
1237
+ if (description) strs.push(description);
1238
+ let schema = void 0;
1239
+ let mediaTypeObject = void 0;
1240
+ if (endpointParam.parameterObject?.schema && isSchemaObject(endpointParam.parameterObject.schema)) schema = endpointParam.parameterObject?.schema;
1241
+ if (endpointParam.bodyObject?.content) {
1242
+ const matchingMediaType = Object.keys(endpointParam.bodyObject.content ?? {}).find(isParamMediaTypeAllowed);
1243
+ if (matchingMediaType) {
1244
+ mediaTypeObject = endpointParam.bodyObject.content[matchingMediaType];
1245
+ if (mediaTypeObject.schema && isSchemaObject(mediaTypeObject.schema)) schema = mediaTypeObject.schema;
1246
+ }
1247
+ }
1248
+ if (schema) strs.push(...getSchemaDescriptions(schema));
1249
+ if (mediaTypeObject?.example) strs.push(`Example: \`${mediaTypeObject.example}\``);
1250
+ const renderedDescription = strs.join(". ");
1251
+ endpointParamDescriptionCache.set(endpointParam, renderedDescription);
1252
+ return renderedDescription;
1253
+ }
1254
+ function getWorkspaceParamNames(resolver, endpoint) {
1255
+ let resolverCache = workspaceParamNamesCache.get(resolver);
1256
+ if (!resolverCache) {
1257
+ resolverCache = /* @__PURE__ */ new WeakMap();
1258
+ workspaceParamNamesCache.set(resolver, resolverCache);
1259
+ }
1260
+ const cached = resolverCache.get(endpoint);
1261
+ if (cached) return cached;
1262
+ const allowList = getWorkspaceContextAllowList(resolver.options.workspaceContext);
1263
+ const endpointParams = getEndpointParamMapping(resolver, endpoint, {});
1264
+ const endpointParamNames = new Set(endpointParams.map((param) => param.name));
1265
+ const workspaceParamNames = endpointParams.filter((param) => param.paramType === "Path").map((param) => param.name);
1266
+ const aclParamNames = (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => invalidVariableNameCharactersToCamel(condition.name)).filter((name) => endpointParamNames.has(name));
1267
+ const names = getUniqueArray([...workspaceParamNames, ...aclParamNames]).filter((name) => allowList.has(name));
1268
+ resolverCache.set(endpoint, names);
1269
+ return names;
1270
+ }
1271
+ function getWorkspaceParamReplacements(resolver, endpoint) {
1272
+ return Object.fromEntries(getWorkspaceParamNames(resolver, endpoint).map((name) => [name, `normalize${capitalize(name)}`]));
1273
+ }
1274
+ function getWorkspaceParamTypes(resolver, endpoint, modelNamespaceTag) {
1275
+ const workspaceParamNames = new Set(getWorkspaceParamNames(resolver, endpoint));
1276
+ return Object.fromEntries(getEndpointParamMapping(resolver, endpoint, { modelNamespaceTag }).filter((param) => workspaceParamNames.has(param.name)).map((param) => [param.name, param.type]));
1277
+ }
1278
+ function renderWorkspaceContextDestructure({ replacements, paramTypes, indent }) {
1279
+ const workspaceParamNames = Object.keys(replacements);
1280
+ if (workspaceParamNames.length === 0) return [];
1281
+ const workspaceParamBindings = workspaceParamNames.map((paramName) => `${paramName}: ${paramName}Workspace`);
1282
+ const workspaceContextType = workspaceParamNames.map((paramName) => `${paramName}?: ${paramTypes[paramName] ?? "unknown"}`).join("; ");
1283
+ return [`${indent}const { ${workspaceParamBindings.join(", ")} } = useWorkspaceContext<{ ${workspaceContextType} }>();`];
1284
+ }
1285
+ function renderWorkspaceParamCoalescing({ replacements, indent }) {
1286
+ const workspaceParamNames = Object.keys(replacements);
1287
+ const lines = [];
1288
+ for (const paramName of workspaceParamNames) {
1289
+ lines.push(`${indent}const ${replacements[paramName]} = ${paramName} ?? ${paramName}Workspace;`);
1290
+ lines.push(`${indent}if (!${replacements[paramName]}) {`);
1291
+ lines.push(`${indent} throw Error(\`${capitalize(paramName)} not provided\`);`);
1292
+ lines.push(`${indent}}`);
1293
+ }
1294
+ return lines;
1295
+ }
1296
+ function renderWorkspaceParamResolutions({ replacements, paramTypes, indent }) {
1297
+ return [...renderWorkspaceContextDestructure({
1298
+ replacements,
1299
+ paramTypes,
1300
+ indent
1301
+ }), ...renderWorkspaceParamCoalescing({
1302
+ replacements,
1303
+ indent
1304
+ })];
1305
+ }
1306
+ function addAsteriskAfterNewLine(str) {
1307
+ return str.replace(/\n/g, "\n *");
1308
+ }
1309
+ function renderQueryJsDocs({ resolver, endpoint, mode, tag }) {
1310
+ const lines = ["/** "];
1311
+ if (mode === "infiniteQuery") lines.push(` * Infinite query \`${getInfiniteQueryName(endpoint)}${endpoint.summary ? "" : ""}`);
1312
+ else if (mode === "query") lines.push(` * Query \`${getQueryName(endpoint)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should be cached" : ""}`);
1313
+ else lines.push(` * Mutation \`${getQueryName(endpoint, true)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should not be cached" : ""}`);
1314
+ if (endpoint.summary) lines.push(` * @summary ${addAsteriskAfterNewLine(endpoint.summary)}`);
1315
+ if (endpoint.description) lines.push(` * @description ${addAsteriskAfterNewLine(endpoint.description)}`);
1316
+ if (endpoint.acl) lines.push(` * @permission Requires \`${getAbilityFunctionName(endpoint)}\` ability `);
1317
+ const params = getEndpointParamMapping(resolver, endpoint, {
1318
+ ...mode !== "infiniteQuery" ? { includeFileParam: true } : {},
1319
+ modelNamespaceTag: tag
1320
+ });
1321
+ for (const endpointParam of params) lines.push(` * @param { ${endpointParam.type} } ${endpointParam.name} ${renderEndpointParamDescription(endpointParam)}`);
1322
+ if (mode === "query") lines.push(" * @param { AppQueryOptions } options Query options");
1323
+ else if (mode === "mutation") lines.push(` * @param { AppMutationOptions${resolver.options.mutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""} } options Mutation options`);
1324
+ else lines.push(" * @param { AppInfiniteQueryOptions } options Infinite query options");
1325
+ const withRawResponse = endpoint.mediaDownload && mode !== "infiniteQuery";
1326
+ const responseType = resolver.options.restClient === "native" ? NATIVE_RESPONSE_TYPE : "AxiosResponse";
1327
+ const resultType = `${withRawResponse ? `${responseType}<` : ""}${getImportedZodSchemaInferedTypeName(resolver, endpoint.response, void 0, tag)}${withRawResponse ? ">" : ""}`;
1328
+ if (mode === "query") lines.push(` * @returns { UseQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1329
+ else if (mode === "mutation") lines.push(` * @returns { UseMutationResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1330
+ else lines.push(` * @returns { UseInfiniteQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1331
+ lines.push(` * @statusCodes [${endpoint.responseStatusCodes.join(", ")}]`);
1332
+ lines.push(" */");
1333
+ return lines.join("\n");
1334
+ }
1335
+ function renderQueryKeys({ resolver, queryEndpoints, tag }) {
1336
+ if (queryEndpoints.length === 0) return "";
1337
+ const lines = [];
1338
+ lines.push("export const keys = {");
1339
+ lines.push(` all: [${QUERIES_MODULE_NAME}] as const,`);
1340
+ for (const endpoint of queryEndpoints) {
1341
+ lines.push(` ${getEndpointName(endpoint)}: (${renderEndpointParams(resolver, endpoint, {
1342
+ pathParamsRequiredOnly: true,
1343
+ modelNamespaceTag: tag
1344
+ })}) => [...keys.all, "${endpoint.path}", ${renderEndpointArgs(resolver, endpoint, {})}] as const,`);
1345
+ if (resolver.options.infiniteQueries && isInfiniteQuery(endpoint, resolver.options)) lines.push(` ${getEndpointName(endpoint)}Infinite: (${renderEndpointParams(resolver, endpoint, {
1346
+ excludePageParam: true,
1347
+ pathParamsRequiredOnly: true,
1348
+ modelNamespaceTag: tag
1349
+ })}) => [...keys.all, "${endpoint.path}", "infinite", ${renderEndpointArgs(resolver, endpoint, { excludePageParam: true })}] as const,`);
1350
+ }
1351
+ lines.push("};");
1352
+ return lines.join("\n");
1353
+ }
1354
+ function renderInlineEndpoints({ resolver, endpoints, tag }) {
1355
+ const lines = [];
1356
+ for (const endpoint of endpoints) {
1357
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: tag });
1358
+ const endpointBody = getEndpointBody(endpoint);
1359
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
1360
+ const endpointConfig = renderInlineEndpointConfig(resolver, endpoint, tag);
1361
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1362
+ lines.push(`const ${getEndpointName(endpoint)} = (${endpointParams}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => {`);
1363
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
1364
+ lines.push(` ${renderInlineRequestInfo(resolver, endpoint, tag)},`);
1365
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
1366
+ if (endpointBody) lines.push(` ${resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
1367
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
1368
+ lines.push(` ${endpointConfig}`);
1369
+ lines.push(" );");
1370
+ lines.push("};");
1371
+ lines.push("");
1372
+ }
1373
+ return lines;
1374
+ }
1375
+ function renderInlineRequestInfo(resolver, endpoint, tag) {
1376
+ return `{ resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} }`;
1377
+ }
1378
+ function getRequestConfigType(resolver) {
1379
+ return `${getRequestConfigTypeName(resolver.options.restClient)} & { allowInvalidResponseData?: boolean }`;
1380
+ }
1381
+ function renderRequestConfigWithSignal(hasRequestConfigParam) {
1382
+ return `{ ${hasRequestConfigParam ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}signal }`;
1383
+ }
1384
+ function renderInlineEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
1385
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
1386
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${getSortingPresenceChain(resolver, param)}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
1387
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
1388
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
1389
+ }
1390
+ function getSortingPresenceChain(resolver, param) {
1391
+ const zodSchemaCode = resolver.getCodeByZodSchemaName(param.zodSchema) ?? param.zodSchema;
1392
+ if (zodSchemaCode.includes(".nullish()")) return ".nullish()";
1393
+ if (zodSchemaCode.includes(".nullable()")) return ".nullable()";
1394
+ return !(param.parameterObject ?? param.bodyObject)?.required ? ".optional()" : "";
1395
+ }
1396
+ function renderInlineEndpointConfig(resolver, endpoint, modelNamespaceTag) {
1397
+ const endpointConfig = getEndpointConfig(endpoint);
1398
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1399
+ const needsBlobConfig = endpoint.mediaDownload || endpoint.response === "z.instanceof(Blob)";
1400
+ if (Object.keys(endpointConfig).length === 0 && !needsBlobConfig) return hasRequestConfigParam ? AXIOS_REQUEST_CONFIG_NAME : "";
1401
+ const lines = [];
1402
+ lines.push("{");
1403
+ if (hasRequestConfigParam) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
1404
+ if (endpointConfig.params) {
1405
+ lines.push(" params: {");
1406
+ for (const param of endpointConfig.params) {
1407
+ const value = resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
1408
+ lines.push(` ${param.name}: ${value},`);
1409
+ }
1410
+ lines.push(" },");
1411
+ }
1412
+ if (endpointConfig.headers) {
1413
+ lines.push(" headers: {");
1414
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
1415
+ lines.push(" },");
1416
+ }
1417
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
1418
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
1419
+ lines.push(" }");
1420
+ return lines.join("\n");
1421
+ }
1422
+ function renderQueryOptions({ resolver, endpoint, inlineEndpoints }) {
1423
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1424
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
1425
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1426
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1427
+ const lines = [];
1428
+ lines.push(`const ${getQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => ({`);
1429
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}(${endpointArgs}),`);
1430
+ const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
1431
+ lines.push(` queryFn: ({ signal }: { signal: AbortSignal }) => ${endpointFunction}(${endpointArgs}${hasRequestConfigParam ? `${endpointArgs ? ", " : ""}${requestConfigWithSignal}` : ""}),`);
1432
+ lines.push("});");
1433
+ return lines.join("\n");
1434
+ }
1435
+ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
1436
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1437
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1438
+ excludePageParam: true,
1439
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
1440
+ });
1441
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1442
+ const endpointArgsWithPage = renderEndpointArgs(resolver, endpoint, { replacePageParam: true });
1443
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1444
+ const lines = [];
1445
+ lines.push(`const ${getInfiniteQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => ({`);
1446
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}Infinite(${endpointArgsWithoutPage}),`);
1447
+ const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
1448
+ lines.push(` queryFn: ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => ${endpointFunction}(${endpointArgsWithPage}${hasRequestConfigParam ? `, ${requestConfigWithSignal}` : ""}),`);
1449
+ lines.push(" initialPageParam: 1,");
1450
+ lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>>) => {`);
1451
+ lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
1452
+ lines.push(` return pageParam * limitParam < (${resolver.options.infiniteQueryResponseParamNames.totalItems} ?? 0) ? pageParam + 1 : null;`);
1453
+ lines.push(" },");
1454
+ lines.push("});");
1455
+ return lines.join("\n");
1456
+ }
1457
+ function renderPrefetchQuery({ resolver, endpoint }) {
1458
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1459
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
1460
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1461
+ const lines = [];
1462
+ lines.push(`export const ${getPrefetchQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: Omit<Parameters<QueryClient["prefetchQuery"]>[0], "queryKey" | "queryFn">, ${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}, ` : ""}throwOnError = false) => {`);
1463
+ lines.push(` const queryOptions = { ...${getQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options };`);
1464
+ lines.push(` return throwOnError ? queryClient.fetchQuery(queryOptions) : queryClient.prefetchQuery(queryOptions);`);
1465
+ lines.push("};");
1466
+ return lines.join("\n");
1467
+ }
1468
+ function renderPrefetchInfiniteQuery({ resolver, endpoint }) {
1469
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1470
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1471
+ excludePageParam: true,
1472
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
1473
+ });
1474
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1475
+ const optionsArgs = `${endpointParams ? `{ ${endpointArgs} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
1476
+ const lines = [];
1477
+ lines.push(`export const ${getPrefetchInfiniteQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: Omit<Parameters<QueryClient["prefetchInfiniteQuery"]>[0], "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam">, ${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}, ` : ""}throwOnError = false) => {`);
1478
+ lines.push(` const queryOptions = { ...${getInfiniteQueryOptionsName(endpoint)}(${optionsArgs}), ...(options as {}) };`);
1479
+ lines.push(` return throwOnError ? queryClient.fetchInfiniteQuery(queryOptions) : queryClient.prefetchInfiniteQuery(queryOptions);`);
1480
+ lines.push("};");
1481
+ return lines.join("\n");
1482
+ }
1483
+ function renderQuery({ resolver, endpoint, inlineEndpoints }) {
1484
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1485
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1486
+ const tag = getEndpointTag(endpoint, resolver.options);
1487
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1488
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1489
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1490
+ const resolvedEndpointArgs = renderEndpointObjectArgs(resolver, endpoint, {}, workspaceParamReplacements);
1491
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1492
+ optionalPathParams: resolver.options.workspaceContext,
1493
+ modelNamespaceTag: tag
1494
+ });
1495
+ const queryOptionsName = getQueryOptionsName(endpoint);
1496
+ const hasQueryFnOverride = hasAclCheck;
1497
+ const requestConfig = `{ ${hasAxiosRequestConfig ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}allowInvalidResponseData: queryConfig.allowInvalidResponseData }`;
1498
+ const queryOptionsArgs = `${resolvedEndpointArgs ? `{ ${resolvedEndpointArgs} }, ` : ""}${requestConfig}`;
1499
+ const lines = [];
1500
+ lines.push(renderQueryJsDocs({
1501
+ resolver,
1502
+ endpoint,
1503
+ mode: "query",
1504
+ tag
1505
+ }));
1506
+ lines.push(`export const ${getQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: AppQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1507
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1508
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1509
+ lines.push(...renderWorkspaceParamResolutions({
1510
+ replacements: workspaceParamReplacements,
1511
+ paramTypes: workspaceParamTypes,
1512
+ indent: " "
1513
+ }));
1514
+ lines.push(" ");
1515
+ lines.push(` return ${QUERY_HOOKS.query}({`);
1516
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
1517
+ if (hasQueryFnOverride) {
1518
+ lines.push(" queryFn: async ({ signal }: { signal: AbortSignal }) => {");
1519
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1520
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ signal });`);
1521
+ lines.push(" },");
1522
+ }
1523
+ lines.push(" ...options,");
1524
+ lines.push(" });");
1525
+ lines.push("};");
1526
+ return lines.join("\n");
1527
+ }
1528
+ function renderMutation({ resolver, endpoint, inlineEndpoints, precomputed }) {
1529
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1530
+ const hasMutationEffects = resolver.options.mutationEffects;
1531
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError;
1532
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1533
+ const tag = getEndpointTag(endpoint, resolver.options);
1534
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1535
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1536
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1537
+ includeFileParam: true,
1538
+ optionalPathParams: resolver.options.workspaceContext,
1539
+ modelNamespaceTag: tag
1540
+ });
1541
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
1542
+ const destructuredMutationArgs = renderEndpointArgs(resolver, endpoint, { includeFileParam: true });
1543
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1544
+ const updateQueryEndpoints = precomputed?.updateQueryEndpoints ?? [];
1545
+ const destructuredVariables = precomputed?.destructuredVariables ?? getDestructuredVariables(resolver, endpoint, updateQueryEndpoints);
1546
+ const hasMutationFnBody = endpoint.mediaUpload || hasAclCheck || Object.keys(workspaceParamReplacements).length > 0;
1547
+ const mutationVariablesType = endpoint.mediaUpload ? `${endpointParams}${endpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : endpointParams;
1548
+ const isPost = endpoint.method === "post";
1549
+ const mutationScopeOption = resolver.options.mutationScope;
1550
+ const operationId = getEndpointName(endpoint);
1551
+ const scopeMatchKey = `${tag}/${operationId}`;
1552
+ let scopeEnabled = false;
1553
+ if (!isPost && mutationScopeOption) {
1554
+ if (mutationScopeOption === true) scopeEnabled = true;
1555
+ else if (typeof mutationScopeOption === "object" && "include" in mutationScopeOption) scopeEnabled = mutationScopeOption.include.some((id) => id === operationId || id === scopeMatchKey);
1556
+ else if (typeof mutationScopeOption === "object" && "exclude" in mutationScopeOption) scopeEnabled = !mutationScopeOption.exclude.some((id) => id === operationId || id === scopeMatchKey);
1557
+ }
1558
+ const scopePathParams = scopeEnabled ? getEndpointParamMapping(resolver, endpoint, {}).filter((p) => p.paramType === "Path") : [];
1559
+ const isScoped = scopePathParams.length > 0;
1560
+ const nonPathEndpointParams = isScoped ? renderEndpointParams(resolver, endpoint, {
1561
+ includeFileParam: true,
1562
+ optionalPathParams: resolver.options.workspaceContext,
1563
+ modelNamespaceTag: tag,
1564
+ excludePathParams: true
1565
+ }) : endpointParams;
1566
+ const nonPathMutationVariablesType = isScoped ? endpoint.mediaUpload ? `${nonPathEndpointParams}${nonPathEndpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : nonPathEndpointParams : mutationVariablesType;
1567
+ const pathParamFirstArg = isScoped ? `{ ${scopePathParams.map((p) => p.name).join(", ")} }: { ${scopePathParams.map((p) => `${p.name}: ${p.type}`).join("; ")} }, ` : "";
1568
+ const mutationOptionsTypeArg = isScoped ? nonPathMutationVariablesType ? `, { ${nonPathMutationVariablesType} }` : "" : `, { ${mutationVariablesType} }`;
1569
+ const lines = [];
1570
+ lines.push(renderQueryJsDocs({
1571
+ resolver,
1572
+ endpoint,
1573
+ mode: "mutation",
1574
+ tag
1575
+ }));
1576
+ lines.push(`export const ${getQueryName(endpoint, true)} = (${pathParamFirstArg}options?: AppMutationOptions<typeof ${endpointFunction}${mutationOptionsTypeArg}>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1577
+ if (hasMutationDefaultOnError) lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1578
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1579
+ lines.push(...renderWorkspaceContextDestructure({
1580
+ replacements: workspaceParamReplacements,
1581
+ paramTypes: workspaceParamTypes,
1582
+ indent: " "
1583
+ }));
1584
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<${QUERY_MODULE_ENUM}.${tag}>({ currentModule: ${QUERIES_MODULE_NAME} });`);
1585
+ lines.push("");
1586
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
1587
+ const nonPathDestructuredArgs = isScoped ? renderEndpointArgs(resolver, endpoint, {
1588
+ includeFileParam: true,
1589
+ excludePathParams: true
1590
+ }) : destructuredMutationArgs;
1591
+ const effectiveParams = isScoped ? nonPathEndpointParams : endpointParams;
1592
+ const effectiveArgs = isScoped ? nonPathDestructuredArgs : destructuredMutationArgs;
1593
+ const mutationFnArg = effectiveParams || endpoint.mediaUpload ? `{ ${effectiveArgs}${endpoint.mediaUpload ? `${effectiveArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
1594
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => ${hasMutationFnBody ? "{ " : ""}`);
1595
+ lines.push(...renderWorkspaceParamCoalescing({
1596
+ replacements: workspaceParamReplacements,
1597
+ indent: " "
1598
+ }));
1599
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1600
+ if (endpoint.mediaUpload) lines.push(...renderMediaUploadMutationBody({
1601
+ resolver,
1602
+ endpointFunction,
1603
+ resolvedEndpointArgs
1604
+ }).map((line) => ` ${line}`));
1605
+ else lines.push(` ${hasMutationFnBody ? "return " : ""}${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""})`);
1606
+ if (hasMutationFnBody) lines.push(" },");
1607
+ else lines.push(",");
1608
+ if (isScoped) {
1609
+ const scopePathParamInterpolations = scopePathParams.map((p) => `:\${${p.name}}`).join("");
1610
+ lines.push(` scope: { id: \`${getEndpointName(endpoint)}${scopePathParamInterpolations}\` },`);
1611
+ }
1612
+ lines.push(" ...options,");
1613
+ if (hasMutationDefaultOnError) lines.push(" onError: options?.onError ?? queryConfig.onError,");
1614
+ if (hasMutationEffects) {
1615
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
1616
+ if (updateQueryEndpoints.length > 0) {
1617
+ const scopedPathParamNames = new Set(scopePathParams.map((p) => p.name));
1618
+ const variablesDestructure = destructuredVariables.filter((v) => !scopedPathParamNames.has(v));
1619
+ if (variablesDestructure.length > 0) lines.push(` const { ${variablesDestructure.join(", ")} } = variables;`);
1620
+ lines.push(...renderWorkspaceParamCoalescing({
1621
+ replacements: workspaceParamReplacements,
1622
+ indent: " "
1623
+ }));
1624
+ lines.push(` const updateKeys = [${updateQueryEndpoints.map((e) => `keys.${getEndpointName(e)}(${renderEndpointArgs(resolver, e, { includeOnlyRequiredParams: true }, workspaceParamReplacements)})`).join(", ")}];`);
1625
+ lines.push(` await runMutationEffects(resData, variables, options, updateKeys);`);
1626
+ } else lines.push(" await runMutationEffects(resData, variables, options);");
1627
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
1628
+ lines.push(" },");
1629
+ }
1630
+ lines.push(" });");
1631
+ lines.push("};");
1632
+ return lines.join("\n");
1633
+ }
1634
+ function groupEndpoints(endpoints, resolver) {
1635
+ const queryEndpoints = [];
1636
+ const mutationEndpoints = [];
1637
+ const infiniteQueryEndpoints = [];
1638
+ const aclEndpoints = [];
1639
+ const infoByEndpoint = /* @__PURE__ */ new Map();
1640
+ const mutationDataByEndpoint = /* @__PURE__ */ new Map();
1641
+ for (const endpoint of endpoints) {
1642
+ const query = isQuery(endpoint);
1643
+ const mutation = isMutation(endpoint);
1644
+ const infiniteQuery = Boolean(resolver.options.infiniteQueries && query && isInfiniteQuery(endpoint, resolver.options));
1645
+ if (query) queryEndpoints.push(endpoint);
1646
+ if (mutation) mutationEndpoints.push(endpoint);
1647
+ if (infiniteQuery) infiniteQueryEndpoints.push(endpoint);
1648
+ if (endpoint.acl) aclEndpoints.push(endpoint);
1649
+ infoByEndpoint.set(endpoint, {
1650
+ query,
1651
+ mutation,
1652
+ infiniteQuery
1653
+ });
1654
+ }
1655
+ for (const endpoint of mutationEndpoints) {
1656
+ 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);
1657
+ mutationDataByEndpoint.set(endpoint, {
1658
+ updateQueryEndpoints,
1659
+ destructuredVariables: getDestructuredVariables(resolver, endpoint, updateQueryEndpoints)
1660
+ });
1661
+ }
1662
+ return {
1663
+ queryEndpoints,
1664
+ mutationEndpoints,
1665
+ infiniteQueryEndpoints,
1666
+ aclEndpoints,
1667
+ infoByEndpoint,
1668
+ mutationDataByEndpoint
1669
+ };
1670
+ }
1671
+ function renderInfiniteQuery({ resolver, endpoint, inlineEndpoints }) {
1672
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1673
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1674
+ const tag = getEndpointTag(endpoint, resolver.options);
1675
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1676
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1677
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1678
+ excludePageParam: true,
1679
+ optionalPathParams: resolver.options.workspaceContext,
1680
+ modelNamespaceTag: tag
1681
+ });
1682
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1683
+ const resolvedEndpointArgsWithoutPage = renderEndpointObjectArgs(resolver, endpoint, { excludePageParam: true }, workspaceParamReplacements);
1684
+ const queryOptionsName = getInfiniteQueryOptionsName(endpoint);
1685
+ const requestConfig = `{ ${hasAxiosRequestConfig ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}allowInvalidResponseData: queryConfig.allowInvalidResponseData }`;
1686
+ const queryOptionsArgs = `${resolvedEndpointArgsWithoutPage ? `{ ${resolvedEndpointArgsWithoutPage} }, ` : ""}${requestConfig}`;
1687
+ const hasQueryFnOverride = hasAclCheck;
1688
+ const lines = [];
1689
+ lines.push(renderQueryJsDocs({
1690
+ resolver,
1691
+ endpoint,
1692
+ mode: "infiniteQuery",
1693
+ tag
1694
+ }));
1695
+ lines.push(`export const ${getInfiniteQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }, ` : ""}options?: AppInfiniteQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1696
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1697
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1698
+ lines.push(...renderWorkspaceParamResolutions({
1699
+ replacements: workspaceParamReplacements,
1700
+ paramTypes: workspaceParamTypes,
1701
+ indent: " "
1702
+ }));
1703
+ lines.push("");
1704
+ lines.push(` return ${QUERY_HOOKS.infiniteQuery}({`);
1705
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
1706
+ if (hasQueryFnOverride) {
1707
+ lines.push(" queryFn: async ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => {");
1708
+ lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1709
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ pageParam, signal });`);
1710
+ lines.push(" },");
1711
+ }
1712
+ lines.push(" ...options,");
1713
+ lines.push(" });");
1714
+ lines.push("};");
1715
+ return lines.join("\n");
1716
+ }
1717
+ //#endregion
1718
+ //#region src/generators/generate/generateAppRestClient.ts
1719
+ function generateAppRestClient(resolver) {
1720
+ const clientName = resolver.options.restClient === "native" ? "NativeRestClient" : "RestClient";
1721
+ return `import { ${clientName} } from "${resolver.options.restClient === "native" ? NATIVE_PACKAGE_IMPORT_PATH : PACKAGE_IMPORT_PATH}";
1722
+
1723
+ export const ${APP_REST_CLIENT_NAME} = new ${clientName}({
1724
+ config: {
1725
+ baseURL: "${resolver.getBaseUrl()}"
1726
+ },
1727
+ });
1728
+ `;
1729
+ }
1730
+ //#endregion
1731
+ //#region src/generators/generate/generateDomainErrors.ts
1732
+ function domainToPascalCase(domain) {
1733
+ return domain.split(/[-_]/).map(capitalize).join("");
1734
+ }
1735
+ const VALID_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1736
+ function generateDomainErrors({ resolver, data }) {
1737
+ const nativeContent = resolver.getNativeRenderedShared?.("domainErrors");
1738
+ if (nativeContent) return nativeContent;
1739
+ const byDomain = /* @__PURE__ */ new Map();
1740
+ for (const { endpoints } of data.values()) for (const endpoint of endpoints) for (const error of endpoint.errors) {
1741
+ if (!error.domainError) continue;
1742
+ const { domain, code } = error.domainError;
1743
+ if (!byDomain.has(domain)) byDomain.set(domain, /* @__PURE__ */ new Map());
1744
+ const domainMap = byDomain.get(domain);
1745
+ if (!domainMap.has(code)) domainMap.set(code, {
1746
+ code,
1747
+ name: error.domainError.name,
1748
+ description: error.description
1749
+ });
1750
+ }
1751
+ if (byDomain.size === 0) return void 0;
1752
+ const blocks = [];
1753
+ for (const [domain, codes] of [...byDomain.entries()].sort(([a], [b]) => a.localeCompare(b))) {
1754
+ const pascalName = domainToPascalCase(domain);
1755
+ const entries = [...codes.values()].sort((a, b) => {
1756
+ if (typeof a.code === "number" && typeof b.code === "number") return a.code - b.code;
1757
+ const sa = String(a.code);
1758
+ const sb = String(b.code);
1759
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
1760
+ }).map(({ code, name, description }) => {
1761
+ const comment = description ? ` /** ${description} */\n ` : " ";
1762
+ const key = name ?? (typeof code === "string" ? code : `ERROR_${code}`);
1763
+ if (!VALID_IDENTIFIER.test(key)) throw new Error(`Domain error code "${code}" produces an invalid identifier "${key}". Use the 'name' field on @ApiDomainErrorResponse to provide a valid identifier.`);
1764
+ return `${comment}${key}: ${typeof code === "string" ? `"${code}"` : String(code)}`;
1765
+ }).join(",\n");
1766
+ blocks.push(`export const ${pascalName}DomainErrors = {\n${entries},\n} as const;`);
1767
+ blocks.push(`export type ${pascalName}DomainErrorCode = (typeof ${pascalName}DomainErrors)[keyof typeof ${pascalName}DomainErrors];`);
1768
+ }
1769
+ return blocks.join("\n\n") + "\n";
1770
+ }
1771
+ //#endregion
1772
+ //#region src/generators/generate/generateQueryModules.ts
1773
+ function generateQueryModules({ resolver, data }) {
1774
+ const nativeContent = resolver.getNativeRenderedShared?.("queryModules");
1775
+ if (nativeContent) return nativeContent;
1776
+ const modules = [];
1777
+ data.forEach((_, tag) => {
1778
+ const endpoints = data.get(tag)?.endpoints;
1779
+ if (!endpoints || endpoints.length === 0) return;
1780
+ modules.push({
1781
+ tag,
1782
+ namespace: getNamespaceName({
1783
+ type: "queries",
1784
+ tag,
1785
+ options: resolver.options
1786
+ })
1787
+ });
1788
+ });
1789
+ const lines = [];
1790
+ lines.push("export const enum QueryModule {");
1791
+ for (const module of modules) lines.push(` ${module.tag} = "${module.namespace}",`);
1792
+ lines.push("}");
1793
+ return lines.join("\n");
1794
+ }
1795
+ //#endregion
1796
+ //#region src/generators/utils/generate-files.utils.ts
1797
+ function getAclFiles(data, resolver) {
1798
+ if (!resolver.options.acl) return [];
1799
+ return [{
1800
+ fileName: getOutputFileName({
1801
+ output: resolver.options.output,
1802
+ fileName: getFileNameWithExtension(ACL_APP_ABILITY_FILE)
1803
+ }),
1804
+ content: generateAppAcl({
1805
+ resolver,
1806
+ data
1807
+ })
1808
+ }];
1809
+ }
1810
+ function getMutationEffectsFiles(data, resolver) {
1811
+ if (!resolver.options.mutationEffects) return [];
1812
+ return [{
1813
+ fileName: getOutputFileName({
1814
+ output: resolver.options.output,
1815
+ fileName: getFileNameWithExtension(QUERY_MODULES_FILE)
1816
+ }),
1817
+ content: generateQueryModules({
1818
+ resolver,
1819
+ data
1820
+ })
1821
+ }];
1822
+ }
1823
+ function getZodExtendedFiles(_data, _resolver) {
1824
+ return [];
1825
+ }
1826
+ function getDomainErrorsFiles(data, resolver) {
1827
+ const content = generateDomainErrors({
1828
+ resolver,
1829
+ data
1830
+ });
1831
+ if (!content) return [];
1832
+ return [{
1833
+ fileName: getOutputFileName({
1834
+ output: resolver.options.output,
1835
+ fileName: getFileNameWithExtension(DOMAIN_ERRORS_FILE)
1836
+ }),
1837
+ content
1838
+ }];
1839
+ }
1840
+ function getAppRestClientFiles(resolver) {
1841
+ if (resolver.options.restClientImportPath !== DEFAULT_GENERATE_OPTIONS.restClientImportPath) return [];
1842
+ return [{
1843
+ fileName: getOutputFileName({
1844
+ output: resolver.options.output,
1845
+ fileName: getFileNameWithExtension(APP_REST_CLIENT_FILE)
1846
+ }),
1847
+ content: generateAppRestClient(resolver)
1848
+ }];
1849
+ }
1850
+ //#endregion
1851
+ //#region src/native/getDataFromNativeOpenAPIDoc.ts
1852
+ var NativeSchemaResolver = class {
1853
+ nativeData;
1854
+ options;
1855
+ openApiDoc;
1856
+ dependencyGraph;
1857
+ refByName;
1858
+ nameByRef;
1859
+ circularSchemas;
1860
+ referencedNames = /* @__PURE__ */ new Map();
1861
+ enumObjectsByCode;
1862
+ constructor(openApiDoc, options, nativeData) {
1863
+ this.nativeData = nativeData;
1864
+ this.openApiDoc = openApiDoc;
1865
+ this.options = options;
1866
+ this.refByName = new Map(Object.entries(nativeData.schemaRefs));
1867
+ for (const name of Object.keys(nativeData.generatedObjects)) if (!this.refByName.has(name)) this.refByName.set(name, `#/x-native-schemas/${encodeURIComponent(name)}`);
1868
+ this.nameByRef = new Map([...this.refByName].map(([name, ref]) => [ref, name]));
1869
+ this.circularSchemas = new Set(nativeData.circularSchemas);
1870
+ const refsDependencyGraph = Object.fromEntries(Object.entries(nativeData.dependencies).map(([ref, dependencies]) => [ref, new Set(dependencies)]));
1871
+ this.dependencyGraph = {
1872
+ refsDependencyGraph,
1873
+ deepDependencyGraph: {}
1874
+ };
1875
+ for (const name of Object.keys(nativeData.generatedObjects)) {
1876
+ const ref = this.refByName.get(name);
1877
+ const dependencies = /* @__PURE__ */ new Set();
1878
+ const addDependency = (dependency) => {
1879
+ if (dependency === ref || dependencies.has(dependency)) return;
1880
+ dependencies.add(dependency);
1881
+ for (const child of this.dependencyGraph.refsDependencyGraph[dependency] ?? []) addDependency(child);
1882
+ };
1883
+ for (const dependencyName of nativeData.generatedDependencies[name] ?? []) {
1884
+ const dependency = this.refByName.get(dependencyName);
1885
+ if (dependency) addDependency(dependency);
1886
+ }
1887
+ this.dependencyGraph.refsDependencyGraph[ref] = dependencies;
1888
+ }
1889
+ }
1890
+ getCodeByZodSchemaName(name) {
1891
+ return this.nativeData.schemas[name];
1892
+ }
1893
+ getNativeRenderedModels(tag) {
1894
+ return this.nativeData.renderedModels[tag];
1895
+ }
1896
+ getNativeRenderedEndpoints(tag) {
1897
+ return this.nativeData.renderedEndpoints[tag];
1898
+ }
1899
+ getNativeRenderedQueries(tag) {
1900
+ return this.nativeData.renderedQueries[tag];
1901
+ }
1902
+ getNativeRenderedAcl(tag) {
1903
+ return this.nativeData.renderedAcl[tag];
1904
+ }
1905
+ getNativeRenderedShared(name) {
1906
+ return this.nativeData.renderedShared[name];
1907
+ }
1908
+ getRefByZodSchemaName(name) {
1909
+ return this.refByName.get(name);
1910
+ }
1911
+ getZodSchemaNameByRef(ref) {
1912
+ return this.nameByRef.get(normalizeRef(ref));
1913
+ }
1914
+ getTagByZodSchemaName(name) {
1915
+ return this.options.modelsInCommon ? this.options.defaultTag : this.nativeData.schemaOwners[name];
1916
+ }
1917
+ isSchemaCircular(ref) {
1918
+ const name = this.nameByRef.get(normalizeRef(ref));
1919
+ return Boolean(name && this.circularSchemas.has(name));
1920
+ }
1921
+ getZodSchemaObj(name) {
1922
+ if (this.nativeData.generatedObjects[name]) return this.nativeData.generatedObjects[name];
1923
+ const ref = this.refByName.get(name);
1924
+ if (ref) return this.resolveRef(ref);
1925
+ const code = this.nativeData.schemas[name];
1926
+ if (!code?.startsWith("z.enum(")) return void 0;
1927
+ this.enumObjectsByCode ??= collectEnumObjects(this.openApiDoc);
1928
+ return this.enumObjectsByCode.get(code);
1929
+ }
1930
+ getExtractedEnumZodSchemaNamesReferencedBySchemaRef(ref) {
1931
+ const normalizedRef = normalizeRef(ref);
1932
+ const cached = this.referencedNames.get(normalizedRef);
1933
+ if (cached) return cached;
1934
+ const name = this.nameByRef.get(normalizedRef);
1935
+ const code = name ? this.nativeData.schemas[name] : void 0;
1936
+ const directNames = new Set([...this.dependencyGraph.refsDependencyGraph[normalizedRef] ?? []].map((dependency) => this.nameByRef.get(dependency)).filter((value) => Boolean(value)));
1937
+ const references = [...code ? [...code.matchAll(/\b[A-Za-z_$][\w$]*Schema\b/g)].map(([match]) => match).filter((match, index, values) => match !== name && values.indexOf(match) === index && match in this.nativeData.schemas && !directNames.has(match)) : []].filter((value, index, values) => values.indexOf(value) === index);
1938
+ this.referencedNames.set(normalizedRef, references);
1939
+ return references;
1940
+ }
1941
+ getCompositeZodSchemaByZodSchemaName() {}
1942
+ resolveObject(value) {
1943
+ if (value && typeof value === "object" && "$ref" in value) return this.resolveRef(value.$ref);
1944
+ return value;
1945
+ }
1946
+ getBaseUrl() {
1947
+ return this.nativeData.baseUrl;
1948
+ }
1949
+ resolveRef(ref) {
1950
+ const segments = normalizeRef(ref).slice(2).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
1951
+ let value = this.openApiDoc;
1952
+ for (const segment of segments) value = value?.[segment];
1953
+ return value;
1954
+ }
1955
+ };
1956
+ function collectEnumObjects(document) {
1957
+ const enums = /* @__PURE__ */ new Map();
1958
+ const visit = (value) => {
1959
+ if (!value || typeof value !== "object") return;
1960
+ if (Array.isArray(value)) {
1961
+ value.forEach(visit);
1962
+ return;
1963
+ }
1964
+ const object = value;
1965
+ if (Array.isArray(object.enum)) {
1966
+ const code = `z.enum(${JSON.stringify(object.enum)})`.replaceAll(",", ", ");
1967
+ Object.assign(enums.get(code) ?? {}, object);
1968
+ enums.set(code, {
1969
+ ...enums.get(code) ?? {},
1970
+ ...object
1971
+ });
1972
+ }
1973
+ Object.values(object).forEach(visit);
1974
+ };
1975
+ visit(document.components?.schemas ?? {});
1976
+ return enums;
1977
+ }
1978
+ function normalizeRef(ref) {
1979
+ if (ref.startsWith("#/")) return ref;
1980
+ if (ref.startsWith("#")) return `#/${ref.slice(1).replace(/^\//, "")}`;
1981
+ return ref;
1982
+ }
1983
+ function getTagElement(tag, data) {
1984
+ let value = data.get(tag);
1985
+ if (!value) {
1986
+ value = {
1987
+ endpoints: [],
1988
+ zodSchemas: {}
1989
+ };
1990
+ data.set(tag, value);
1991
+ }
1992
+ return value;
1993
+ }
1994
+ function getDataFromNativeOpenAPIDoc(openApiDoc, options, nativeSource) {
1995
+ const started = performance.now();
1996
+ const source = nativeSource?.source ?? JSON.stringify(openApiDoc);
1997
+ const afterLoad = performance.now();
1998
+ const nativeResult = compileNativeData(source, nativeSource?.yaml ?? false, JSON.stringify({
1999
+ ...options,
2000
+ nativeCompact: true
2001
+ }));
2002
+ const afterNative = performance.now();
2003
+ const nativeData = nativeResult.data;
2004
+ const afterParse = performance.now();
2005
+ const resolver = new NativeSchemaResolver(nativeData.document ?? openApiDoc, options, nativeData);
2006
+ const afterResolver = performance.now();
2007
+ const data = /* @__PURE__ */ new Map();
2008
+ if (nativeData.renderedComplete) {
2009
+ for (const tag of nativeData.renderedTags) data.set(tag, {
2010
+ endpoints: [],
2011
+ zodSchemas: {}
2012
+ });
2013
+ if (process.env.OPENAPI_NATIVE_PROFILE === "1") console.error(`native bridge load=${(afterLoad - started).toFixed(1)}ms call=${(afterNative - afterLoad).toFixed(1)}ms parse=${(afterParse - afterNative).toFixed(1)}ms facade=${(performance.now() - afterParse).toFixed(1)}ms compact=true`);
2014
+ return {
2015
+ resolver,
2016
+ data
2017
+ };
2018
+ }
2019
+ if (!options.splitByTags) {
2020
+ data.set(options.defaultTag, {
2021
+ endpoints: nativeData.endpoints,
2022
+ zodSchemas: nativeData.schemas
2023
+ });
2024
+ return {
2025
+ resolver,
2026
+ data
2027
+ };
2028
+ }
2029
+ for (const endpoint of nativeData.endpoints) getTagElement(getEndpointTag(endpoint, options), data).endpoints.push(endpoint);
2030
+ for (const [name, code] of Object.entries(nativeData.schemas)) {
2031
+ const tag = options.modelsInCommon ? options.defaultTag : nativeData.schemaOwners[name];
2032
+ if (tag) getTagElement(tag, data).zodSchemas[name] = code;
2033
+ }
2034
+ if (process.env.OPENAPI_NATIVE_PROFILE === "1") console.error(`native bridge load=${(afterLoad - started).toFixed(1)}ms call=${(afterNative - afterLoad).toFixed(1)}ms parse=${(afterParse - afterNative).toFixed(1)}ms facade=${(afterResolver - afterParse).toFixed(1)}ms split=${(performance.now() - afterResolver).toFixed(1)}ms`);
2035
+ return {
2036
+ resolver,
2037
+ data
2038
+ };
2039
+ }
2040
+ //#endregion
2041
+ //#region src/generators/generateCodeFromOpenAPIDoc.ts
2042
+ var generateCodeFromOpenAPIDoc_exports = /* @__PURE__ */ __exportAll({ generateCodeFromOpenAPIDoc: () => generateCodeFromOpenAPIDoc });
2043
+ function generateCodeFromOpenAPIDoc(openApiDoc, options, profiler, nativeSource) {
2044
+ const p = profiler ?? new Profiler(false);
2045
+ const importPath = options.standalone && options.importPath === "ts" ? "relative" : options.importPath;
2046
+ const resolvedOptions = {
2047
+ ...options,
2048
+ importPath
2049
+ };
2050
+ const { resolver, data } = p.runSync("data.extract", () => nativeSource && shouldUseNativeCodegen() ? getDataFromNativeOpenAPIDoc(openApiDoc, resolvedOptions, nativeSource) : getDataFromOpenAPIDoc(openApiDoc, resolvedOptions, p));
2051
+ const generateFilesData = [];
2052
+ const appAclTags = [];
2053
+ const modelsOnly = Boolean(resolver.options.modelsOnly);
2054
+ const shouldGenerateEndpoints = !modelsOnly && Array.from(data.keys()).some((tag) => !shouldInlineEndpointsForTag(tag, resolver.options));
2055
+ const generateTypes = modelsOnly ? ["models"] : [
2056
+ "models",
2057
+ ...shouldGenerateEndpoints ? ["endpoints"] : [],
2058
+ "queries",
2059
+ ...resolver.options.acl ? ["acl"] : [],
2060
+ ...resolver.options.builderConfigs ? ["configs"] : []
2061
+ ];
2062
+ const generateFunctions = {
2063
+ ["models"]: generateModels,
2064
+ ["endpoints"]: generateEndpoints,
2065
+ ["queries"]: generateQueries,
2066
+ ["acl"]: generateAcl,
2067
+ ["configs"]: generateConfigs
2068
+ };
2069
+ data.forEach((_, tag) => {
2070
+ generateTypes.forEach((type) => {
2071
+ const content = p.runSync(`render.${type}`, () => generateFunctions[type]({
2072
+ resolver,
2073
+ data,
2074
+ tag
2075
+ }));
2076
+ if (content) {
2077
+ const fileName = getOutputFileName({
2078
+ output: options.output,
2079
+ fileName: getTagFileName({
2080
+ tag,
2081
+ type,
2082
+ options
2083
+ })
2084
+ });
2085
+ generateFilesData.push({
2086
+ fileName,
2087
+ content
2088
+ });
2089
+ if (type === "acl") appAclTags.push(tag);
2090
+ }
2091
+ });
2092
+ });
2093
+ 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)), ...p.runSync("render.DomainErrors", () => getDomainErrorsFiles(data, resolver)));
2094
+ return generateFilesData;
2095
+ }
2096
+ //#endregion
2097
+ export { generateCodeFromOpenAPIDoc_exports as n, generateCodeFromOpenAPIDoc as t };