@povio/openapi-codegen-cli 3.1.0 → 3.2.0-rc.2

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