@kubb/plugin-fetch 5.0.0-beta.100

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1381 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
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_kit = require("kubb/kit");
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path, 1);
30
+ let _kubb_plugin_ts = require("@kubb/plugin-ts");
31
+ let kubb_jsx = require("kubb/jsx");
32
+ let kubb_jsx_jsx_runtime = require("kubb/jsx/jsx-runtime");
33
+ let _kubb_plugin_zod = require("@kubb/plugin-zod");
34
+ let node_url = require("node:url");
35
+ //#region ../../internals/shared/src/params.ts
36
+ /**
37
+ * Drops parameters that share the same name, keeping the first.
38
+ *
39
+ * A malformed spec can declare the same parameter name twice within one `in` location. Both would
40
+ * resolve to the same output property, so emitting both would yield an object type with a duplicate
41
+ * member, which TypeScript rejects. This is a defensive guard against that case, not a casing guard:
42
+ * parameter names flow through unchanged, so no two distinct names ever collide here anymore.
43
+ */
44
+ function dedupeParams(params) {
45
+ const seen = /* @__PURE__ */ new Set();
46
+ return params.filter((param) => {
47
+ if (seen.has(param.name)) return false;
48
+ seen.add(param.name);
49
+ return true;
50
+ });
51
+ }
52
+ //#endregion
53
+ //#region ../../internals/shared/src/operation.ts
54
+ /**
55
+ * Builds the `ResolverFileParams` every operation generator passes to
56
+ * `resolver.file`: a file named `name`, tagged by the operation's first
57
+ * tag (or `'default'`), at the operation's path. Centralizes the entry object
58
+ * that was repeated at dozens of call sites across the client and query plugins.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
63
+ * ```
64
+ */
65
+ function operationFileEntry(node, name, extname = ".ts") {
66
+ return {
67
+ name,
68
+ extname,
69
+ tag: node.tags[0] ?? "default",
70
+ path: node.path
71
+ };
72
+ }
73
+ function getOperationLink(node, link) {
74
+ if (!link) return null;
75
+ if (typeof link === "function") return link(node) ?? null;
76
+ return node.path ? `{@link ${kubb_kit.Url.toPath(node.path)}}` : null;
77
+ }
78
+ /**
79
+ * Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several
80
+ * are present and the union, default, and form-data flags the client uses to pick one.
81
+ */
82
+ function buildContentTypeInfo(contentTypes) {
83
+ const isMultipleContentTypes = contentTypes.length > 1;
84
+ return {
85
+ contentTypes,
86
+ isMultipleContentTypes,
87
+ contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
88
+ defaultContentType: contentTypes[0] ?? "application/json",
89
+ hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
90
+ };
91
+ }
92
+ function getContentTypeInfo(node) {
93
+ return buildContentTypeInfo(node.requestBody?.content?.map((e) => e.contentType) ?? []);
94
+ }
95
+ /**
96
+ * The request-body counterpart for the primary success response: the content types it documents and
97
+ * whether several are present, so the client can let a caller pick which one to accept.
98
+ */
99
+ function getResponseContentTypeInfo(node) {
100
+ return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? []);
101
+ }
102
+ /**
103
+ * Reads the single base content type of an operation's primary success response, lowercased and
104
+ * stripped of any `; charset=...` suffix. Returns `undefined` when the response declares zero or
105
+ * more than one content type, since neither case has a single type to act on.
106
+ */
107
+ function getPrimarySuccessContentType(node) {
108
+ const contentTypes = getPrimarySuccessResponse(node)?.content?.map((entry) => entry.contentType) ?? [];
109
+ if (contentTypes.length !== 1) return void 0;
110
+ return contentTypes[0].split(";")[0].trim().toLowerCase();
111
+ }
112
+ /**
113
+ * Whether an operation streams its primary success response as Server-Sent Events
114
+ * (`text/event-stream`). The client generator uses this to return a typed event stream instead of a
115
+ * one-shot `RequestResult`.
116
+ */
117
+ function isEventStream(node) {
118
+ return getPrimarySuccessContentType(node) === "text/event-stream";
119
+ }
120
+ /**
121
+ * Derives the default `responseType` for an operation from its primary success response.
122
+ *
123
+ * Returns a value only when that response declares a single non-JSON content type. `text/event-stream`
124
+ * and other binary types (`application/octet-stream`, `application/pdf`, `image/*`, `audio/*`,
125
+ * `video/*`) map to a stream or `'blob'`, and other `text/*` maps to `'text'`. Otherwise `undefined`,
126
+ * leaving the runtime client's `Content-Type` auto-detection in charge.
127
+ */
128
+ function getResponseType(node) {
129
+ const baseType = getPrimarySuccessContentType(node);
130
+ if (!baseType) return void 0;
131
+ if (baseType === "application/json" || baseType.endsWith("+json") || baseType === "text/json") return void 0;
132
+ if (baseType === "text/event-stream") return "stream";
133
+ if (baseType.startsWith("text/")) return "text";
134
+ if (baseType === "application/octet-stream" || baseType === "application/pdf" || /^(image|audio|video)\//.test(baseType)) return "blob";
135
+ }
136
+ /**
137
+ * Which of the grouped request options an operation carries.
138
+ */
139
+ function getRequestGroups(node) {
140
+ const { path, query, header } = getOperationParameters(node);
141
+ return {
142
+ path: path.length > 0,
143
+ query: query.length > 0,
144
+ body: Boolean(node.requestBody?.content?.[0]?.schema),
145
+ headers: header.length > 0
146
+ };
147
+ }
148
+ /**
149
+ * Resolves which grouped request options an operation carries together with whether each group
150
+ * holds a required member. The grouped parameter stays optional only when nothing inside it is
151
+ * required, matching the generated `RequestConfig` type.
152
+ */
153
+ function getRequestGroupOptionality(node) {
154
+ const groups = getRequestGroups(node);
155
+ const { path, query, header } = getOperationParameters(node);
156
+ const hasRequiredPath = path.some((param) => param.required);
157
+ const hasRequiredQuery = query.some((param) => param.required);
158
+ const hasRequiredHeader = header.some((param) => param.required);
159
+ return {
160
+ groups,
161
+ hasRequiredPath,
162
+ hasRequiredQuery,
163
+ hasRequiredHeader,
164
+ isOptional: !hasRequiredPath && !hasRequiredQuery && !hasRequiredHeader && !groups.body
165
+ };
166
+ }
167
+ function buildOperationComments(node, options = {}) {
168
+ const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
169
+ const linkComment = getOperationLink(node, link);
170
+ const filteredComments = (linkPosition === "beforeDeprecated" ? [
171
+ node.description && `@description ${node.description}`,
172
+ node.summary && `@summary ${node.summary}`,
173
+ linkComment,
174
+ node.deprecated && "@deprecated"
175
+ ] : [
176
+ node.description && `@description ${node.description}`,
177
+ node.summary && `@summary ${node.summary}`,
178
+ node.deprecated && "@deprecated",
179
+ linkComment
180
+ ]).filter((comment) => Boolean(comment));
181
+ if (!splitLines) return filteredComments;
182
+ return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
183
+ }
184
+ function getOperationParameters(node) {
185
+ return {
186
+ path: dedupeParams(node.parameters.filter((param) => param.in === "path")),
187
+ query: dedupeParams(node.parameters.filter((param) => param.in === "query")),
188
+ header: dedupeParams(node.parameters.filter((param) => param.in === "header")),
189
+ cookie: dedupeParams(node.parameters.filter((param) => param.in === "cookie"))
190
+ };
191
+ }
192
+ function getStatusCodeNumber(statusCode) {
193
+ const code = Number(statusCode);
194
+ return Number.isNaN(code) ? null : code;
195
+ }
196
+ function isSuccessStatusCode(statusCode) {
197
+ const code = getStatusCodeNumber(statusCode);
198
+ return code !== null && code >= 200 && code < 300;
199
+ }
200
+ function getSuccessResponses(responses) {
201
+ return responses.filter((response) => isSuccessStatusCode(response.statusCode));
202
+ }
203
+ function getOperationSuccessResponses(node) {
204
+ return getSuccessResponses(node.responses);
205
+ }
206
+ function getPrimarySuccessResponse(node) {
207
+ return getOperationSuccessResponses(node)[0] ?? null;
208
+ }
209
+ //#endregion
210
+ //#region ../../internals/utils/src/casing.ts
211
+ /**
212
+ * Shared implementation for camelCase and PascalCase conversion.
213
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
214
+ * and capitalizes each word according to `pascal`.
215
+ *
216
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
217
+ */
218
+ function toCamelOrPascal(text, pascal) {
219
+ 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) => {
220
+ if (word.length > 1 && word === word.toUpperCase()) return word;
221
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
222
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
223
+ }
224
+ /**
225
+ * Converts `text` to camelCase.
226
+ *
227
+ * @example Word boundaries
228
+ * `camelCase('hello-world') // 'helloWorld'`
229
+ *
230
+ * @example With a prefix
231
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
232
+ */
233
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
234
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
235
+ }
236
+ /**
237
+ * Converts `text` to PascalCase.
238
+ *
239
+ * @example Word boundaries
240
+ * `pascalCase('hello-world') // 'HelloWorld'`
241
+ *
242
+ * @example With a suffix
243
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
244
+ */
245
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
246
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
247
+ }
248
+ //#endregion
249
+ //#region ../../internals/utils/src/reserved.ts
250
+ /**
251
+ * JavaScript and Java reserved words.
252
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
253
+ */
254
+ const reservedWords = /* @__PURE__ */ new Set([
255
+ "abstract",
256
+ "arguments",
257
+ "boolean",
258
+ "break",
259
+ "byte",
260
+ "case",
261
+ "catch",
262
+ "char",
263
+ "class",
264
+ "const",
265
+ "continue",
266
+ "debugger",
267
+ "default",
268
+ "delete",
269
+ "do",
270
+ "double",
271
+ "else",
272
+ "enum",
273
+ "eval",
274
+ "export",
275
+ "extends",
276
+ "false",
277
+ "final",
278
+ "finally",
279
+ "float",
280
+ "for",
281
+ "function",
282
+ "goto",
283
+ "if",
284
+ "implements",
285
+ "import",
286
+ "in",
287
+ "instanceof",
288
+ "int",
289
+ "interface",
290
+ "let",
291
+ "long",
292
+ "native",
293
+ "new",
294
+ "null",
295
+ "package",
296
+ "private",
297
+ "protected",
298
+ "public",
299
+ "return",
300
+ "short",
301
+ "static",
302
+ "super",
303
+ "switch",
304
+ "synchronized",
305
+ "this",
306
+ "throw",
307
+ "throws",
308
+ "transient",
309
+ "true",
310
+ "try",
311
+ "typeof",
312
+ "var",
313
+ "void",
314
+ "volatile",
315
+ "while",
316
+ "with",
317
+ "yield",
318
+ "Array",
319
+ "Date",
320
+ "hasOwnProperty",
321
+ "Infinity",
322
+ "isFinite",
323
+ "isNaN",
324
+ "isPrototypeOf",
325
+ "length",
326
+ "Math",
327
+ "name",
328
+ "NaN",
329
+ "Number",
330
+ "Object",
331
+ "prototype",
332
+ "String",
333
+ "toString",
334
+ "undefined",
335
+ "valueOf"
336
+ ]);
337
+ /**
338
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * isValidVarName('status') // true
343
+ * isValidVarName('class') // false (reserved word)
344
+ * isValidVarName('42foo') // false (starts with digit)
345
+ * ```
346
+ */
347
+ function isValidVarName(name) {
348
+ if (!name || reservedWords.has(name)) return false;
349
+ return isIdentifier(name);
350
+ }
351
+ /**
352
+ * Returns `name` when it's a syntactically valid JavaScript variable name,
353
+ * otherwise prefixes it with `_` so the result is a valid identifier.
354
+ *
355
+ * Useful for sanitizing OpenAPI schema names or operation IDs that start with
356
+ * a digit (e.g. `409`, `504AccountCancel`) before using them as exported
357
+ * variable, type, or function names.
358
+ *
359
+ * @example
360
+ * ```ts
361
+ * ensureValidVarName('409') // '_409'
362
+ * ensureValidVarName('504AccountCancel') // '_504AccountCancel'
363
+ * ensureValidVarName('Pet') // 'Pet'
364
+ * ensureValidVarName('class') // '_class'
365
+ * ```
366
+ */
367
+ function ensureValidVarName(name) {
368
+ if (!name || isValidVarName(name)) return name;
369
+ return `_${name}`;
370
+ }
371
+ /**
372
+ * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
373
+ *
374
+ * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
375
+ * even though they are not valid variable names, so use this (not {@link isValidVarName}) when
376
+ * deciding whether an object key needs quoting.
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * isIdentifier('name') // true
381
+ * isIdentifier('x-total')// false
382
+ * ```
383
+ */
384
+ function isIdentifier(name) {
385
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
386
+ }
387
+ //#endregion
388
+ //#region ../../internals/utils/src/codegen.ts
389
+ /**
390
+ * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
391
+ * comments.
392
+ *
393
+ * @example
394
+ * ```ts
395
+ * buildJSDoc(['@type string', '@example hello'])
396
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
397
+ * ```
398
+ */
399
+ function buildJSDoc(comments, options = {}) {
400
+ const { indent = " * ", suffix = "\n ", fallback = " " } = options;
401
+ if (comments.length === 0) return fallback;
402
+ return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
403
+ }
404
+ //#endregion
405
+ //#region ../../internals/shared/src/group.ts
406
+ /**
407
+ * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
408
+ * shared default naming so every plugin groups output consistently:
409
+ *
410
+ * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
411
+ * - other groups use the camelCased group (`pet store` → `petStore`).
412
+ *
413
+ * A user-provided `group.name` always wins over the default namer, so callers stay in
414
+ * control of their output folders. Returns `null` when grouping is disabled, matching the
415
+ * per-plugin convention.
416
+ *
417
+ * @param group - The user-supplied group option, or `undefined` to disable grouping.
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * createGroupConfig(group) // shared across every plugin
422
+ * ```
423
+ */
424
+ function createGroupConfig(group) {
425
+ if (!group) return null;
426
+ const defaultName = (ctx) => {
427
+ if (group.type === "path") return `${ctx.group.split("/")[1]}`;
428
+ return camelCase(ctx.group);
429
+ };
430
+ return {
431
+ ...group,
432
+ name: group.name ? group.name : defaultName
433
+ };
434
+ }
435
+ //#endregion
436
+ //#region ../../internals/client/src/builders/generics.ts
437
+ /**
438
+ * Builds the `RequestResult` generic arguments for one operation: the plugin-ts per-status responses
439
+ * record plus the per-call `ThrowOnError` flag. `SuccessOf` / `ErrorOf` split the record inside the
440
+ * runtime, so this only names the record and threads `ThrowOnError`.
441
+ *
442
+ * @example
443
+ * `buildRequestResultGenerics({ node, tsResolver }) // 'AddPetResponses, ThrowOnError'`
444
+ */
445
+ function buildRequestResultGenerics({ node, tsResolver }) {
446
+ return `${tsResolver.response.responses(node)}, ThrowOnError`;
447
+ }
448
+ //#endregion
449
+ //#region ../../internals/client/src/builders/returnStatement.ts
450
+ /**
451
+ * Builds the return statement of a generated operation function. The runtime call already resolves
452
+ * to `{ data, error, request, response }`; the generated code forwards that result and casts it to
453
+ * the operation's `RequestResult`, which carries the `throwOnError` discrimination.
454
+ *
455
+ * @example
456
+ * `return request({ method: 'POST', url: '/pet', ...config }) as Promise<RequestResult<AddPetResponses, ThrowOnError>>`
457
+ */
458
+ function buildReturnStatement({ node, tsResolver, callConfig }) {
459
+ return `return request(${callConfig}) as Promise<RequestResult<${buildRequestResultGenerics({
460
+ node,
461
+ tsResolver
462
+ })}>>`;
463
+ }
464
+ //#endregion
465
+ //#region ../../internals/client/src/builders/security.ts
466
+ function serializeAuth(auth) {
467
+ const parts = [`type: '${auth.type}'`];
468
+ if (auth.scheme) parts.push(`scheme: '${auth.scheme}'`);
469
+ if (auth.name) parts.push(`name: '${auth.name}'`);
470
+ if (auth.in) parts.push(`in: '${auth.in}'`);
471
+ return `{ ${parts.join(", ")} }`;
472
+ }
473
+ /**
474
+ * Maps an OpenAPI security scheme to the inline `Auth` object, or `null` when the runtime cannot
475
+ * place it (an unresolved `$ref`, or an `apiKey` without a name or outside `header` / `query` /
476
+ * `cookie`). `http` schemes other than `basic` are treated as bearer.
477
+ */
478
+ function resolveSecurityScheme(scheme) {
479
+ if (!scheme || "$ref" in scheme) return null;
480
+ if (scheme.type === "apiKey") {
481
+ if (!scheme.name || scheme.in !== "header" && scheme.in !== "query" && scheme.in !== "cookie") return null;
482
+ return {
483
+ type: "apiKey",
484
+ name: scheme.name,
485
+ in: scheme.in
486
+ };
487
+ }
488
+ if (scheme.type === "http") return {
489
+ type: "http",
490
+ scheme: scheme.scheme?.toLowerCase() === "basic" ? "basic" : "bearer"
491
+ };
492
+ if (scheme.type === "oauth2") return { type: "oauth2" };
493
+ if (scheme.type === "openIdConnect") return { type: "openIdConnect" };
494
+ return null;
495
+ }
496
+ /**
497
+ * Derives the per-operation security metadata from the OpenAPI document. The operation's own
498
+ * `security` overrides the global `security` (an explicit empty array disables auth), and every
499
+ * referenced scheme is resolved from `components.securitySchemes` into a flat, de-duplicated list of
500
+ * `Auth` objects the runtime walks in order.
501
+ *
502
+ * @example
503
+ * `getOperationSecurity({ document, method: 'POST', path: '/pet' })`
504
+ * `// [{ type: 'http', scheme: 'bearer' }]`
505
+ */
506
+ function getOperationSecurity({ document, method, path }) {
507
+ if (!document) return void 0;
508
+ const requirements = (document.paths?.[path]?.[method.toLowerCase()])?.security ?? document.security;
509
+ if (!requirements?.length) return void 0;
510
+ const definitions = document.components?.securitySchemes ?? {};
511
+ const security = [];
512
+ const seen = /* @__PURE__ */ new Set();
513
+ for (const requirement of requirements) for (const schemeName of Object.keys(requirement)) {
514
+ if (seen.has(schemeName)) continue;
515
+ seen.add(schemeName);
516
+ const auth = resolveSecurityScheme(definitions[schemeName]);
517
+ if (auth) security.push(auth);
518
+ }
519
+ return security.length ? security : void 0;
520
+ }
521
+ /**
522
+ * Serializes the per-operation security into the literal emitted on each generated call's `security`
523
+ * field. The runtime `resolveAuth` helper walks it, calling the configured `auth` resolver per entry.
524
+ *
525
+ * @example
526
+ * `buildSecurityMetadata({ security: [{ type: 'http', scheme: 'bearer' }] }) // "[{ type: 'http', scheme: 'bearer' }]"`
527
+ */
528
+ function buildSecurityMetadata({ security }) {
529
+ if (!security?.length) return null;
530
+ return `[${security.map(serializeAuth).join(", ")}]`;
531
+ }
532
+ //#endregion
533
+ //#region ../../internals/client/src/builders/signature.ts
534
+ const declarationPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
535
+ /**
536
+ * Builds the grouped-options signature for one operation: a single `options` object whose `TData`
537
+ * is the plugin-ts `<Name>Options` (carrying a literal `url`), and a `RequestResult` return type
538
+ * keyed to the plugin-ts per-status responses record. There are no positional arguments.
539
+ *
540
+ * The generated file imports `<Name>Options` and `<Name>Responses` and uses them directly, so no
541
+ * per-operation input type has to be emitted.
542
+ */
543
+ function buildGroupedOptionsSignature({ node, tsResolver }) {
544
+ const optionsName = tsResolver.response.options(node);
545
+ const responsesName = tsResolver.response.responses(node);
546
+ const resultGenerics = buildRequestResultGenerics({
547
+ node,
548
+ tsResolver
549
+ });
550
+ const { isOptional } = getRequestGroupOptionality(node);
551
+ return {
552
+ dataTypeName: optionsName,
553
+ paramsSignature: declarationPrinter.print((0, _kubb_plugin_ts.createFunctionParameters)({ params: [(0, _kubb_plugin_ts.createFunctionParameter)({
554
+ name: "options",
555
+ type: `Options<${optionsName}, ThrowOnError>`,
556
+ ...isOptional ? { default: "{}" } : {}
557
+ })] })) ?? "",
558
+ returnType: `Promise<RequestResult<${resultGenerics}>>`,
559
+ generics: ["ThrowOnError extends boolean = true"],
560
+ importedTypeNames: [optionsName, responsesName]
561
+ };
562
+ }
563
+ //#endregion
564
+ //#region ../../internals/client/src/builders/validatorOptions.ts
565
+ /**
566
+ * Returns `true` when any direction of the validator uses zod (used for dependency checks).
567
+ */
568
+ function isValidatorEnabled(validator) {
569
+ if (!validator) return false;
570
+ if (validator === "zod") return true;
571
+ return Boolean(validator.request || validator.response);
572
+ }
573
+ /**
574
+ * Returns `'zod'` when request body parsing is enabled, `null` otherwise. The string shorthand
575
+ * `'zod'` validates the response only, so it does not enable request parsing.
576
+ */
577
+ function resolveRequestValidator(validator) {
578
+ if (!validator || validator === "zod") return null;
579
+ return validator.request ?? null;
580
+ }
581
+ /**
582
+ * Returns `'zod'` when query-parameters parsing is enabled, `null` otherwise. Only the object form
583
+ * `{ request: 'zod' }` enables it.
584
+ */
585
+ function resolveQueryParamsValidator(validator) {
586
+ if (!validator || validator === "zod") return null;
587
+ return validator.request ?? null;
588
+ }
589
+ /**
590
+ * Returns `'zod'` when response parsing is enabled, `null` otherwise. The string shorthand `'zod'`
591
+ * maps to response parsing.
592
+ */
593
+ function resolveResponseValidator(validator) {
594
+ if (!validator) return null;
595
+ if (validator === "zod") return "zod";
596
+ return validator.response ?? null;
597
+ }
598
+ /**
599
+ * Resolves the zod expression a generated client validates a success response with. Only success
600
+ * (2xx) bodies reach the parse under the throw-on-error contract, so the success-only
601
+ * `<operation>ResponseSchema` is used; error bodies are never zod-parsed.
602
+ */
603
+ function buildZodResponseParse(node, zodResolver) {
604
+ const name = zodResolver.response.response(node);
605
+ return name ? {
606
+ expression: name,
607
+ importNames: [name]
608
+ } : null;
609
+ }
610
+ /**
611
+ * Resolves the zod expression a generated client validates an error body with on the non-throw path.
612
+ * Uses the error-only `<operation>ErrorSchema` (the union of non-2xx statuses); returns `null` when the
613
+ * operation documents no error responses with a schema.
614
+ */
615
+ function buildZodErrorParse(node, zodResolver) {
616
+ if (!node.responses.some((res) => !isSuccessStatusCode(res.statusCode) && res.content?.some((entry) => entry.schema))) return null;
617
+ const name = zodResolver.response.error?.(node);
618
+ return name ? {
619
+ expression: name,
620
+ importNames: [name]
621
+ } : null;
622
+ }
623
+ //#endregion
624
+ //#region ../../internals/client/src/builders/validator.ts
625
+ /**
626
+ * Builds the validator-hook references for one operation. Request validation runs before the send;
627
+ * response validation runs on the success body only. Returns `null` references when the matching
628
+ * direction is disabled or the schema is absent.
629
+ */
630
+ function buildValidatorHooks({ node, validator, zodResolver }) {
631
+ const importedZodNames = [];
632
+ const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
633
+ const zodRequestName = zodResolver && resolveRequestValidator(validator) === "zod" && hasRequestBody ? zodResolver.response.body(node) : null;
634
+ const request = zodRequestName ?? null;
635
+ if (zodRequestName) importedZodNames.push(zodRequestName);
636
+ const responseParse = zodResolver && resolveResponseValidator(validator) === "zod" ? buildZodResponseParse(node, zodResolver) : null;
637
+ const response = responseParse ? responseParse.expression : null;
638
+ if (responseParse) importedZodNames.push(...responseParse.importNames);
639
+ const errorParse = zodResolver && resolveResponseValidator(validator) === "zod" ? buildZodErrorParse(node, zodResolver) : null;
640
+ const error = errorParse ? errorParse.expression : null;
641
+ if (errorParse) importedZodNames.push(...errorParse.importNames);
642
+ return {
643
+ request,
644
+ response,
645
+ error,
646
+ importedZodNames
647
+ };
648
+ }
649
+ //#endregion
650
+ //#region ../../internals/client/src/builders/sdkMethod.ts
651
+ /**
652
+ * Builds the call config literal forwarded to the contract client, mirroring the shared `Operation`
653
+ * component: `{ method, url, security?, validator?, ...config }`. The `...config` spread carries every
654
+ * per-call field (including `throwOnError`), so the method stays a thin wrapper over the contract.
655
+ */
656
+ function buildCallConfig({ node, validator, zodResolver, security }) {
657
+ const validators = buildValidatorHooks({
658
+ node,
659
+ validator,
660
+ zodResolver
661
+ });
662
+ const validatorEntries = [validators.request ? `request: ${validators.request}` : null, validators.response ? `response: ${validators.response}` : null].filter(Boolean);
663
+ const validatorLiteral = validatorEntries.length ? `validator: { ${validatorEntries.join(", ")} }` : null;
664
+ const securityLiteral = buildSecurityMetadata({ security });
665
+ return `{ ${[
666
+ `method: '${node.method.toUpperCase()}'`,
667
+ `url: '${node.path}'`,
668
+ securityLiteral ? `security: ${securityLiteral}` : null,
669
+ validatorLiteral,
670
+ "...config"
671
+ ].filter(Boolean).join(", ")} }`;
672
+ }
673
+ /**
674
+ * Builds a single instance method for a generated SDK class. The body forwards the single grouped
675
+ * `options` object to the instance's own client (`this.client`, built once in the constructor) and
676
+ * returns the `RequestResult`. A per-call `options.client` still overrides the instance client, so
677
+ * one operation can be routed to a different environment without a new instance.
678
+ */
679
+ function buildSdkMethod({ node, name, tsResolver, zodResolver, validator, security }) {
680
+ if (!kubb_kit.ast.isHttpOperationNode(node)) return "";
681
+ const signature = buildGroupedOptionsSignature({
682
+ node,
683
+ tsResolver
684
+ });
685
+ const returnStatement = buildReturnStatement({
686
+ node,
687
+ tsResolver,
688
+ callConfig: buildCallConfig({
689
+ node,
690
+ validator,
691
+ zodResolver,
692
+ security
693
+ })
694
+ });
695
+ const generics = signature.generics.length ? `<${signature.generics.join(", ")}>` : "";
696
+ const jsdoc = buildJSDoc(buildOperationComments(node, {
697
+ link: "urlPath",
698
+ linkPosition: "beforeDeprecated",
699
+ splitLines: true
700
+ }));
701
+ const methodBody = [
702
+ "const { client: request = this.client, ...config } = options",
703
+ "",
704
+ returnStatement
705
+ ].map((line) => line ? ` ${line}` : "").join("\n");
706
+ return `${jsdoc} public ${name}${generics}(${signature.paramsSignature}): ${signature.returnType} {\n${methodBody}\n }`;
707
+ }
708
+ //#endregion
709
+ //#region ../../internals/client/src/builders/styles.ts
710
+ /**
711
+ * Renders a parameter name as an object-literal key, quoted when it is not a bare identifier.
712
+ * Path keys are camelCased to match the URL template placeholders. Query, header, and cookie keys
713
+ * keep the spec name, matching the remapped keys the runtime serializes.
714
+ */
715
+ function toKey(name, location) {
716
+ const key = location === "path" ? camelCase(name) : name;
717
+ return isValidVarName(key) ? key : JSON.stringify(key);
718
+ }
719
+ /**
720
+ * Serializes one parameter's metadata into a `{ style, explode }` literal, or `null` when the
721
+ * parameter carries neither. Path and query carry the serialization `style`; header and cookie use a
722
+ * fixed style (`simple` and `form`), so only `explode` is emitted for them.
723
+ */
724
+ function serializeParameter(parameter) {
725
+ const parts = [];
726
+ if ((parameter.in === "path" || parameter.in === "query") && parameter.style) parts.push(`style: '${parameter.style}'`);
727
+ if (parameter.explode !== void 0) parts.push(`explode: ${parameter.explode}`);
728
+ return parts.length > 0 ? `{ ${parts.join(", ")} }` : null;
729
+ }
730
+ /**
731
+ * Builds the per-operation `styles` literal from the operation's parameters, grouped by location.
732
+ * Path entries are keyed by the camelCased name to match the URL template placeholders; query,
733
+ * header, and cookie entries keep the spec name to match the keys the runtime serializes.
734
+ * Only parameters whose source defines `style` or `explode` are emitted, so calls without
735
+ * serialization metadata keep the runtime defaults and existing output is unchanged. Returns `null`
736
+ * when no parameter carries metadata.
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * // a path param with { style: 'matrix', explode: true } and a query param with { explode: false }
741
+ * buildStyles({ node }) // "{ path: { id: { style: 'matrix', explode: true } }, query: { tags: { explode: false } } }"
742
+ * ```
743
+ */
744
+ function buildStyles({ node }) {
745
+ if (!kubb_kit.ast.isHttpOperationNode(node)) return null;
746
+ const groups = {
747
+ path: [],
748
+ query: [],
749
+ header: [],
750
+ cookie: []
751
+ };
752
+ for (const parameter of node.parameters) {
753
+ const literal = serializeParameter(parameter);
754
+ if (!literal) continue;
755
+ groups[parameter.in].push(`${toKey(parameter.name, parameter.in)}: ${literal}`);
756
+ }
757
+ const locations = Object.keys(groups).filter((location) => groups[location].length > 0);
758
+ if (locations.length === 0) return null;
759
+ return `{ ${locations.map((location) => `${location}: { ${groups[location].join(", ")} }`).join(", ")} }`;
760
+ }
761
+ //#endregion
762
+ //#region ../../internals/client/src/components/Operation.tsx
763
+ /**
764
+ * Renders one client operation: the grouped `<Name>Request` type and the function that forwards a
765
+ * single `options` object to the resolved client and returns the `RequestResult`. The type, signature,
766
+ * and call config are built with the AST factory, and only the jsx-renderer emits the source.
767
+ */
768
+ function Operation({ name, node, tsResolver, zodResolver, validator, security, isExportable = true, isIndexable = true }) {
769
+ if (!kubb_kit.ast.isHttpOperationNode(node)) return null;
770
+ const signature = buildGroupedOptionsSignature({
771
+ node,
772
+ tsResolver
773
+ });
774
+ const validators = buildValidatorHooks({
775
+ node,
776
+ validator,
777
+ zodResolver
778
+ });
779
+ const securityLiteral = buildSecurityMetadata({ security });
780
+ const stylesLiteral = buildStyles({ node });
781
+ const { defaultContentType } = getContentTypeInfo(node);
782
+ const bakedRequestContentType = Boolean(node.requestBody?.content?.[0]?.schema) && defaultContentType !== "application/json" ? defaultContentType : null;
783
+ const mergeContentType = Boolean(bakedRequestContentType) && getResponseContentTypeInfo(node).isMultipleContentTypes;
784
+ const contentTypeLiteral = !bakedRequestContentType ? null : mergeContentType ? `contentType: { request: '${bakedRequestContentType}', ...(typeof contentType === 'string' ? { request: contentType } : contentType) }` : `contentType: { request: '${bakedRequestContentType}' }`;
785
+ const eventStream = isEventStream(node);
786
+ const responseType = getResponseType(node);
787
+ const responseTypeLiteral = responseType ? `responseType: '${responseType}'` : null;
788
+ const validatorEntries = [
789
+ validators.request ? `request: ${validators.request}` : null,
790
+ validators.response ? `response: ${validators.response}` : null,
791
+ validators.error ? `error: ${validators.error}` : null
792
+ ].filter(Boolean);
793
+ const validatorLiteral = validatorEntries.length ? `validator: { ${validatorEntries.join(", ")} }` : null;
794
+ const callConfig = `{ ${[
795
+ `method: '${node.method.toUpperCase()}'`,
796
+ `url: '${node.path}'`,
797
+ securityLiteral ? `security: ${securityLiteral}` : null,
798
+ stylesLiteral ? `styles: ${stylesLiteral}` : null,
799
+ validatorLiteral,
800
+ contentTypeLiteral,
801
+ responseTypeLiteral,
802
+ "...config"
803
+ ].filter(Boolean).join(", ")} }`;
804
+ const eventType = `SuccessOf<${tsResolver.response.responses(node)}>`;
805
+ const returnType = eventStream ? `Promise<EventStreamResult<${eventType}>>` : signature.returnType;
806
+ const returnStatement = eventStream ? `return toEventStream<${eventType}>(request(${callConfig}))` : buildReturnStatement({
807
+ node,
808
+ tsResolver,
809
+ callConfig
810
+ });
811
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Source, {
812
+ name,
813
+ isExportable,
814
+ isIndexable,
815
+ children: /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.Function, {
816
+ name,
817
+ export: isExportable,
818
+ generics: signature.generics,
819
+ params: signature.paramsSignature,
820
+ returnType,
821
+ JSDoc: { comments: buildOperationComments(node, {
822
+ link: "urlPath",
823
+ linkPosition: "beforeDeprecated",
824
+ splitLines: true
825
+ }) },
826
+ children: [
827
+ mergeContentType ? "const { client: request = client, contentType, ...config } = options" : "const { client: request = client, ...config } = options",
828
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)("br", {}),
829
+ returnStatement
830
+ ]
831
+ })
832
+ });
833
+ }
834
+ //#endregion
835
+ //#region ../../internals/client/src/components/SdkClient.tsx
836
+ /**
837
+ * Renders one instance class per tag with one method per operation. The constructor takes a client
838
+ * config object and builds its own client through `createClient`, so each environment is a separate
839
+ * instance: `const api = new PetClient({ baseURL }); api.getPetById(...)`. A per-call `client` option
840
+ * still overrides the instance client for a one-off call.
841
+ */
842
+ function SdkClient({ name, isExportable = true, isIndexable = true, operations, validator, children }) {
843
+ const methods = operations.map(({ node, name: methodName, tsResolver, zodResolver, security }) => buildSdkMethod({
844
+ node,
845
+ name: methodName,
846
+ tsResolver,
847
+ zodResolver,
848
+ validator,
849
+ security
850
+ }));
851
+ const classCode = `export class ${name} {\n${[
852
+ " private readonly client: ClientInstance",
853
+ "",
854
+ " constructor(config: ClientConfig = {}) {",
855
+ " this.client = createClient(config)",
856
+ " }"
857
+ ].join("\n")}\n\n${methods.join("\n\n")}\n}`;
858
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.File.Source, {
859
+ name,
860
+ isExportable,
861
+ isIndexable,
862
+ children: [classCode, children]
863
+ });
864
+ }
865
+ //#endregion
866
+ //#region ../../internals/client/src/generators/clientGenerator.tsx
867
+ /**
868
+ * Builds the built-in per-operation generator shared by the client plugins (`@kubb/plugin-fetch`,
869
+ * `@kubb/plugin-axios`). Emits one async function per OpenAPI operation using the shared
870
+ * `Operation` component: a grouped `<Name>Request` type and a function that forwards a single
871
+ * `options` object to the bundled `client` and returns the `RequestResult`. Only the generator
872
+ * `name` differs between plugins; every other resolution, import, and rendering step is identical.
873
+ */
874
+ function createClientGenerator(name) {
875
+ return (0, kubb_kit.defineGenerator)({
876
+ name,
877
+ renderer: kubb_jsx.jsxRenderer,
878
+ operation(node, ctx) {
879
+ if (!kubb_kit.ast.isHttpOperationNode(node)) return null;
880
+ const { config, driver, resolver, root } = ctx;
881
+ const { output, validator, group } = ctx.options;
882
+ const pluginTs = driver.getPlugin(_kubb_plugin_ts.pluginTsName);
883
+ if (!pluginTs) return null;
884
+ const tsResolver = driver.getResolver(_kubb_plugin_ts.pluginTsName);
885
+ const pluginZod = resolveResponseValidator(validator) === "zod" || resolveRequestValidator(validator) === "zod" ? driver.getPlugin(_kubb_plugin_zod.pluginZodName) : null;
886
+ const zodResolver = pluginZod ? driver.getResolver(_kubb_plugin_zod.pluginZodName) : null;
887
+ const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
888
+ const importedTypeNames = [tsResolver.response.options(node), tsResolver.response.responses(node)];
889
+ const importedZodNames = zodResolver ? [
890
+ resolveResponseValidator(validator) === "zod" ? zodResolver.response.response?.(node) : null,
891
+ resolveResponseValidator(validator) === "zod" ? buildZodErrorParse(node, zodResolver)?.expression ?? null : null,
892
+ resolveRequestValidator(validator) === "zod" && hasRequestBody ? zodResolver.response.body?.(node) : null
893
+ ].filter((name) => Boolean(name)) : [];
894
+ const meta = {
895
+ name: resolver.name(node.operationId),
896
+ file: resolver.file({
897
+ ...operationFileEntry(node, node.operationId),
898
+ root,
899
+ output,
900
+ group: group ?? void 0
901
+ }),
902
+ fileTs: tsResolver.file({
903
+ ...operationFileEntry(node, node.operationId),
904
+ root,
905
+ output: pluginTs.options?.output ?? output,
906
+ group: pluginTs.options?.group ?? void 0
907
+ }),
908
+ fileZod: zodResolver && pluginZod?.options ? zodResolver.file({
909
+ ...operationFileEntry(node, node.operationId),
910
+ root,
911
+ output: pluginZod.options.output ?? output,
912
+ group: pluginZod.options?.group ?? void 0
913
+ }) : null
914
+ };
915
+ const security = getOperationSecurity({
916
+ document: ctx.adapter.document,
917
+ method: node.method,
918
+ path: node.path
919
+ });
920
+ const clientPath = node_path.default.resolve(root, ".kubb/client.ts");
921
+ const eventStream = isEventStream(node);
922
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.File, {
923
+ baseName: meta.file.baseName,
924
+ path: meta.file.path,
925
+ meta: meta.file.meta,
926
+ banner: resolver.default.banner(ctx.meta, {
927
+ output,
928
+ config,
929
+ file: {
930
+ path: meta.file.path,
931
+ baseName: meta.file.baseName
932
+ }
933
+ }),
934
+ footer: resolver.default.footer(ctx.meta, {
935
+ output,
936
+ config,
937
+ file: {
938
+ path: meta.file.path,
939
+ baseName: meta.file.baseName
940
+ }
941
+ }),
942
+ children: [
943
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
944
+ name: eventStream ? ["client", "toEventStream"] : ["client"],
945
+ root: meta.file.path,
946
+ path: clientPath
947
+ }),
948
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
949
+ name: eventStream ? [
950
+ "Options",
951
+ "EventStreamResult",
952
+ "SuccessOf"
953
+ ] : ["Options", "RequestResult"],
954
+ root: meta.file.path,
955
+ path: clientPath,
956
+ isTypeOnly: true
957
+ }),
958
+ meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
959
+ name: Array.from(new Set(importedTypeNames)),
960
+ root: meta.file.path,
961
+ path: meta.fileTs.path,
962
+ isTypeOnly: true
963
+ }),
964
+ meta.fileZod && importedZodNames.length > 0 && /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
965
+ name: importedZodNames,
966
+ root: meta.file.path,
967
+ path: meta.fileZod.path
968
+ }),
969
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(Operation, {
970
+ name: meta.name,
971
+ node,
972
+ tsResolver,
973
+ zodResolver,
974
+ validator,
975
+ security
976
+ })
977
+ ]
978
+ });
979
+ }
980
+ });
981
+ }
982
+ //#endregion
983
+ //#region ../../internals/client/src/components/SdkFacade.tsx
984
+ /**
985
+ * Renders a composed root SDK class that instantiates every tag client from one shared config, so
986
+ * `new PetStore({ baseURL }).petClient.getPetById(...)` reaches an operation through a single entry
987
+ * point bound to one environment. The per-tag clients are read-only fields built in the constructor.
988
+ */
989
+ function SdkFacade({ name, isExportable = true, isIndexable = true, members, children }) {
990
+ const fields = members.map((member) => ` readonly ${member.propName}: ${member.className}`);
991
+ const assignments = members.map((member) => ` this.${member.propName} = new ${member.className}(config)`);
992
+ const classCode = `export class ${name} {\n${[
993
+ ...fields,
994
+ "",
995
+ " constructor(config: ClientConfig = {}) {",
996
+ ...assignments,
997
+ " }"
998
+ ].join("\n")}\n}`;
999
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.File.Source, {
1000
+ name,
1001
+ isExportable,
1002
+ isIndexable,
1003
+ children: [classCode, children]
1004
+ });
1005
+ }
1006
+ //#endregion
1007
+ //#region ../../internals/client/src/generators/sdkGenerator.tsx
1008
+ function resolveTypeImportNames(node, tsResolver) {
1009
+ return [tsResolver.response.options(node), tsResolver.response.responses(node)];
1010
+ }
1011
+ function resolveZodImportNames(node, zodResolver, validator) {
1012
+ const { query: queryParams } = getOperationParameters(node);
1013
+ return [
1014
+ resolveResponseValidator(validator) === "zod" ? zodResolver.response.response(node) : null,
1015
+ resolveResponseValidator(validator) === "zod" ? buildZodErrorParse(node, zodResolver)?.expression ?? null : null,
1016
+ resolveRequestValidator(validator) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.response.body(node) : null,
1017
+ resolveQueryParamsValidator(validator) === "zod" && queryParams.length > 0 ? zodResolver.param.query(node, queryParams[0]) : null
1018
+ ].filter((n) => Boolean(n));
1019
+ }
1020
+ /**
1021
+ * Groups operations into one controller per tag. Operations without a tag fall back to a single
1022
+ * `Client`/`ApiClient` controller, matching the resolver's default naming.
1023
+ */
1024
+ function buildControllers(nodes, ctx) {
1025
+ const { driver, resolver, root } = ctx;
1026
+ const { output, group, validator } = ctx.options;
1027
+ const pluginTs = driver.getPlugin(_kubb_plugin_ts.pluginTsName);
1028
+ const tsResolver = driver.getResolver(_kubb_plugin_ts.pluginTsName);
1029
+ const tsPluginOptions = pluginTs.options;
1030
+ const pluginZod = isValidatorEnabled(validator) ? driver.getPlugin(_kubb_plugin_zod.pluginZodName) : null;
1031
+ const zodResolver = pluginZod ? driver.getResolver(_kubb_plugin_zod.pluginZodName) : null;
1032
+ const document = ctx.adapter.document;
1033
+ function buildOperationData(node) {
1034
+ const typeFile = tsResolver.file({
1035
+ ...operationFileEntry(node, node.operationId),
1036
+ root,
1037
+ output: tsPluginOptions?.output ?? output,
1038
+ group: tsPluginOptions?.group
1039
+ });
1040
+ const zodFile = zodResolver && pluginZod?.options ? zodResolver.file({
1041
+ ...operationFileEntry(node, node.operationId),
1042
+ root,
1043
+ output: pluginZod.options?.output ?? output,
1044
+ group: pluginZod.options?.group ?? void 0
1045
+ }) : null;
1046
+ const security = kubb_kit.ast.isHttpOperationNode(node) ? getOperationSecurity({
1047
+ document,
1048
+ method: node.method,
1049
+ path: node.path
1050
+ }) : void 0;
1051
+ return {
1052
+ node,
1053
+ name: resolver.name(node.operationId),
1054
+ tsResolver,
1055
+ zodResolver,
1056
+ typeFile,
1057
+ zodFile,
1058
+ security
1059
+ };
1060
+ }
1061
+ return nodes.reduce((acc, operationNode) => {
1062
+ if (!kubb_kit.ast.isHttpOperationNode(operationNode)) return acc;
1063
+ const tag = operationNode.tags[0];
1064
+ const name = tag ? group?.name?.({ group: camelCase(tag) }) ?? resolver.groupName(tag) : resolver.className("ApiClient");
1065
+ const file = resolver.file({
1066
+ name,
1067
+ extname: ".ts",
1068
+ tag,
1069
+ root,
1070
+ output,
1071
+ group: group ?? void 0
1072
+ });
1073
+ const operationData = buildOperationData(operationNode);
1074
+ const previous = acc.find((item) => item.file.path === file.path);
1075
+ if (previous) previous.operations.push(operationData);
1076
+ else acc.push({
1077
+ name,
1078
+ tag,
1079
+ file,
1080
+ operations: [operationData]
1081
+ });
1082
+ return acc;
1083
+ }, []);
1084
+ }
1085
+ function collectImportsByFile(ops, pick) {
1086
+ const namesByPath = /* @__PURE__ */ new Map();
1087
+ const filesByPath = /* @__PURE__ */ new Map();
1088
+ ops.forEach((op) => {
1089
+ const { file, names } = pick(op);
1090
+ if (!file || names.length === 0) return;
1091
+ if (!namesByPath.has(file.path)) namesByPath.set(file.path, /* @__PURE__ */ new Set());
1092
+ const set = namesByPath.get(file.path);
1093
+ names.forEach((n) => set.add(n));
1094
+ filesByPath.set(file.path, file);
1095
+ });
1096
+ return {
1097
+ namesByPath,
1098
+ filesByPath
1099
+ };
1100
+ }
1101
+ /**
1102
+ * Builds the class-based SDK generator for a client plugin (`@kubb/plugin-fetch`,
1103
+ * `@kubb/plugin-axios`). Only registered when `sdk` is set; otherwise the plugin keeps its
1104
+ * standalone per-operation functions.
1105
+ *
1106
+ * Every tag client is an instance class whose constructor takes a client config and builds its own
1107
+ * client, so each environment is a separate instance. With `sdk.mode: 'tag'` (the default) it
1108
+ * emits one class per tag and, when `sdk.name` is set, a composed root that instantiates every tag
1109
+ * client. With `sdk.mode: 'flat'` it emits one class named by `sdk.name`, with every operation as a
1110
+ * direct method.
1111
+ */
1112
+ function createSdkGenerator() {
1113
+ return (0, kubb_kit.defineGenerator)({
1114
+ name: "sdk",
1115
+ renderer: kubb_jsx.jsxRenderer,
1116
+ operations(nodes, ctx) {
1117
+ const { config, resolver, root } = ctx;
1118
+ const { output, group, validator, sdk } = ctx.options;
1119
+ if (!ctx.driver.getPlugin(_kubb_plugin_ts.pluginTsName) || !sdk) return null;
1120
+ const controllers = buildControllers(nodes, ctx);
1121
+ const clientPath = node_path.default.resolve(root, ".kubb/client.ts");
1122
+ const banner = (file) => resolver.default.banner(ctx.meta, {
1123
+ output,
1124
+ config,
1125
+ file: {
1126
+ path: file.path,
1127
+ baseName: file.baseName
1128
+ }
1129
+ });
1130
+ const footer = (file) => resolver.default.footer(ctx.meta, {
1131
+ output,
1132
+ config,
1133
+ file: {
1134
+ path: file.path,
1135
+ baseName: file.baseName
1136
+ }
1137
+ });
1138
+ const renderClassFile = (className, file, ops) => {
1139
+ const { namesByPath: typeNamesByPath, filesByPath: typeFilesByPath } = collectImportsByFile(ops, (op) => ({
1140
+ file: op.typeFile,
1141
+ names: resolveTypeImportNames(op.node, op.tsResolver)
1142
+ }));
1143
+ const { namesByPath: zodNamesByPath, filesByPath: zodFilesByPath } = isValidatorEnabled(validator) ? collectImportsByFile(ops, (op) => ({
1144
+ file: op.zodFile,
1145
+ names: op.zodResolver ? resolveZodImportNames(op.node, op.zodResolver, validator) : []
1146
+ })) : {
1147
+ namesByPath: /* @__PURE__ */ new Map(),
1148
+ filesByPath: /* @__PURE__ */ new Map()
1149
+ };
1150
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.File, {
1151
+ baseName: file.baseName,
1152
+ path: file.path,
1153
+ meta: file.meta,
1154
+ banner: banner(file),
1155
+ footer: footer(file),
1156
+ children: [
1157
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1158
+ name: ["createClient"],
1159
+ root: file.path,
1160
+ path: clientPath
1161
+ }),
1162
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1163
+ name: [
1164
+ "ClientConfig",
1165
+ "ClientInstance",
1166
+ "Options",
1167
+ "RequestResult"
1168
+ ],
1169
+ root: file.path,
1170
+ path: clientPath,
1171
+ isTypeOnly: true
1172
+ }),
1173
+ validator === "zod" && ops.some((op) => op.node.requestBody?.content?.[0]?.schema != null) && /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1174
+ name: ["z"],
1175
+ path: "zod",
1176
+ isTypeOnly: true
1177
+ }),
1178
+ Array.from(typeNamesByPath.entries()).map(([filePath, set]) => /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1179
+ name: Array.from(set),
1180
+ root: file.path,
1181
+ path: typeFilesByPath.get(filePath).path,
1182
+ isTypeOnly: true
1183
+ }, filePath)),
1184
+ isValidatorEnabled(validator) && Array.from(zodNamesByPath.entries()).map(([filePath, set]) => /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1185
+ name: Array.from(set),
1186
+ root: file.path,
1187
+ path: zodFilesByPath.get(filePath).path
1188
+ }, filePath)),
1189
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(SdkClient, {
1190
+ name: className,
1191
+ operations: ops,
1192
+ validator
1193
+ })
1194
+ ]
1195
+ }, file.path);
1196
+ };
1197
+ if (sdk.mode === "flat") return renderClassFile(resolver.className(sdk.name ?? "sdk"), resolver.file({
1198
+ name: sdk.name ?? "sdk",
1199
+ extname: ".ts",
1200
+ root,
1201
+ output,
1202
+ group: group ?? void 0
1203
+ }), controllers.flatMap((controller) => controller.operations));
1204
+ const classFiles = controllers.map(({ name, file, operations: ops }) => renderClassFile(name, file, ops));
1205
+ if (!sdk.name) return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx_jsx_runtime.Fragment, { children: classFiles });
1206
+ const sdkFile = resolver.file({
1207
+ name: sdk.name,
1208
+ extname: ".ts",
1209
+ root,
1210
+ output,
1211
+ group: group ?? void 0
1212
+ });
1213
+ const facadeName = resolver.className(sdk.name);
1214
+ const members = controllers.map(({ name, tag }) => ({
1215
+ className: name,
1216
+ propName: resolver.propertyName(tag ?? name)
1217
+ }));
1218
+ return /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx_jsx_runtime.Fragment, { children: [classFiles, /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsxs)(kubb_jsx.File, {
1219
+ baseName: sdkFile.baseName,
1220
+ path: sdkFile.path,
1221
+ meta: sdkFile.meta,
1222
+ banner: banner(sdkFile),
1223
+ footer: footer(sdkFile),
1224
+ children: [
1225
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1226
+ name: ["ClientConfig"],
1227
+ root: sdkFile.path,
1228
+ path: clientPath,
1229
+ isTypeOnly: true
1230
+ }),
1231
+ controllers.map(({ name, file }) => /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(kubb_jsx.File.Import, {
1232
+ name: [name],
1233
+ root: sdkFile.path,
1234
+ path: file.path
1235
+ }, name)),
1236
+ /* @__PURE__ */ (0, kubb_jsx_jsx_runtime.jsx)(SdkFacade, {
1237
+ name: facadeName,
1238
+ members
1239
+ })
1240
+ ]
1241
+ }, sdkFile.path)] });
1242
+ }
1243
+ });
1244
+ }
1245
+ //#endregion
1246
+ //#region ../../internals/client/src/macros.ts
1247
+ /**
1248
+ * Macros the client plugins apply by default, ahead of any user macros. `macroSimplifyUnion`
1249
+ * drops union members a broader scalar already covers, keeping the generated response and error
1250
+ * unions tidy. A plugin wires them with `ctx.setMacros([...defaultMacros, ...userMacros])`.
1251
+ */
1252
+ const defaultMacros = [kubb_kit.macroSimplifyUnion];
1253
+ //#endregion
1254
+ //#region ../../internals/client/src/resolver.ts
1255
+ /**
1256
+ * Default resolver shared by the client plugins. Functions and files inherit the built-in camelCase
1257
+ * `name` and `file`; classes and tag groups use PascalCase.
1258
+ *
1259
+ * @example
1260
+ * ```ts
1261
+ * resolverClient.name('show pet by id') // 'showPetById'
1262
+ * resolverClient.groupName('pet') // 'PetClient'
1263
+ * ```
1264
+ */
1265
+ const resolverClient = (0, kubb_kit.createResolver)({
1266
+ pluginName: "plugin-contract-client",
1267
+ className(name) {
1268
+ return ensureValidVarName(pascalCase(name));
1269
+ },
1270
+ groupName(name) {
1271
+ return ensureValidVarName(pascalCase(`${name} Client`));
1272
+ },
1273
+ propertyName(name) {
1274
+ return ensureValidVarName(camelCase(name));
1275
+ }
1276
+ });
1277
+ //#endregion
1278
+ //#region src/generators/clientGenerator.tsx
1279
+ /**
1280
+ * Built-in operation generator for `@kubb/plugin-fetch`. Emits one async function per OpenAPI
1281
+ * operation using the shared `Operation` component: a grouped `<Name>Request` type and a function
1282
+ * that forwards a single `options` object to the bundled `client` and returns the `RequestResult`.
1283
+ */
1284
+ const clientGenerator = createClientGenerator("fetch");
1285
+ //#endregion
1286
+ //#region src/templates.ts
1287
+ /** Absolute path to the fetch client template, copied into `.kubb/client.ts`. */
1288
+ const fetchClientTemplatePath = (0, node_url.fileURLToPath)(new URL("../templates/fetch.ts", require("url").pathToFileURL(__filename).href));
1289
+ /** Absolute path to the fetch serializers template, copied into `.kubb/serializers.ts`. */
1290
+ const fetchSerializersTemplatePath = (0, node_url.fileURLToPath)(new URL("../templates/serializers.ts", require("url").pathToFileURL(__filename).href));
1291
+ /**
1292
+ * Absolute path to the Standard Schema runtime template. Pass it to a file node's `copy` field to
1293
+ * emit the helper into the generated `.kubb/standardSchema.ts` verbatim.
1294
+ */
1295
+ const standardSchemaTemplatePath = (0, node_url.fileURLToPath)(new URL("../templates/standardSchema.ts", require("url").pathToFileURL(__filename).href));
1296
+ //#endregion
1297
+ //#region src/plugin.ts
1298
+ /**
1299
+ * Canonical plugin name for `@kubb/plugin-fetch`. Used for driver lookups and cross-plugin
1300
+ * dependency references.
1301
+ */
1302
+ const pluginFetchName = "plugin-fetch";
1303
+ /**
1304
+ * Generates a type-safe HTTP client pinned to the Fetch API. Each operation becomes one async
1305
+ * function that takes a single grouped `options` object and returns the shared `RequestResult`
1306
+ * contract. The runtime is always bundled into `.kubb/client.ts`, so generated code never imports
1307
+ * from `@kubb/plugin-fetch` and the only runtime dependency is the global `fetch`.
1308
+ *
1309
+ * @example
1310
+ * ```ts
1311
+ * import { defineConfig } from 'kubb/config'
1312
+ * import { pluginTs } from '@kubb/plugin-ts'
1313
+ * import { pluginFetch } from '@kubb/plugin-fetch'
1314
+ *
1315
+ * export default defineConfig({
1316
+ * input: './petStore.yaml',
1317
+ * output: { path: './src/gen' },
1318
+ * plugins: [
1319
+ * pluginTs(),
1320
+ * pluginFetch({ output: { path: './clients' } }),
1321
+ * ],
1322
+ * })
1323
+ * ```
1324
+ */
1325
+ const pluginFetch = (0, kubb_kit.definePlugin)((options) => {
1326
+ const { output = {
1327
+ path: "clients",
1328
+ barrel: { type: "named" }
1329
+ }, exclude = [], include, override = [], baseURL, validator = false, group, sdk, resolver: userResolver } = options;
1330
+ const resolved = {
1331
+ output,
1332
+ exclude,
1333
+ include,
1334
+ override,
1335
+ group: createGroupConfig(group),
1336
+ baseURL,
1337
+ validator,
1338
+ sdk: sdk ? {
1339
+ mode: sdk.mode ?? "tag",
1340
+ name: sdk.name
1341
+ } : void 0,
1342
+ resolver: userResolver ? kubb_kit.Resolver.merge(resolverClient, userResolver) : resolverClient
1343
+ };
1344
+ const selectedGenerators = resolved.sdk ? [createSdkGenerator()] : [clientGenerator];
1345
+ return {
1346
+ name: pluginFetchName,
1347
+ options,
1348
+ dependencies: [_kubb_plugin_ts.pluginTsName, isValidatorEnabled(resolved.validator) ? _kubb_plugin_zod.pluginZodName : null].filter((dependency) => Boolean(dependency)),
1349
+ hooks: { "kubb:plugin:setup"(ctx) {
1350
+ ctx.setOptions(resolved);
1351
+ ctx.setResolver(resolved.resolver);
1352
+ ctx.setMacros([...defaultMacros, ...options.macros ?? []]);
1353
+ ctx.addGenerator(...selectedGenerators);
1354
+ const root = node_path.default.resolve(ctx.config.root, ctx.config.output.path);
1355
+ const baseURLExpression = baseURL ? baseURL.includes("${") ? `\`${baseURL.replaceAll("`", "\\`")}\`` : JSON.stringify(baseURL) : void 0;
1356
+ ctx.injectFile({
1357
+ baseName: "serializers.ts",
1358
+ path: node_path.default.resolve(root, ".kubb/serializers.ts"),
1359
+ copy: fetchSerializersTemplatePath
1360
+ });
1361
+ ctx.injectFile({
1362
+ baseName: "client.ts",
1363
+ path: node_path.default.resolve(root, ".kubb/client.ts"),
1364
+ copy: fetchClientTemplatePath,
1365
+ footer: baseURLExpression ? `client.setConfig({ baseURL: ${baseURLExpression} })` : void 0
1366
+ });
1367
+ ctx.injectFile({
1368
+ baseName: "standardSchema.ts",
1369
+ path: node_path.default.resolve(root, ".kubb/standardSchema.ts"),
1370
+ copy: standardSchemaTemplatePath
1371
+ });
1372
+ } }
1373
+ };
1374
+ });
1375
+ //#endregion
1376
+ exports.clientGenerator = clientGenerator;
1377
+ exports.default = pluginFetch;
1378
+ exports.pluginFetch = pluginFetch;
1379
+ exports.pluginFetchName = pluginFetchName;
1380
+
1381
+ //# sourceMappingURL=index.cjs.map