@kubb/plugin-react-query 5.0.0-beta.64 → 5.0.0-beta.74

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