@kubb/plugin-swr 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,947 +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_ast_utils = require("@kubb/ast/utils");
29
- let _kubb_plugin_ts = require("@kubb/plugin-ts");
30
- let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
31
- let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
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
- function getOperationLink(node, link) {
248
- if (!link) return null;
249
- if (typeof link === "function") return link(node) ?? null;
250
- if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
251
- return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
252
- }
253
- function getContentTypeInfo(node) {
254
- const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
255
- const isMultipleContentTypes = contentTypes.length > 1;
256
- return {
257
- contentTypes,
258
- isMultipleContentTypes,
259
- contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
260
- defaultContentType: contentTypes[0] ?? "application/json",
261
- hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
262
- };
263
- }
264
- function buildRequestConfigType(node, resolver) {
265
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
266
- const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
267
- return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
268
- }
269
- function buildOperationComments(node, options = {}) {
270
- const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
271
- const linkComment = getOperationLink(node, link);
272
- const filteredComments = (linkPosition === "beforeDeprecated" ? [
273
- node.description && `@description ${node.description}`,
274
- node.summary && `@summary ${node.summary}`,
275
- linkComment,
276
- node.deprecated && "@deprecated"
277
- ] : [
278
- node.description && `@description ${node.description}`,
279
- node.summary && `@summary ${node.summary}`,
280
- node.deprecated && "@deprecated",
281
- linkComment
282
- ]).filter((comment) => Boolean(comment));
283
- if (!splitLines) return filteredComments;
284
- return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
285
- }
286
- function getOperationParameters(node, options = {}) {
287
- const params = (0, _kubb_ast_utils.caseParams)(node.parameters, options.paramsCasing);
288
- return {
289
- path: params.filter((param) => param.in === "path"),
290
- query: params.filter((param) => param.in === "query"),
291
- header: params.filter((param) => param.in === "header"),
292
- cookie: params.filter((param) => param.in === "cookie")
293
- };
294
- }
295
- function getStatusCodeNumber(statusCode) {
296
- const code = Number(statusCode);
297
- return Number.isNaN(code) ? null : code;
298
- }
299
- function isErrorStatusCode(statusCode) {
300
- const code = getStatusCodeNumber(statusCode);
301
- return code !== null && code >= 400;
302
- }
303
- function resolveErrorNames(node, resolver) {
304
- return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
305
- }
306
- function resolveStatusCodeNames(node, resolver) {
307
- return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
308
- }
309
- /**
310
- * Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
311
- * Each member is `{ status: N; data: StatusNType; statusText: string }`.
312
- */
313
- function buildStatusUnionType(node, resolver) {
314
- const members = node.responses.map((r) => {
315
- const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
316
- const statusCode = Number.parseInt(r.statusCode, 10);
317
- return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
318
- });
319
- if (members.length === 1) return members[0];
320
- return `(${members.join(" | ")})`;
321
- }
322
- const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
323
- function resolveOperationTypeNames(node, resolver, options = {}) {
324
- const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
325
- let byResolver = typeNamesByResolver.get(resolver);
326
- if (byResolver) {
327
- const cached = byResolver.get(cacheKey);
328
- if (cached) return cached;
329
- } else {
330
- byResolver = /* @__PURE__ */ new Map();
331
- typeNamesByResolver.set(resolver, byResolver);
332
- }
333
- const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
334
- const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
335
- const exclude = new Set(options.exclude ?? []);
336
- const paramNames = [
337
- ...path.map((param) => resolver.resolvePathParamsName(node, param)),
338
- ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
339
- ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
340
- ];
341
- const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
342
- const result = (options.order === "body-response-first" ? [
343
- ...bodyAndResponseNames,
344
- ...paramNames,
345
- ...responseStatusNames
346
- ] : [
347
- ...paramNames,
348
- ...bodyAndResponseNames,
349
- ...responseStatusNames
350
- ]).filter((name) => Boolean(name) && !exclude.has(name));
351
- byResolver.set(cacheKey, result);
352
- return result;
353
- }
354
- //#endregion
355
- //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
356
- const declarationPrinter$4 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
357
- const mutationKeyTransformer = ({ node }) => {
358
- if (!node.path) return [];
359
- return [`{ url: '${Url.toPath(node.path)}' }`];
360
- };
361
- function MutationKey$1({ name, paramsCasing, node, transformer }) {
362
- const paramsNode = _kubb_core.ast.factory.createFunctionParameters({ params: [] });
363
- const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
364
- const keys = (transformer ?? mutationKeyTransformer)({
365
- node,
366
- casing: paramsCasing
367
- });
368
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
369
- name,
370
- isExportable: true,
371
- isIndexable: true,
372
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
373
- name,
374
- export: true,
375
- params: paramsSignature,
376
- singleLine: true,
377
- children: `[${keys.join(", ")}] as const`
378
- })
379
- });
380
- }
381
- __name(MutationKey$1, "MutationKey");
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 (0, _kubb_ast_utils.createOperationParams)(node, {
402
- paramsType,
403
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
404
- paramsCasing,
405
- resolver,
406
- extraParams: [_kubb_core.ast.factory.createFunctionParameter({
407
- name: "config",
408
- type: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }",
409
- default: "{}"
410
- })]
411
- });
412
- }
413
- /**
414
- * Returns `'zod'` when response-direction parsing is enabled.
415
- * The string shorthand `'zod'` also enables response parsing.
416
- */
417
- function resolveResponseParser(parser) {
418
- if (!parser) return null;
419
- if (parser === "zod") return "zod";
420
- return parser.response ?? null;
421
- }
422
- /**
423
- * Returns `'zod'` when request body parsing is enabled.
424
- * The string shorthand `'zod'` also enables request body parsing (existing behavior).
425
- */
426
- function resolveRequestParser(parser) {
427
- if (!parser) return null;
428
- if (parser === "zod") return "zod";
429
- return parser.request ?? null;
430
- }
431
- /**
432
- * Returns `'zod'` when query-params parsing is enabled.
433
- * Only the object form `{ request: 'zod' }` enables this. `parser: 'zod'` does not.
434
- */
435
- function resolveQueryParamsParser(parser) {
436
- if (!parser || parser === "zod") return null;
437
- return parser.request ?? null;
438
- }
439
- /**
440
- * Collects the Zod schema import names for an operation based on the active parser directions.
441
- *
442
- * - `parser: 'zod'`: response and request body names (backward-compatible behavior).
443
- * - `parser: { request: 'zod' }`: request body and query params names.
444
- * - `parser: { response: 'zod' }`: response name only.
445
- * - `parser: { request: 'zod', response: 'zod' }`: all three.
446
- *
447
- * Returns an empty array when no resolver is provided or `parser` is falsy.
448
- */
449
- function resolveZodSchemaNames(node, zodResolver, parser) {
450
- if (!zodResolver || !parser) return [];
451
- const { query: queryParams } = getOperationParameters(node);
452
- return [
453
- resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
454
- resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
455
- resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
456
- ].filter((n) => Boolean(n));
457
- }
458
- /**
459
- * Build QueryKey params: pathParams + data + queryParams (NO headers, NO config).
460
- */
461
- function buildQueryKeyParams(node, options) {
462
- const { pathParamsType, paramsCasing, resolver } = options;
463
- const casedParams = (0, _kubb_ast_utils.caseParams)(node.parameters, paramsCasing);
464
- const pathParams = casedParams.filter((p) => p.in === "path");
465
- const queryParams = casedParams.filter((p) => p.in === "query");
466
- const queryGroupType = (0, _kubb_ast_utils.resolveGroupType)({
467
- node,
468
- params: queryParams,
469
- group: "query",
470
- resolver
471
- });
472
- const bodyType = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
473
- const bodyRequired = node.requestBody?.required ?? false;
474
- const params = [];
475
- if (pathParams.length) {
476
- const pathChildren = pathParams.map((p) => ({
477
- name: p.name,
478
- type: (0, _kubb_ast_utils.resolveParamType)({
479
- node,
480
- param: p,
481
- resolver
482
- }),
483
- optional: !p.required
484
- }));
485
- if (pathParamsType === "object") params.push(_kubb_core.ast.factory.createFunctionParameter({
486
- properties: pathChildren,
487
- default: pathChildren.every((c) => c.optional) ? "{}" : void 0
488
- }));
489
- else params.push(...pathChildren.map((child) => _kubb_core.ast.factory.createFunctionParameter(child)));
490
- }
491
- if (bodyType) params.push(_kubb_core.ast.factory.createFunctionParameter({
492
- name: "data",
493
- type: bodyType,
494
- optional: !bodyRequired
495
- }));
496
- params.push(...(0, _kubb_ast_utils.buildGroupParam)({
497
- name: "params",
498
- node,
499
- params: queryParams,
500
- groupType: queryGroupType,
501
- resolver,
502
- wrapType: (type) => type
503
- }));
504
- return _kubb_core.ast.factory.createFunctionParameters({ params });
505
- }
506
- /**
507
- * Collect the names of the required params (no default) that drive the `enabled`
508
- * guard. These are exactly the params that should be made optional in the
509
- * generated signatures so callers can pass `undefined` to reach the disabled state.
510
- */
511
- function getEnabledParamNames(paramsNode) {
512
- const required = [];
513
- for (const param of paramsNode.params) {
514
- const members = groupMembers(param);
515
- if (members) {
516
- for (const member of members) if (!member.optional) required.push(member.name);
517
- } else if (typeof param.name === "string" && !param.optional && param.default === void 0) required.push(param.name);
518
- }
519
- return required;
520
- }
521
- /**
522
- * Return a copy of `paramsNode` with the named params marked optional.
523
- *
524
- * Used to align signatures with the `enabled` guard: the guard already disables
525
- * the query while a param is falsy, so the param should accept `undefined`. The
526
- * change is type-only — the `queryFn` keeps calling the client with a non-null
527
- * assertion (see `injectNonNullAssertions`), so the emitted runtime is unchanged.
528
- */
529
- function markParamsOptional(paramsNode, names) {
530
- if (names.length === 0) return paramsNode;
531
- const nameSet = new Set(names);
532
- const params = paramsNode.params.map((param) => {
533
- const members = groupMembers(param);
534
- if (members) {
535
- const next = members.map((member) => nameSet.has(member.name) ? {
536
- ...member,
537
- optional: true
538
- } : member);
539
- return {
540
- ...param,
541
- type: _kubb_core.ast.factory.createTypeLiteral({ members: next })
542
- };
543
- }
544
- return typeof param.name === "string" && nameSet.has(param.name) ? _kubb_core.ast.factory.createFunctionParameter({
545
- name: param.name,
546
- type: param.type,
547
- rest: param.rest,
548
- optional: true
549
- }) : param;
550
- });
551
- return _kubb_core.ast.factory.createFunctionParameters({ params });
552
- }
553
- /**
554
- * Add a non-null assertion (`!`) to the named params inside a printed client-call
555
- * string. Bridges the type gap created by `markParamsOptional` while keeping the
556
- * runtime identical (the `!` is erased at compile time).
557
- *
558
- * Handles destructured shorthand groups (`{ petId }` → `{ petId: petId! }`) and
559
- * standalone identifiers (`params` → `params!`).
560
- */
561
- function injectNonNullAssertions(callStr, names) {
562
- if (names.length === 0) return callStr;
563
- const nameSet = new Set(names);
564
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
565
- if (inner.includes(":") || inner.includes("...")) return match;
566
- const keys = inner.split(",").map((k) => k.trim()).filter(Boolean);
567
- if (!keys.some((k) => nameSet.has(k))) return match;
568
- return `{ ${keys.map((k) => nameSet.has(k) ? `${k}: ${k}!` : k).join(", ")} }`;
569
- });
570
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => nameSet.has(name) ? `${name}!` : match);
571
- return result;
572
- }
573
- //#endregion
574
- //#region ../../internals/tanstack-query/src/components/QueryKey.tsx
575
- const declarationPrinter$3 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
576
- const queryKeyTransformer = ({ node, casing }) => {
577
- if (!node.path) return [];
578
- const hasQueryParams = getOperationParameters(node).query.length > 0;
579
- const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
580
- return [
581
- Url.toObject(node.path, {
582
- type: "path",
583
- stringify: true,
584
- casing
585
- }),
586
- hasQueryParams ? "...(params ? [params] : [])" : null,
587
- hasRequestBody ? "...(data ? [data] : [])" : null
588
- ].filter(Boolean);
589
- };
590
- function QueryKey({ name, node, tsResolver, paramsCasing, pathParamsType, typeName, transformer }) {
591
- const baseParamsNode = buildQueryKeyParams(node, {
592
- pathParamsType,
593
- paramsCasing,
594
- resolver: tsResolver
595
- });
596
- const paramsNode = markParamsOptional(baseParamsNode, getEnabledParamNames(baseParamsNode));
597
- const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
598
- const keys = (transformer ?? queryKeyTransformer)({
599
- node,
600
- casing: paramsCasing
601
- });
602
- 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, {
603
- name,
604
- isExportable: true,
605
- isIndexable: true,
606
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
607
- name,
608
- export: true,
609
- params: paramsSignature,
610
- singleLine: true,
611
- children: `[${keys.join(", ")}] as const`
612
- })
613
- }), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
614
- name: typeName,
615
- isTypeOnly: true,
616
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
617
- name: typeName,
618
- children: `ReturnType<typeof ${name}>`
619
- })
620
- })] });
621
- }
622
- //#endregion
623
- //#region src/components/Mutation.tsx
624
- const declarationPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
625
- const callPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
626
- const keysPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
627
- function createMutationArgParams(node, options) {
628
- return (0, _kubb_ast_utils.createOperationParams)(node, {
629
- paramsType: "inline",
630
- pathParamsType: "inline",
631
- paramsCasing: options.paramsCasing,
632
- resolver: options.resolver
633
- });
634
- }
635
- function buildMutationParamsNode(node, options) {
636
- const { dataReturnType, mutationKeyTypeName, mutationArgTypeName, resolver } = options;
637
- const responseName = resolver.resolveResponseName(node);
638
- const errorNames = resolveErrorNames(node, resolver);
639
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
640
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
641
- return _kubb_core.ast.factory.createFunctionParameters({ params: [_kubb_core.ast.factory.createFunctionParameter({
642
- name: "options",
643
- type: `{
644
- mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${mutationArgTypeName}> & { throwOnError?: boolean },
645
- client?: ${buildRequestConfigType(node, resolver)},
646
- shouldFetch?: boolean,
647
- }`,
648
- default: "{}"
649
- })] });
650
- }
651
- function Mutation({ name, clientName, mutationKeyName, mutationKeyTypeName, mutationArgTypeName, paramsCasing, paramsType, pathParamsType, dataReturnType, node, tsResolver }) {
652
- const responseName = tsResolver.resolveResponseName(node);
653
- const errorNames = resolveErrorNames(node, tsResolver);
654
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
655
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
656
- const mutationArgParamsNode = createMutationArgParams(node, {
657
- paramsCasing,
658
- resolver: tsResolver
659
- });
660
- const hasMutationParams = mutationArgParamsNode.params.length > 0;
661
- const argTypeBody = hasMutationParams ? declarationPrinter$2.print(mutationArgParamsNode) ?? "" : "";
662
- const argKeysStr = hasMutationParams ? keysPrinter.print(mutationArgParamsNode) ?? "" : "";
663
- const generics = [
664
- TData,
665
- TError,
666
- `${mutationKeyTypeName} | null`,
667
- mutationArgTypeName
668
- ];
669
- const paramsNode = buildMutationParamsNode(node, {
670
- paramsCasing,
671
- dataReturnType,
672
- mutationKeyTypeName,
673
- mutationArgTypeName,
674
- resolver: tsResolver
675
- });
676
- const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
677
- const clientCallParamsNode = (0, _kubb_ast_utils.createOperationParams)(node, {
678
- paramsType,
679
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
680
- paramsCasing,
681
- resolver: tsResolver,
682
- extraParams: [_kubb_core.ast.factory.createFunctionParameter({
683
- name: "config",
684
- type: buildRequestConfigType(node, tsResolver),
685
- default: "{}"
686
- })]
687
- });
688
- const clientCallStr = callPrinter$2.print(clientCallParamsNode) ?? "";
689
- 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, {
690
- name: mutationArgTypeName,
691
- isExportable: true,
692
- isIndexable: true,
693
- isTypeOnly: true,
694
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
695
- name: mutationArgTypeName,
696
- export: true,
697
- children: hasMutationParams ? `{ ${argTypeBody} }` : "never"
698
- })
699
- }), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
700
- name,
701
- isExportable: true,
702
- isIndexable: true,
703
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
704
- name,
705
- export: true,
706
- params: paramsSignature,
707
- JSDoc: { comments: buildOperationComments(node) },
708
- children: `
709
- const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
710
- const mutationKey = ${mutationKeyName}()
711
-
712
- return useSWRMutation<${generics.join(", ")}>(
713
- shouldFetch ? mutationKey : null,
714
- async (_url${hasMutationParams ? `, { arg: { ${argKeysStr} } }` : ""}) => {
715
- return ${clientName}(${clientCallStr})
716
- },
717
- mutationOptions
718
- )
719
- `
720
- })
721
- })] });
722
- }
723
- //#endregion
724
- //#region src/components/MutationKey.tsx
725
- function MutationKey({ name, typeName, node, paramsCasing, pathParamsType, transformer }) {
726
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(MutationKey$1, {
727
- name,
728
- node,
729
- paramsCasing,
730
- pathParamsType,
731
- transformer
732
- }), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
733
- name: typeName,
734
- isExportable: true,
735
- isIndexable: true,
736
- isTypeOnly: true,
737
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
738
- export: true,
739
- name: typeName,
740
- children: `ReturnType<typeof ${name}>`
741
- })
742
- })] });
743
- }
744
- //#endregion
745
- //#region src/components/QueryOptions.tsx
746
- const declarationPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
747
- const callPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
748
- function getQueryOptionsParams(node, options) {
749
- return buildQueryOptionsParams(node, options);
750
- }
751
- function QueryOptions({ name, clientName, node, tsResolver, paramsCasing, paramsType, pathParamsType }) {
752
- const enabledNames = getEnabledParamNames(buildQueryKeyParams(node, {
753
- pathParamsType,
754
- paramsCasing,
755
- resolver: tsResolver
756
- }));
757
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
758
- paramsType,
759
- paramsCasing,
760
- pathParamsType,
761
- resolver: tsResolver
762
- }), enabledNames);
763
- const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
764
- const clientCallStr = injectNonNullAssertions(callPrinter$1.print(paramsNode) ?? "", enabledNames);
765
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
766
- name,
767
- isExportable: true,
768
- isIndexable: true,
769
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
770
- name,
771
- export: true,
772
- params: paramsSignature,
773
- children: `
774
- return {
775
- fetcher: async () => {
776
- return ${clientName}(${clientCallStr})
777
- },
778
- }
779
- `
780
- })
781
- });
782
- }
783
- //#endregion
784
- //#region src/components/Query.tsx
785
- const declarationPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
786
- const callPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
787
- function buildQueryParamsNode(node, options) {
788
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
789
- const responseName = resolver.resolveResponseName(node);
790
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
791
- const errorNames = resolveErrorNames(node, resolver);
792
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
793
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
794
- const optionsParam = _kubb_core.ast.factory.createFunctionParameter({
795
- name: "options",
796
- type: `{
797
- query?: SWRConfiguration<${[TData, TError].join(", ")}>,
798
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"},
799
- shouldFetch?: boolean,
800
- immutable?: boolean
801
- }`,
802
- default: "{}"
803
- });
804
- return (0, _kubb_ast_utils.createOperationParams)(node, {
805
- paramsType,
806
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
807
- paramsCasing,
808
- resolver,
809
- extraParams: [optionsParam]
810
- });
811
- }
812
- function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
813
- const responseName = tsResolver.resolveResponseName(node);
814
- const errorNames = resolveErrorNames(node, tsResolver);
815
- const generics = [
816
- dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver),
817
- `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`,
818
- `${queryKeyTypeName} | null`
819
- ];
820
- const queryKeyParamsNode = buildQueryKeyParams(node, {
821
- pathParamsType,
822
- paramsCasing,
823
- resolver: tsResolver
824
- });
825
- const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
826
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
827
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
828
- paramsType,
829
- paramsCasing,
830
- pathParamsType,
831
- resolver: tsResolver
832
- });
833
- const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
834
- const paramsNode = markParamsOptional(buildQueryParamsNode(node, {
835
- paramsType,
836
- paramsCasing,
837
- pathParamsType,
838
- dataReturnType,
839
- resolver: tsResolver
840
- }), enabledNames);
841
- const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
842
- const shouldFetchExpr = enabledNames.length ? `shouldFetch && !!(${enabledNames.join(" && ")})` : "shouldFetch";
843
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
844
- name,
845
- isExportable: true,
846
- isIndexable: true,
847
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
848
- name,
849
- export: true,
850
- params: paramsSignature,
851
- JSDoc: { comments: buildOperationComments(node) },
852
- children: `
853
- const { query: queryOptions, client: config = {}, shouldFetch = true, immutable } = options ?? {}
854
-
855
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
856
-
857
- return useSWR<${generics.join(", ")}>(
858
- ${shouldFetchExpr} ? queryKey : null,
859
- {
860
- ...${queryOptionsName}(${queryOptionsParamsCall}),
861
- ...(immutable ? {
862
- revalidateIfStale: false,
863
- revalidateOnFocus: false,
864
- revalidateOnReconnect: false
865
- } : { }),
866
- ...queryOptions,
867
- }
868
- )
869
- `
870
- })
871
- });
872
- }
873
- //#endregion
874
- Object.defineProperty(exports, "Mutation", {
875
- enumerable: true,
876
- get: function() {
877
- return Mutation;
878
- }
879
- });
880
- Object.defineProperty(exports, "MutationKey", {
881
- enumerable: true,
882
- get: function() {
883
- return MutationKey;
884
- }
885
- });
886
- Object.defineProperty(exports, "Query", {
887
- enumerable: true,
888
- get: function() {
889
- return Query;
890
- }
891
- });
892
- Object.defineProperty(exports, "QueryKey", {
893
- enumerable: true,
894
- get: function() {
895
- return QueryKey;
896
- }
897
- });
898
- Object.defineProperty(exports, "QueryOptions", {
899
- enumerable: true,
900
- get: function() {
901
- return QueryOptions;
902
- }
903
- });
904
- Object.defineProperty(exports, "__name", {
905
- enumerable: true,
906
- get: function() {
907
- return __name;
908
- }
909
- });
910
- Object.defineProperty(exports, "__toESM", {
911
- enumerable: true,
912
- get: function() {
913
- return __toESM;
914
- }
915
- });
916
- Object.defineProperty(exports, "camelCase", {
917
- enumerable: true,
918
- get: function() {
919
- return camelCase;
920
- }
921
- });
922
- Object.defineProperty(exports, "mutationKeyTransformer", {
923
- enumerable: true,
924
- get: function() {
925
- return mutationKeyTransformer;
926
- }
927
- });
928
- Object.defineProperty(exports, "queryKeyTransformer", {
929
- enumerable: true,
930
- get: function() {
931
- return queryKeyTransformer;
932
- }
933
- });
934
- Object.defineProperty(exports, "resolveOperationTypeNames", {
935
- enumerable: true,
936
- get: function() {
937
- return resolveOperationTypeNames;
938
- }
939
- });
940
- Object.defineProperty(exports, "resolveZodSchemaNames", {
941
- enumerable: true,
942
- get: function() {
943
- return resolveZodSchemaNames;
944
- }
945
- });
946
-
947
- //# sourceMappingURL=components-DxWGjLWg.cjs.map