@kubb/plugin-vue-query 5.0.0-beta.56 → 5.0.0-beta.73

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 (40) hide show
  1. package/README.md +2 -2
  2. package/dist/index.cjs +1638 -55
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +430 -3
  5. package/dist/index.js +1610 -49
  6. package/dist/index.js.map +1 -1
  7. package/package.json +10 -20
  8. package/dist/components-B79Gljyl.js +0 -1195
  9. package/dist/components-B79Gljyl.js.map +0 -1
  10. package/dist/components-D3xIZ9FA.cjs +0 -1315
  11. package/dist/components-D3xIZ9FA.cjs.map +0 -1
  12. package/dist/components.cjs +0 -9
  13. package/dist/components.d.ts +0 -187
  14. package/dist/components.js +0 -2
  15. package/dist/generators-BTtcGtUY.cjs +0 -637
  16. package/dist/generators-BTtcGtUY.cjs.map +0 -1
  17. package/dist/generators-D95ddIFV.js +0 -620
  18. package/dist/generators-D95ddIFV.js.map +0 -1
  19. package/dist/generators.cjs +0 -5
  20. package/dist/generators.d.ts +0 -30
  21. package/dist/generators.js +0 -2
  22. package/dist/types-CwabLiFK.d.ts +0 -266
  23. package/src/components/InfiniteQuery.tsx +0 -127
  24. package/src/components/InfiniteQueryOptions.tsx +0 -191
  25. package/src/components/Mutation.tsx +0 -150
  26. package/src/components/MutationKey.tsx +0 -1
  27. package/src/components/Query.tsx +0 -126
  28. package/src/components/QueryKey.tsx +0 -52
  29. package/src/components/QueryOptions.tsx +0 -116
  30. package/src/components/index.ts +0 -7
  31. package/src/generators/index.ts +0 -3
  32. package/src/generators/infiniteQueryGenerator.tsx +0 -196
  33. package/src/generators/mutationGenerator.tsx +0 -157
  34. package/src/generators/queryGenerator.tsx +0 -180
  35. package/src/index.ts +0 -2
  36. package/src/plugin.ts +0 -183
  37. package/src/resolvers/resolverVueQuery.ts +0 -76
  38. package/src/types.ts +0 -268
  39. package/src/utils.ts +0 -57
  40. /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,1315 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __name = (target, value) => __defProp(target, "name", {
5
- value,
6
- configurable: true
7
- });
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
- key = keys[i];
15
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
- //#endregion
27
- let _kubb_core = require("@kubb/core");
28
- let _kubb_plugin_ts = require("@kubb/plugin-ts");
29
- let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
30
- let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
31
- let _kubb_ast_utils = require("@kubb/ast/utils");
32
- //#region ../../internals/utils/src/casing.ts
33
- /**
34
- * Shared implementation for camelCase and PascalCase conversion.
35
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
36
- * and capitalizes each word according to `pascal`.
37
- *
38
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
39
- */
40
- function toCamelOrPascal(text, pascal) {
41
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
42
- if (word.length > 1 && word === word.toUpperCase()) return word;
43
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
44
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
45
- }
46
- /**
47
- * Converts `text` to camelCase.
48
- *
49
- * @example Word boundaries
50
- * `camelCase('hello-world') // 'helloWorld'`
51
- *
52
- * @example With a prefix
53
- * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
54
- */
55
- function camelCase(text, { prefix = "", suffix = "" } = {}) {
56
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
57
- }
58
- //#endregion
59
- //#region ../../internals/utils/src/reserved.ts
60
- /**
61
- * JavaScript and Java reserved words.
62
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
63
- */
64
- const reservedWords = new Set([
65
- "abstract",
66
- "arguments",
67
- "boolean",
68
- "break",
69
- "byte",
70
- "case",
71
- "catch",
72
- "char",
73
- "class",
74
- "const",
75
- "continue",
76
- "debugger",
77
- "default",
78
- "delete",
79
- "do",
80
- "double",
81
- "else",
82
- "enum",
83
- "eval",
84
- "export",
85
- "extends",
86
- "false",
87
- "final",
88
- "finally",
89
- "float",
90
- "for",
91
- "function",
92
- "goto",
93
- "if",
94
- "implements",
95
- "import",
96
- "in",
97
- "instanceof",
98
- "int",
99
- "interface",
100
- "let",
101
- "long",
102
- "native",
103
- "new",
104
- "null",
105
- "package",
106
- "private",
107
- "protected",
108
- "public",
109
- "return",
110
- "short",
111
- "static",
112
- "super",
113
- "switch",
114
- "synchronized",
115
- "this",
116
- "throw",
117
- "throws",
118
- "transient",
119
- "true",
120
- "try",
121
- "typeof",
122
- "var",
123
- "void",
124
- "volatile",
125
- "while",
126
- "with",
127
- "yield",
128
- "Array",
129
- "Date",
130
- "hasOwnProperty",
131
- "Infinity",
132
- "isFinite",
133
- "isNaN",
134
- "isPrototypeOf",
135
- "length",
136
- "Math",
137
- "name",
138
- "NaN",
139
- "Number",
140
- "Object",
141
- "prototype",
142
- "String",
143
- "toString",
144
- "undefined",
145
- "valueOf"
146
- ]);
147
- /**
148
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
149
- *
150
- * @example
151
- * ```ts
152
- * isValidVarName('status') // true
153
- * isValidVarName('class') // false (reserved word)
154
- * isValidVarName('42foo') // false (starts with digit)
155
- * ```
156
- */
157
- function isValidVarName(name) {
158
- if (!name || reservedWords.has(name)) return false;
159
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
160
- }
161
- //#endregion
162
- //#region ../../internals/utils/src/url.ts
163
- function transformParam(raw, casing) {
164
- const param = isValidVarName(raw) ? raw : camelCase(raw);
165
- return casing === "camelcase" ? camelCase(param) : param;
166
- }
167
- function toParamsObject(path, { replacer, casing } = {}) {
168
- const params = {};
169
- for (const match of path.matchAll(/\{([^}]+)\}/g)) {
170
- const param = transformParam(match[1], casing);
171
- const key = replacer ? replacer(param) : param;
172
- params[key] = key;
173
- }
174
- return Object.keys(params).length > 0 ? params : null;
175
- }
176
- /**
177
- * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.
178
- */
179
- var Url = class Url {
180
- /**
181
- * Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.
182
- *
183
- * @example
184
- * Url.canParse('https://petstore.swagger.io/v2') // true
185
- * Url.canParse('/pet/{petId}') // false
186
- */
187
- static canParse(url, base) {
188
- return URL.canParse(url, base);
189
- }
190
- /**
191
- * Converts an OpenAPI/Swagger path to Express-style colon syntax.
192
- *
193
- * @example
194
- * Url.toPath('/pet/{petId}') // '/pet/:petId'
195
- */
196
- static toPath(path) {
197
- return path.replace(/\{([^}]+)\}/g, ":$1");
198
- }
199
- /**
200
- * Converts an OpenAPI/Swagger path to a TypeScript template literal string.
201
- * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,
202
- * and `casing` controls parameter identifier casing.
203
- *
204
- * @example
205
- * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'
206
- *
207
- * @example
208
- * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'
209
- */
210
- static toTemplateString(path, { prefix, replacer, casing } = {}) {
211
- const result = path.split(/\{([^}]+)\}/).map((part, i) => {
212
- if (i % 2 === 0) return part;
213
- const param = transformParam(part, casing);
214
- return `\${${replacer ? replacer(param) : param}}`;
215
- }).join("");
216
- return `\`${prefix ?? ""}${result}\``;
217
- }
218
- /**
219
- * Returns the path and its extracted params as a structured `URLObject`, or as a stringified
220
- * expression when `stringify` is set.
221
- *
222
- * @example
223
- * Url.toObject('/pet/{petId}')
224
- * // { url: '/pet/:petId', params: { petId: 'petId' } }
225
- */
226
- static toObject(path, { type = "path", replacer, stringify, casing } = {}) {
227
- const object = {
228
- url: type === "path" ? Url.toPath(path) : Url.toTemplateString(path, {
229
- replacer,
230
- casing
231
- }),
232
- params: toParamsObject(path, {
233
- replacer,
234
- casing
235
- })
236
- };
237
- if (stringify) {
238
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
239
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
240
- return `{ url: '${object.url}' }`;
241
- }
242
- return object;
243
- }
244
- };
245
- //#endregion
246
- //#region ../../internals/shared/src/operation.ts
247
- /**
248
- * Builds the `ResolverFileParams` every operation generator passes to
249
- * `resolver.resolveFile`: a file named `name`, tagged by the operation's first
250
- * tag (or `'default'`), at the operation's path. Centralizes the entry object
251
- * that was repeated at dozens of call sites across the client and query plugins.
252
- *
253
- * @example
254
- * ```ts
255
- * resolver.resolveFile(operationFileEntry(node, node.operationId), { root, output, group })
256
- * ```
257
- */
258
- function operationFileEntry(node, name, extname = ".ts") {
259
- return {
260
- name,
261
- extname,
262
- tag: node.tags[0] ?? "default",
263
- path: node.path
264
- };
265
- }
266
- function getOperationLink(node, link) {
267
- if (!link) return null;
268
- if (typeof link === "function") return link(node) ?? null;
269
- if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
270
- return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
271
- }
272
- function getContentTypeInfo(node) {
273
- const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
274
- const isMultipleContentTypes = contentTypes.length > 1;
275
- return {
276
- contentTypes,
277
- isMultipleContentTypes,
278
- contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
279
- defaultContentType: contentTypes[0] ?? "application/json",
280
- hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
281
- };
282
- }
283
- function buildRequestConfigType(node, resolver) {
284
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
285
- const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
286
- return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
287
- }
288
- function buildOperationComments(node, options = {}) {
289
- const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
290
- const linkComment = getOperationLink(node, link);
291
- const filteredComments = (linkPosition === "beforeDeprecated" ? [
292
- node.description && `@description ${node.description}`,
293
- node.summary && `@summary ${node.summary}`,
294
- linkComment,
295
- node.deprecated && "@deprecated"
296
- ] : [
297
- node.description && `@description ${node.description}`,
298
- node.summary && `@summary ${node.summary}`,
299
- node.deprecated && "@deprecated",
300
- linkComment
301
- ]).filter((comment) => Boolean(comment));
302
- if (!splitLines) return filteredComments;
303
- return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
304
- }
305
- function getOperationParameters(node, options = {}) {
306
- const params = _kubb_core.ast.caseParams(node.parameters, options.paramsCasing);
307
- return {
308
- path: params.filter((param) => param.in === "path"),
309
- query: params.filter((param) => param.in === "query"),
310
- header: params.filter((param) => param.in === "header"),
311
- cookie: params.filter((param) => param.in === "cookie")
312
- };
313
- }
314
- function getStatusCodeNumber(statusCode) {
315
- const code = Number(statusCode);
316
- return Number.isNaN(code) ? null : code;
317
- }
318
- function isSuccessStatusCode(statusCode) {
319
- const code = getStatusCodeNumber(statusCode);
320
- return code !== null && code >= 200 && code < 300;
321
- }
322
- function isErrorStatusCode(statusCode) {
323
- const code = getStatusCodeNumber(statusCode);
324
- return code !== null && code >= 400;
325
- }
326
- function resolveErrorNames(node, resolver) {
327
- return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
328
- }
329
- function resolveSuccessNames(node, resolver) {
330
- return node.responses.filter((response) => isSuccessStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
331
- }
332
- function resolveStatusCodeNames(node, resolver) {
333
- return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
334
- }
335
- /**
336
- * Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
337
- * Each member is `{ status: N; data: StatusNType; statusText: string }`.
338
- */
339
- function buildStatusUnionType(node, resolver) {
340
- const members = node.responses.map((r) => {
341
- const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
342
- const statusCode = Number.parseInt(r.statusCode, 10);
343
- return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
344
- });
345
- if (members.length === 1) return members[0];
346
- return `(${members.join(" | ")})`;
347
- }
348
- const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
349
- function resolveOperationTypeNames(node, resolver, options = {}) {
350
- const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
351
- let byResolver = typeNamesByResolver.get(resolver);
352
- if (byResolver) {
353
- const cached = byResolver.get(cacheKey);
354
- if (cached) return cached;
355
- } else {
356
- byResolver = /* @__PURE__ */ new Map();
357
- typeNamesByResolver.set(resolver, byResolver);
358
- }
359
- const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
360
- const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
361
- const exclude = new Set(options.exclude ?? []);
362
- const paramNames = [
363
- ...path.map((param) => resolver.resolvePathParamsName(node, param)),
364
- ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
365
- ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
366
- ];
367
- const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
368
- const result = (options.order === "body-response-first" ? [
369
- ...bodyAndResponseNames,
370
- ...paramNames,
371
- ...responseStatusNames
372
- ] : [
373
- ...paramNames,
374
- ...bodyAndResponseNames,
375
- ...responseStatusNames
376
- ]).filter((name) => Boolean(name) && !exclude.has(name));
377
- byResolver.set(cacheKey, result);
378
- return result;
379
- }
380
- //#endregion
381
- //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
382
- const declarationPrinter$7 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
383
- const mutationKeyTransformer = ({ node }) => {
384
- if (!node.path) return [];
385
- return [`{ url: '${Url.toPath(node.path)}' }`];
386
- };
387
- function MutationKey({ name, paramsCasing, node, transformer }) {
388
- const paramsNode = _kubb_core.ast.createFunctionParameters({ params: [] });
389
- const paramsSignature = declarationPrinter$7.print(paramsNode) ?? "";
390
- const keys = (transformer ?? mutationKeyTransformer)({
391
- node,
392
- casing: paramsCasing
393
- });
394
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
395
- name,
396
- isExportable: true,
397
- isIndexable: true,
398
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
399
- name,
400
- export: true,
401
- params: paramsSignature,
402
- singleLine: true,
403
- children: `[${keys.join(", ")}] as const`
404
- })
405
- });
406
- }
407
- //#endregion
408
- //#region ../../internals/tanstack-query/src/utils.ts
409
- /**
410
- * Builds the shared `(…params, config = {})` parameter list for a TanStack
411
- * query-options function. The trailing `config` parameter is typed as a partial
412
- * `RequestConfig` with an optional `client`. Framework plugins wrap the result
413
- * when needed, for example vue-query applies `MaybeRefOrGetter`.
414
- */
415
- function buildQueryOptionsParams(node, options) {
416
- const { paramsType, paramsCasing, pathParamsType, resolver } = options;
417
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
418
- return _kubb_core.ast.createOperationParams(node, {
419
- paramsType,
420
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
421
- paramsCasing,
422
- resolver,
423
- extraParams: [_kubb_core.ast.createFunctionParameter({
424
- name: "config",
425
- type: _kubb_core.ast.createParamsType({
426
- variant: "reference",
427
- name: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"
428
- }),
429
- default: "{}"
430
- })]
431
- });
432
- }
433
- /**
434
- * Returns `'zod'` when response-direction parsing is enabled.
435
- * The string shorthand `'zod'` also enables response parsing.
436
- */
437
- function resolveResponseParser(parser) {
438
- if (!parser) return null;
439
- if (parser === "zod") return "zod";
440
- return parser.response ?? null;
441
- }
442
- /**
443
- * Returns `'zod'` when request body parsing is enabled.
444
- * The string shorthand `'zod'` also enables request body parsing (existing behavior).
445
- */
446
- function resolveRequestParser(parser) {
447
- if (!parser) return null;
448
- if (parser === "zod") return "zod";
449
- return parser.request ?? null;
450
- }
451
- /**
452
- * Returns `'zod'` when query-params parsing is enabled.
453
- * Only the object form `{ request: 'zod' }` enables this. `parser: 'zod'` does not.
454
- */
455
- function resolveQueryParamsParser(parser) {
456
- if (!parser || parser === "zod") return null;
457
- return parser.request ?? null;
458
- }
459
- /**
460
- * Collects the Zod schema import names for an operation based on the active parser directions.
461
- *
462
- * - `parser: 'zod'`: response and request body names (backward-compatible behavior).
463
- * - `parser: { request: 'zod' }`: request body and query params names.
464
- * - `parser: { response: 'zod' }`: response name only.
465
- * - `parser: { request: 'zod', response: 'zod' }`: all three.
466
- *
467
- * Returns an empty array when no resolver is provided or `parser` is falsy.
468
- */
469
- function resolveZodSchemaNames(node, zodResolver, parser) {
470
- if (!zodResolver || !parser) return [];
471
- const { query: queryParams } = getOperationParameters(node);
472
- return [
473
- resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
474
- resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
475
- resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
476
- ].filter((n) => Boolean(n));
477
- }
478
- /**
479
- * Resolve the type for a single path parameter.
480
- *
481
- * - When the resolver's group name differs from the individual param name
482
- * (e.g. kubbV4) → `GroupName['paramName']` (member access).
483
- * - When they match (v5 default) → `TypeName` (direct reference).
484
- */
485
- function resolvePathParamType(node, param, resolver) {
486
- const individualName = resolver.resolveParamName(node, param);
487
- const groupName = resolver.resolvePathParamsName(node, param);
488
- if (groupName !== individualName) return _kubb_core.ast.createParamsType({
489
- variant: "member",
490
- base: groupName,
491
- key: param.name
492
- });
493
- return _kubb_core.ast.createParamsType({
494
- variant: "reference",
495
- name: individualName
496
- });
497
- }
498
- /**
499
- * Derive a query-params group type from the resolver.
500
- * Returns `null` when no query params exist or when the group name
501
- * equals the individual param name (no real group).
502
- */
503
- function resolveQueryGroupType(node, params, resolver) {
504
- if (!params.length) return null;
505
- const firstParam = params[0];
506
- const groupName = resolver.resolveQueryParamsName(node, firstParam);
507
- if (groupName === resolver.resolveParamName(node, firstParam)) return null;
508
- return {
509
- type: _kubb_core.ast.createParamsType({
510
- variant: "reference",
511
- name: groupName
512
- }),
513
- optional: params.every((p) => !p.required)
514
- };
515
- }
516
- /**
517
- * Build a single `FunctionParameterNode` for a query or header group.
518
- */
519
- function buildGroupParam(name, node, params, groupType, resolver) {
520
- if (groupType) return [_kubb_core.ast.createFunctionParameter({
521
- name,
522
- type: groupType.type,
523
- optional: groupType.optional
524
- })];
525
- if (params.length) {
526
- const structProps = params.map((p) => ({
527
- name: p.name,
528
- type: _kubb_core.ast.createParamsType({
529
- variant: "reference",
530
- name: resolver.resolveParamName(node, p)
531
- }),
532
- optional: !p.required
533
- }));
534
- return [_kubb_core.ast.createFunctionParameter({
535
- name,
536
- type: _kubb_core.ast.createParamsType({
537
- variant: "struct",
538
- properties: structProps
539
- }),
540
- optional: params.every((p) => !p.required)
541
- })];
542
- }
543
- return [];
544
- }
545
- /**
546
- * Build QueryKey params: pathParams + data + queryParams (NO headers, NO config).
547
- */
548
- function buildQueryKeyParams(node, options) {
549
- const { pathParamsType, paramsCasing, resolver } = options;
550
- const casedParams = _kubb_core.ast.caseParams(node.parameters, paramsCasing);
551
- const pathParams = casedParams.filter((p) => p.in === "path");
552
- const queryParams = casedParams.filter((p) => p.in === "query");
553
- const queryGroupType = resolveQueryGroupType(node, queryParams, resolver);
554
- const bodyType = node.requestBody?.content?.[0]?.schema ? _kubb_core.ast.createParamsType({
555
- variant: "reference",
556
- name: resolver.resolveDataName(node)
557
- }) : null;
558
- const bodyRequired = node.requestBody?.required ?? false;
559
- const params = [];
560
- if (pathParams.length) {
561
- const pathChildren = pathParams.map((p) => _kubb_core.ast.createFunctionParameter({
562
- name: p.name,
563
- type: resolvePathParamType(node, p, resolver),
564
- optional: !p.required
565
- }));
566
- params.push({
567
- kind: "ParameterGroup",
568
- properties: pathChildren,
569
- inline: pathParamsType === "inline",
570
- default: pathChildren.every((c) => c.optional) ? "{}" : void 0
571
- });
572
- }
573
- if (bodyType) params.push(_kubb_core.ast.createFunctionParameter({
574
- name: "data",
575
- type: bodyType,
576
- optional: !bodyRequired
577
- }));
578
- params.push(...buildGroupParam("params", node, queryParams, queryGroupType, resolver));
579
- return _kubb_core.ast.createFunctionParameters({ params });
580
- }
581
- /**
582
- * Collect the names of the required params (no default) that drive the `enabled`
583
- * guard. These are exactly the params that should be made optional in the
584
- * generated signatures so callers can pass `undefined` to reach the disabled state.
585
- */
586
- function getEnabledParamNames(paramsNode) {
587
- const required = [];
588
- for (const param of paramsNode.params) if ("kind" in param && param.kind === "ParameterGroup") {
589
- const group = param;
590
- for (const child of group.properties) if (!child.optional && child.default === void 0) required.push(child.name);
591
- } else {
592
- const fp = param;
593
- if (!fp.optional && fp.default === void 0) required.push(fp.name);
594
- }
595
- return required;
596
- }
597
- /**
598
- * Return a copy of `paramsNode` with the named params marked optional.
599
- *
600
- * Used to align signatures with the `enabled` guard: the guard already disables
601
- * the query while a param is falsy, so the param should accept `undefined`. The
602
- * change is type-only — the `queryFn` keeps calling the client with a non-null
603
- * assertion (see `injectNonNullAssertions`), so the emitted runtime is unchanged.
604
- */
605
- function markParamsOptional(paramsNode, names) {
606
- if (names.length === 0) return paramsNode;
607
- const nameSet = new Set(names);
608
- const params = paramsNode.params.map((param) => {
609
- if ("kind" in param && param.kind === "ParameterGroup") {
610
- const group = param;
611
- return {
612
- ...group,
613
- properties: group.properties.map((child) => nameSet.has(child.name) ? _kubb_core.ast.createFunctionParameter({
614
- name: child.name,
615
- type: child.type,
616
- rest: child.rest,
617
- optional: true
618
- }) : child)
619
- };
620
- }
621
- const fp = param;
622
- return nameSet.has(fp.name) ? _kubb_core.ast.createFunctionParameter({
623
- name: fp.name,
624
- type: fp.type,
625
- rest: fp.rest,
626
- optional: true
627
- }) : fp;
628
- });
629
- return _kubb_core.ast.createFunctionParameters({ params });
630
- }
631
- (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
632
- const queryKeyTransformer = ({ node, casing }) => {
633
- if (!node.path) return [];
634
- const hasQueryParams = getOperationParameters(node).query.length > 0;
635
- const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
636
- return [
637
- Url.toObject(node.path, {
638
- type: "path",
639
- stringify: true,
640
- casing
641
- }),
642
- hasQueryParams ? "...(params ? [params] : [])" : null,
643
- hasRequestBody ? "...(data ? [data] : [])" : null
644
- ].filter(Boolean);
645
- };
646
- //#endregion
647
- //#region src/utils.ts
648
- function printType(typeNode) {
649
- if (!typeNode) return "unknown";
650
- if (typeNode.variant === "reference") return typeNode.name;
651
- if (typeNode.variant === "member") return `${typeNode.base}['${typeNode.key}']`;
652
- if (typeNode.variant === "struct") return `{ ${typeNode.properties.map((p) => {
653
- const typeStr = printType(p.type);
654
- const key = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(p.name) ? p.name : JSON.stringify(p.name);
655
- return p.optional ? `${key}?: ${typeStr}` : `${key}: ${typeStr}`;
656
- }).join("; ")} }`;
657
- return "unknown";
658
- }
659
- function wrapWithMaybeRefOrGetter(paramsNode, skip) {
660
- const wrappedParams = paramsNode.params.map((param) => {
661
- if ("kind" in param && param.kind === "ParameterGroup") {
662
- const group = param;
663
- return {
664
- ...group,
665
- properties: group.properties.map((p) => ({
666
- ...p,
667
- type: p.type ? _kubb_core.ast.createParamsType({
668
- variant: "reference",
669
- name: `MaybeRefOrGetter<${printType(p.type)}>`
670
- }) : p.type
671
- }))
672
- };
673
- }
674
- const fp = param;
675
- if (skip?.(fp.name)) return fp;
676
- return {
677
- ...fp,
678
- type: fp.type ? _kubb_core.ast.createParamsType({
679
- variant: "reference",
680
- name: `MaybeRefOrGetter<${printType(fp.type)}>`
681
- }) : fp.type
682
- };
683
- });
684
- return _kubb_core.ast.createFunctionParameters({ params: wrappedParams });
685
- }
686
- //#endregion
687
- //#region src/components/QueryKey.tsx
688
- const declarationPrinter$5 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
689
- function buildQueryKeyParamsNode(node, options) {
690
- return wrapWithMaybeRefOrGetter(buildQueryKeyParams(node, options));
691
- }
692
- function QueryKey({ name, node, tsResolver, paramsCasing, pathParamsType, typeName, transformer }) {
693
- const baseParamsNode = buildQueryKeyParamsNode(node, {
694
- pathParamsType,
695
- paramsCasing,
696
- resolver: tsResolver
697
- });
698
- const paramsNode = markParamsOptional(baseParamsNode, getEnabledParamNames(baseParamsNode));
699
- const paramsSignature = declarationPrinter$5.print(paramsNode) ?? "";
700
- const keys = (transformer ?? queryKeyTransformer)({
701
- node,
702
- casing: paramsCasing
703
- });
704
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
705
- name,
706
- isExportable: true,
707
- isIndexable: true,
708
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
709
- name,
710
- export: true,
711
- params: paramsSignature,
712
- singleLine: true,
713
- children: `[${keys.join(", ")}] as const`
714
- })
715
- }), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
716
- name: typeName,
717
- isExportable: true,
718
- isIndexable: true,
719
- isTypeOnly: true,
720
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
721
- name: typeName,
722
- export: true,
723
- children: `ReturnType<typeof ${name}>`
724
- })
725
- })] });
726
- }
727
- //#endregion
728
- //#region src/components/QueryOptions.tsx
729
- const declarationPrinter$4 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
730
- const callPrinter$4 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
731
- function getQueryOptionsParams(node, options) {
732
- return wrapWithMaybeRefOrGetter(buildQueryOptionsParams(node, options), (name) => name === "config");
733
- }
734
- function QueryOptions({ name, clientName, dataReturnType, node, tsResolver, paramsCasing, paramsType, pathParamsType, queryKeyName }) {
735
- const successNames = resolveSuccessNames(node, tsResolver);
736
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
737
- const errorNames = resolveErrorNames(node, tsResolver);
738
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
739
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
740
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
741
- pathParamsType,
742
- paramsCasing,
743
- resolver: tsResolver
744
- });
745
- const queryKeyParamsCall = callPrinter$4.print(queryKeyParamsNode) ?? "";
746
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
747
- const enabledText = enabledNames.length ? `enabled: () => ${enabledNames.map((n) => `!!toValue(${n})`).join(" && ")},` : "";
748
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
749
- paramsType,
750
- paramsCasing,
751
- pathParamsType,
752
- resolver: tsResolver
753
- }), enabledNames);
754
- const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
755
- const clientCallStr = (callPrinter$4.print(paramsNode) ?? "").replace(/\bconfig\b(?=[^,]*$)/, "{ ...config, signal: config.signal ?? signal }");
756
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
757
- name,
758
- isExportable: true,
759
- isIndexable: true,
760
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
761
- name,
762
- export: true,
763
- params: paramsSignature,
764
- children: `
765
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
766
- return queryOptions<${TData}, ${TError}, ${TData}>({${enabledText ? `\n ${enabledText}` : ""}
767
- queryKey,
768
- queryFn: async ({ signal }) => {
769
- return ${clientName}(${addToValueCalls$1(clientCallStr, enabledNames)})
770
- },
771
- })
772
- `
773
- })
774
- });
775
- }
776
- /**
777
- * Wraps parameter names with `toValue()` in the client call string,
778
- * except for 'config'-related params (which are already plain objects).
779
- *
780
- * Handles both inline params (`petId, config`) and object shorthand
781
- * params (`{ petId }, config`) by expanding to `{ petId: toValue(petId) }`.
782
- */
783
- function addToValueCalls$1(callStr, enabledNames = []) {
784
- const optional = new Set(enabledNames);
785
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
786
- if (inner.includes(":") || inner.includes("...")) return match;
787
- return `{ ${inner.split(",").map((k) => k.trim()).filter(Boolean).map((k) => `${k}: toValue(${optional.has(k) ? `${k}!` : k})`).join(", ")} }`;
788
- });
789
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => {
790
- if (name === "config" || name === "signal" || name === "undefined") return match;
791
- if (match.includes("toValue(")) return match;
792
- return `toValue(${optional.has(name) ? `${name}!` : name})`;
793
- });
794
- return result;
795
- }
796
- __name(addToValueCalls$1, "addToValueCalls");
797
- //#endregion
798
- //#region src/components/InfiniteQuery.tsx
799
- const declarationPrinter$3 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
800
- const callPrinter$3 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
801
- function buildInfiniteQueryParamsNode(node, options) {
802
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
803
- const successNames = resolveSuccessNames(node, resolver);
804
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
805
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
806
- const errorNames = resolveErrorNames(node, resolver);
807
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
808
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
809
- const optionsParam = _kubb_core.ast.createFunctionParameter({
810
- name: "options",
811
- type: _kubb_core.ast.createParamsType({
812
- variant: "reference",
813
- name: `{
814
- query?: Partial<UseInfiniteQueryOptions<${[
815
- TData,
816
- TError,
817
- "TQueryData",
818
- "TQueryKey",
819
- "TQueryData"
820
- ].join(", ")}>> & { client?: QueryClient },
821
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"}
822
- }`
823
- }),
824
- default: "{}"
825
- });
826
- return wrapWithMaybeRefOrGetter(_kubb_core.ast.createOperationParams(node, {
827
- paramsType,
828
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
829
- paramsCasing,
830
- resolver,
831
- extraParams: [optionsParam]
832
- }), (name) => name === "options");
833
- }
834
- function InfiniteQuery({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
835
- const successNames = resolveSuccessNames(node, tsResolver);
836
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
837
- const errorNames = resolveErrorNames(node, tsResolver);
838
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
839
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
840
- const returnType = `UseInfiniteQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
841
- const generics = [
842
- `TData = InfiniteData<${TData}>`,
843
- `TQueryData = ${TData}`,
844
- `TQueryKey extends QueryKey = ${queryKeyTypeName}`
845
- ];
846
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
847
- pathParamsType,
848
- paramsCasing,
849
- resolver: tsResolver
850
- });
851
- const queryKeyParamsCall = callPrinter$3.print(queryKeyParamsNode) ?? "";
852
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
853
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
854
- paramsType,
855
- paramsCasing,
856
- pathParamsType,
857
- resolver: tsResolver
858
- });
859
- const queryOptionsParamsCall = callPrinter$3.print(queryOptionsParamsNode) ?? "";
860
- const paramsNode = markParamsOptional(buildInfiniteQueryParamsNode(node, {
861
- paramsType,
862
- paramsCasing,
863
- pathParamsType,
864
- dataReturnType,
865
- resolver: tsResolver
866
- }), enabledNames);
867
- const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
868
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
869
- name,
870
- isExportable: true,
871
- isIndexable: true,
872
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
873
- name,
874
- export: true,
875
- generics: generics.join(", "),
876
- params: paramsSignature,
877
- JSDoc: { comments: buildOperationComments(node) },
878
- children: `
879
- const { query: queryConfig = {}, client: config = {} } = options ?? {}
880
- const { client: queryClient, ...resolvedOptions } = queryConfig
881
- const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
882
-
883
- const query = useInfiniteQuery({
884
- ...${queryOptionsName}(${queryOptionsParamsCall}),
885
- ...resolvedOptions,
886
- queryKey
887
- } as unknown as UseInfiniteQueryOptions<${TData}, ${TError}, ${TData}, TQueryKey, ${TData}>, toValue(queryClient)) as ${returnType}
888
-
889
- query.queryKey = queryKey as TQueryKey
890
-
891
- return query
892
- `
893
- })
894
- });
895
- }
896
- //#endregion
897
- //#region src/components/InfiniteQueryOptions.tsx
898
- const declarationPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
899
- const callPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
900
- function InfiniteQueryOptions({ name, clientName, initialPageParam, cursorParam, nextParam, previousParam, node, tsResolver, paramsCasing, paramsType, dataReturnType, pathParamsType, queryParam, queryKeyName }) {
901
- const successNames = resolveSuccessNames(node, tsResolver);
902
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
903
- const queryFnDataType = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
904
- const errorNames = resolveErrorNames(node, tsResolver);
905
- const errorType = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
906
- const isInitialPageParamDefined = initialPageParam !== void 0 && initialPageParam !== null;
907
- const fallbackPageParamType = typeof initialPageParam === "number" ? "number" : typeof initialPageParam === "string" ? initialPageParam.includes(" as ") ? (() => {
908
- const parts = initialPageParam.split(" as ");
909
- return parts[parts.length - 1] ?? "unknown";
910
- })() : "string" : typeof initialPageParam === "boolean" ? "boolean" : "unknown";
911
- const rawQueryParams = getOperationParameters(node).query;
912
- const queryParamsTypeName = rawQueryParams.length > 0 ? (() => {
913
- const groupName = tsResolver.resolveQueryParamsName(node, rawQueryParams[0]);
914
- return groupName !== tsResolver.resolveParamName(node, rawQueryParams[0]) ? groupName : null;
915
- })() : null;
916
- const queryParamType = queryParam && queryParamsTypeName ? `${queryParamsTypeName}['${queryParam}']` : null;
917
- const pageParamType = queryParamType ? isInitialPageParamDefined ? `NonNullable<${queryParamType}>` : queryParamType : fallbackPageParamType;
918
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
919
- pathParamsType,
920
- paramsCasing,
921
- resolver: tsResolver
922
- });
923
- const queryKeyParamsCall = callPrinter$2.print(queryKeyParamsNode) ?? "";
924
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
925
- const enabledText = enabledNames.length ? `enabled: () => ${enabledNames.map((n) => `!!toValue(${n})`).join(" && ")},` : "";
926
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
927
- paramsType,
928
- paramsCasing,
929
- pathParamsType,
930
- resolver: tsResolver
931
- }), enabledNames);
932
- const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
933
- const clientCallStr = (callPrinter$2.print(paramsNode) ?? "").replace(/\bconfig\b(?=[^,]*$)/, "{ ...config, signal: config.signal ?? signal }");
934
- const hasNewParams = nextParam != null || previousParam != null;
935
- const [getNextPageParamExpr, getPreviousPageParamExpr] = (() => {
936
- if (hasNewParams) {
937
- const nextAccessor = nextParam ? (0, _kubb_ast_utils.getNestedAccessor)(nextParam, "lastPage") : null;
938
- const prevAccessor = previousParam ? (0, _kubb_ast_utils.getNestedAccessor)(previousParam, "firstPage") : null;
939
- return [nextAccessor ? `getNextPageParam: (lastPage) => ${nextAccessor}` : null, prevAccessor ? `getPreviousPageParam: (firstPage) => ${prevAccessor}` : null];
940
- }
941
- if (cursorParam) return [`getNextPageParam: (lastPage) => lastPage['${cursorParam}']`, `getPreviousPageParam: (firstPage) => firstPage['${cursorParam}']`];
942
- return [dataReturnType === "full" ? "getNextPageParam: (lastPage, _allPages, lastPageParam) => Array.isArray(lastPage.data) && lastPage.data.length === 0 ? undefined : lastPageParam + 1" : "getNextPageParam: (lastPage, _allPages, lastPageParam) => Array.isArray(lastPage) && lastPage.length === 0 ? undefined : lastPageParam + 1", "getPreviousPageParam: (_firstPage, _allPages, firstPageParam) => firstPageParam <= 1 ? undefined : firstPageParam - 1"];
943
- })();
944
- const queryOptionsArr = [
945
- `initialPageParam: ${typeof initialPageParam === "string" ? JSON.stringify(initialPageParam) : initialPageParam}`,
946
- getNextPageParamExpr,
947
- getPreviousPageParamExpr
948
- ].filter(Boolean);
949
- const infiniteOverrideParams = queryParam && queryParamsTypeName ? `params = {
950
- ...(params ?? {}),
951
- ['${queryParam}']: pageParam as unknown as ${queryParamsTypeName}['${queryParam}'],
952
- } as ${queryParamsTypeName}` : "";
953
- if (infiniteOverrideParams) return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
954
- name,
955
- isExportable: true,
956
- isIndexable: true,
957
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
958
- name,
959
- export: true,
960
- params: paramsSignature,
961
- children: `
962
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
963
- return infiniteQueryOptions<${queryFnDataType}, ${errorType}, InfiniteData<${queryFnDataType}>, QueryKey, ${pageParamType}>({${enabledText ? `\n ${enabledText}` : ""}
964
- queryKey,
965
- queryFn: async ({ signal, pageParam }) => {
966
- ${infiniteOverrideParams}
967
- return ${clientName}(${addToValueCalls(clientCallStr, enabledNames)})
968
- },
969
- ${queryOptionsArr.join(",\n ")}
970
- })
971
- `
972
- })
973
- });
974
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
975
- name,
976
- isExportable: true,
977
- isIndexable: true,
978
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
979
- name,
980
- export: true,
981
- params: paramsSignature,
982
- children: `
983
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
984
- return infiniteQueryOptions<${queryFnDataType}, ${errorType}, InfiniteData<${queryFnDataType}>, QueryKey, ${pageParamType}>({${enabledText ? `\n ${enabledText}` : ""}
985
- queryKey,
986
- queryFn: async ({ signal }) => {
987
- return ${clientName}(${addToValueCalls(clientCallStr, enabledNames)})
988
- },
989
- ${queryOptionsArr.join(",\n ")}
990
- })
991
- `
992
- })
993
- });
994
- }
995
- function addToValueCalls(callStr, enabledNames = []) {
996
- const optional = new Set(enabledNames);
997
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
998
- if (inner.includes(":") || inner.includes("...")) return match;
999
- return `{ ${inner.split(",").map((k) => k.trim()).filter(Boolean).map((k) => `${k}: toValue(${optional.has(k) ? `${k}!` : k})`).join(", ")} }`;
1000
- });
1001
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => {
1002
- if (name === "config" || name === "signal" || name === "undefined") return match;
1003
- if (match.includes("toValue(")) return match;
1004
- return `toValue(${optional.has(name) ? `${name}!` : name})`;
1005
- });
1006
- return result;
1007
- }
1008
- //#endregion
1009
- //#region src/components/Mutation.tsx
1010
- const declarationPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
1011
- const callPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
1012
- const keysPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "keys" });
1013
- function createMutationArgParams(node, options) {
1014
- return _kubb_core.ast.createOperationParams(node, {
1015
- paramsType: "inline",
1016
- pathParamsType: "inline",
1017
- paramsCasing: options.paramsCasing,
1018
- resolver: options.resolver
1019
- });
1020
- }
1021
- function buildMutationParamsNode(node, options) {
1022
- const { paramsCasing, dataReturnType, resolver } = options;
1023
- const successNames = resolveSuccessNames(node, resolver);
1024
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
1025
- const errorNames = resolveErrorNames(node, resolver);
1026
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
1027
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1028
- const wrappedParamsNode = wrapWithMaybeRefOrGetter(createMutationArgParams(node, {
1029
- paramsCasing,
1030
- resolver
1031
- }));
1032
- const TRequestWrapped = wrappedParamsNode.params.length > 0 ? declarationPrinter$1.print(wrappedParamsNode) ?? "" : "";
1033
- return _kubb_core.ast.createFunctionParameters({ params: [_kubb_core.ast.createFunctionParameter({
1034
- name: "options",
1035
- type: _kubb_core.ast.createParamsType({
1036
- variant: "reference",
1037
- name: `{
1038
- mutation?: MutationObserverOptions<${[
1039
- TData,
1040
- TError,
1041
- TRequestWrapped ? `{${TRequestWrapped}}` : "undefined",
1042
- "TContext"
1043
- ].join(", ")}> & { client?: QueryClient },
1044
- client?: ${buildRequestConfigType(node, resolver)},
1045
- }`
1046
- }),
1047
- default: "{}"
1048
- })] });
1049
- }
1050
- function Mutation({ name, clientName, paramsCasing, paramsType, pathParamsType, dataReturnType, node, tsResolver, mutationKeyName }) {
1051
- const successNames = resolveSuccessNames(node, tsResolver);
1052
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
1053
- const errorNames = resolveErrorNames(node, tsResolver);
1054
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
1055
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1056
- const mutationArgParamsNode = createMutationArgParams(node, {
1057
- paramsCasing,
1058
- resolver: tsResolver
1059
- });
1060
- const hasMutationParams = mutationArgParamsNode.params.length > 0;
1061
- const TRequest = hasMutationParams ? declarationPrinter$1.print(mutationArgParamsNode) ?? "" : "";
1062
- const argKeysStr = hasMutationParams ? keysPrinter.print(mutationArgParamsNode) ?? "" : "";
1063
- const generics = [
1064
- TData,
1065
- TError,
1066
- TRequest ? `{${TRequest}}` : "undefined",
1067
- "TContext"
1068
- ].join(", ");
1069
- const mutationKeyParamsNode = _kubb_core.ast.createFunctionParameters({ params: [] });
1070
- const mutationKeyParamsCall = callPrinter$1.print(mutationKeyParamsNode) ?? "";
1071
- const clientCallParamsNode = _kubb_core.ast.createOperationParams(node, {
1072
- paramsType,
1073
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
1074
- paramsCasing,
1075
- resolver: tsResolver,
1076
- extraParams: [_kubb_core.ast.createFunctionParameter({
1077
- name: "config",
1078
- type: _kubb_core.ast.createParamsType({
1079
- variant: "reference",
1080
- name: buildRequestConfigType(node, tsResolver)
1081
- }),
1082
- default: "{}"
1083
- })]
1084
- });
1085
- const clientCallStr = callPrinter$1.print(clientCallParamsNode) ?? "";
1086
- const paramsNode = buildMutationParamsNode(node, {
1087
- paramsCasing,
1088
- dataReturnType,
1089
- resolver: tsResolver
1090
- });
1091
- const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
1092
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
1093
- name,
1094
- isExportable: true,
1095
- isIndexable: true,
1096
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
1097
- name,
1098
- export: true,
1099
- params: paramsSignature,
1100
- JSDoc: { comments: buildOperationComments(node) },
1101
- generics: ["TContext"],
1102
- children: `
1103
- const { mutation = {}, client: config = {} } = options ?? {}
1104
- const { client: queryClient, ...mutationOptions } = mutation;
1105
- const mutationKey = mutationOptions?.mutationKey ?? ${mutationKeyName}(${mutationKeyParamsCall})
1106
-
1107
- return useMutation<${generics}>({
1108
- mutationFn: async(${hasMutationParams ? `{ ${argKeysStr} }` : ""}) => {
1109
- return ${clientName}(${clientCallStr})
1110
- },
1111
- mutationKey,
1112
- ...mutationOptions
1113
- }, queryClient)
1114
- `
1115
- })
1116
- });
1117
- }
1118
- //#endregion
1119
- //#region src/components/Query.tsx
1120
- const declarationPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
1121
- const callPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
1122
- function buildQueryParamsNode(node, options) {
1123
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
1124
- const successNames = resolveSuccessNames(node, resolver);
1125
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
1126
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
1127
- const errorNames = resolveErrorNames(node, resolver);
1128
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
1129
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1130
- const optionsParam = _kubb_core.ast.createFunctionParameter({
1131
- name: "options",
1132
- type: _kubb_core.ast.createParamsType({
1133
- variant: "reference",
1134
- name: `{
1135
- query?: Partial<UseQueryOptions<${[
1136
- TData,
1137
- TError,
1138
- "TData",
1139
- "TQueryData",
1140
- "TQueryKey"
1141
- ].join(", ")}>> & { client?: QueryClient },
1142
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"}
1143
- }`
1144
- }),
1145
- default: "{}"
1146
- });
1147
- return wrapWithMaybeRefOrGetter(_kubb_core.ast.createOperationParams(node, {
1148
- paramsType,
1149
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
1150
- paramsCasing,
1151
- resolver,
1152
- extraParams: [optionsParam]
1153
- }), (name) => name === "options");
1154
- }
1155
- function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
1156
- const successNames = resolveSuccessNames(node, tsResolver);
1157
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
1158
- const errorNames = resolveErrorNames(node, tsResolver);
1159
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
1160
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1161
- const returnType = `UseQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
1162
- const generics = [
1163
- `TData = ${TData}`,
1164
- `TQueryData = ${TData}`,
1165
- `TQueryKey extends QueryKey = ${queryKeyTypeName}`
1166
- ];
1167
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
1168
- pathParamsType,
1169
- paramsCasing,
1170
- resolver: tsResolver
1171
- });
1172
- const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
1173
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
1174
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
1175
- paramsType,
1176
- paramsCasing,
1177
- pathParamsType,
1178
- resolver: tsResolver
1179
- });
1180
- const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
1181
- const paramsNode = markParamsOptional(buildQueryParamsNode(node, {
1182
- paramsType,
1183
- paramsCasing,
1184
- pathParamsType,
1185
- dataReturnType,
1186
- resolver: tsResolver
1187
- }), enabledNames);
1188
- const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
1189
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
1190
- name,
1191
- isExportable: true,
1192
- isIndexable: true,
1193
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
1194
- name,
1195
- export: true,
1196
- generics: generics.join(", "),
1197
- params: paramsSignature,
1198
- JSDoc: { comments: buildOperationComments(node) },
1199
- children: `
1200
- const { query: queryConfig = {}, client: config = {} } = options ?? {}
1201
- const { client: queryClient, ...resolvedOptions } = queryConfig
1202
- const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
1203
-
1204
- const query = useQuery({
1205
- ...${queryOptionsName}(${queryOptionsParamsCall}),
1206
- ...resolvedOptions,
1207
- queryKey
1208
- } as unknown as UseQueryOptions<${TData}, ${TError}, TData, ${TData}, TQueryKey>, toValue(queryClient)) as ${returnType}
1209
-
1210
- query.queryKey = queryKey as TQueryKey
1211
-
1212
- return query
1213
- `
1214
- })
1215
- });
1216
- }
1217
- //#endregion
1218
- Object.defineProperty(exports, "InfiniteQuery", {
1219
- enumerable: true,
1220
- get: function() {
1221
- return InfiniteQuery;
1222
- }
1223
- });
1224
- Object.defineProperty(exports, "InfiniteQueryOptions", {
1225
- enumerable: true,
1226
- get: function() {
1227
- return InfiniteQueryOptions;
1228
- }
1229
- });
1230
- Object.defineProperty(exports, "Mutation", {
1231
- enumerable: true,
1232
- get: function() {
1233
- return Mutation;
1234
- }
1235
- });
1236
- Object.defineProperty(exports, "MutationKey", {
1237
- enumerable: true,
1238
- get: function() {
1239
- return MutationKey;
1240
- }
1241
- });
1242
- Object.defineProperty(exports, "Query", {
1243
- enumerable: true,
1244
- get: function() {
1245
- return Query;
1246
- }
1247
- });
1248
- Object.defineProperty(exports, "QueryKey", {
1249
- enumerable: true,
1250
- get: function() {
1251
- return QueryKey;
1252
- }
1253
- });
1254
- Object.defineProperty(exports, "QueryOptions", {
1255
- enumerable: true,
1256
- get: function() {
1257
- return QueryOptions;
1258
- }
1259
- });
1260
- Object.defineProperty(exports, "__name", {
1261
- enumerable: true,
1262
- get: function() {
1263
- return __name;
1264
- }
1265
- });
1266
- Object.defineProperty(exports, "__toESM", {
1267
- enumerable: true,
1268
- get: function() {
1269
- return __toESM;
1270
- }
1271
- });
1272
- Object.defineProperty(exports, "camelCase", {
1273
- enumerable: true,
1274
- get: function() {
1275
- return camelCase;
1276
- }
1277
- });
1278
- Object.defineProperty(exports, "getOperationParameters", {
1279
- enumerable: true,
1280
- get: function() {
1281
- return getOperationParameters;
1282
- }
1283
- });
1284
- Object.defineProperty(exports, "mutationKeyTransformer", {
1285
- enumerable: true,
1286
- get: function() {
1287
- return mutationKeyTransformer;
1288
- }
1289
- });
1290
- Object.defineProperty(exports, "operationFileEntry", {
1291
- enumerable: true,
1292
- get: function() {
1293
- return operationFileEntry;
1294
- }
1295
- });
1296
- Object.defineProperty(exports, "queryKeyTransformer", {
1297
- enumerable: true,
1298
- get: function() {
1299
- return queryKeyTransformer;
1300
- }
1301
- });
1302
- Object.defineProperty(exports, "resolveOperationTypeNames", {
1303
- enumerable: true,
1304
- get: function() {
1305
- return resolveOperationTypeNames;
1306
- }
1307
- });
1308
- Object.defineProperty(exports, "resolveZodSchemaNames", {
1309
- enumerable: true,
1310
- get: function() {
1311
- return resolveZodSchemaNames;
1312
- }
1313
- });
1314
-
1315
- //# sourceMappingURL=components-D3xIZ9FA.cjs.map