@kubb/plugin-ky 0.0.0-stage → 0.0.0

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.
@@ -0,0 +1,300 @@
1
+ # Server-sent events
2
+
3
+ Consume typed server-sent events and JSON Lines with the generated Ky client. Stop, resume, and handle streaming errors.
4
+
5
+ Kubb types the items from the OpenAPI document, and `.kubb/sse.ts` parses events as the WHATWG event stream specification does.
6
+
7
+ ## How Kubb detects a stream
8
+
9
+ Kubb generates a stream call when the success response declares only a stream content type:
10
+
11
+ | The success response declares | Each item |
12
+ | ------------------------------------------------------------------------------------------ | ---------------------------------------------- |
13
+ | `text/event-stream`, and the item schema declares `event` or `data` | `TypedEvent<Item>`, narrowed by `event.event` |
14
+ | `text/event-stream`, with any other item schema | `ServerSentEvent<Item>`, with `Item` in `data` |
15
+ | `application/jsonl`, `application/x-ndjson`, `application/json-seq`, or a `+json-seq` type | `Item`, one per line |
16
+
17
+ With `text/event-stream` next to another content type, Kubb generates a normal call instead. See [JSON or an event stream](#json-or-an-event-stream).
18
+
19
+ The item schema is `itemSchema` in OpenAPI 3.2. In OpenAPI 3.0 and 3.1, `schema` describes one event or one line:
20
+
21
+ ::code-group
22
+
23
+ ```yaml [Typed events]
24
+ /chat:
25
+ post:
26
+ operationId: streamChat
27
+ responses:
28
+ '200':
29
+ description: One event per oneOf member
30
+ content:
31
+ text/event-stream:
32
+ itemSchema:
33
+ type: object
34
+ required: [event]
35
+ properties:
36
+ event: { type: string }
37
+ id: { type: string }
38
+ retry: { type: integer, minimum: 0 }
39
+ oneOf:
40
+ - type: object
41
+ required: [event, data]
42
+ properties:
43
+ event: { type: string, const: message_delta }
44
+ data: { $ref: '#/components/schemas/MessageDelta' }
45
+ - type: object
46
+ required: [event]
47
+ properties:
48
+ event: { type: string, const: ping }
49
+ data: { type: string }
50
+ ```
51
+
52
+ ```yaml [Payload only]
53
+ /pet/{petId}/events:
54
+ get:
55
+ operationId: streamPetEvents
56
+ responses:
57
+ '200':
58
+ description: One PetEvent per event
59
+ content:
60
+ text/event-stream:
61
+ schema: { type: string } # the whole stream, for tools that do not read itemSchema
62
+ itemSchema: { $ref: '#/components/schemas/PetEvent' }
63
+ ```
64
+
65
+ ```yaml [JSON Lines]
66
+ /logs:
67
+ get:
68
+ operationId: streamLogs
69
+ responses:
70
+ '200':
71
+ description: One LogEntry per line
72
+ content:
73
+ application/jsonl:
74
+ itemSchema: { $ref: '#/components/schemas/LogEntry' }
75
+ ```
76
+
77
+ ::
78
+
79
+ In OpenAPI 3.0 and 3.1, put the item schema on `schema` instead: the `PetEvent` reference for a payload, or the same `oneOf` with a `discriminator` on `event` for typed events.
80
+
81
+ ## The generated function
82
+
83
+ ```typescript
84
+ export function streamChat<ThrowOnError extends boolean = true>(
85
+ options: StreamOptions<StreamChatOptions, ThrowOnError> = {},
86
+ ): Unwrappable<StreamResult<StreamChatResponses, ThrowOnError, TypedEvent<SuccessOf<StreamChatResponses>>>>
87
+ ```
88
+
89
+ A `StreamResult` has the fields of a `RequestResult` for the first connection, plus `stream` and `lastEventId`. The result iterates its items, which are also in `stream` and `data`. With `returnType: 'data'`, the call resolves to the items.
90
+
91
+ Pass these stream options next to the request params:
92
+
93
+ | Option | What it does |
94
+ | -------------- | ---------------------------------------------------------------------------------------------- |
95
+ | `terminator` | Ends the stream when an event's `data`, or a JSON line, equals this value, such as `[DONE]`. |
96
+ | `transform` | Maps each Server-Sent Event before validation, for example to camelCase its keys. |
97
+ | `maxEventSize` | The most characters in one event or line. Default `16 * 1024 * 1024`. `Infinity` turns it off. |
98
+ | `signal` | An `AbortSignal` that ends the request and the loop. |
99
+
100
+ ## Consume items
101
+
102
+ ::code-group
103
+
104
+ ```typescript [Typed events]
105
+ import { streamChat } from './gen/clients/streamChat'
106
+
107
+ for await (const event of await streamChat({ body: { prompt: 'Hi' }, terminator: '[DONE]' })) {
108
+ switch (event.event) {
109
+ case 'message_delta':
110
+ render(event.data.text) // MessageDelta
111
+ break
112
+ case 'ping':
113
+ break
114
+ }
115
+ }
116
+ ```
117
+
118
+ ```typescript [Payload only]
119
+ import { streamPetEvents } from './gen/clients/streamPetEvents'
120
+
121
+ const { stream, response } = await streamPetEvents({ path: { petId: 1 } })
122
+ console.info(response.status) // 200
123
+
124
+ for await (const { data } of stream) console.info(data.type) // PetEvent
125
+ ```
126
+
127
+ ```typescript [JSON Lines]
128
+ import { streamLogs } from './gen/clients/streamLogs'
129
+
130
+ for await (const entry of await streamLogs()) console.info(entry.level, entry.message) // LogEntry
131
+ ```
132
+
133
+ ```typescript [returnType: 'data']
134
+ // with pluginKy({ returnType: 'data' })
135
+ const events = await streamPetEvents({ path: { petId: 1 } })
136
+
137
+ for await (const { data } of events) console.info(data.type)
138
+ ```
139
+
140
+ ::
141
+
142
+ An event the document does not declare reaches the `default` of your `switch`, so declare heartbeat and `error` events too. For event names, IDs, and JSON Lines limits, see [Event names, IDs, and JSON Lines](#event-names-ids-and-json-lines).
143
+
144
+ With `validator: 'zod'`, the validator checks each item: the whole event for typed events, `data` for a payload, and each line for JSON Lines. To keep going past a failing item, return `{ value }` from `onValidationError`:
145
+
146
+ ```typescript
147
+ const { stream } = await streamChat({ body, onValidationError: (error, { value }) => ({ value }) })
148
+ ```
149
+
150
+ ## Stop, abort, and resume
151
+
152
+ - `break` out of the loop to stop. The runtime cancels the reader and releases the connection.
153
+ - Pass `signal` to stop from outside. The call or the loop rejects with the signal's reason.
154
+ - A dropped connection ends the loop with the transport's error. The runtime does not reconnect, so the retry policy is up to your app.
155
+
156
+ To resume, send a new call with a `Last-Event-ID` header. `lastEventId` is the `id` of the last event the server completed. Declare `Last-Event-ID` as a header parameter, so the call accepts it in `headers`:
157
+
158
+ ```typescript
159
+ import { ResponseError } from './gen/.kubb/client'
160
+ import { ParseError } from './gen/.kubb/standardSchema'
161
+
162
+ async function* resumeChat(attempts = 3) {
163
+ let lastEventId = ''
164
+
165
+ for (let attempt = 1; ; attempt++) {
166
+ try {
167
+ const result = await streamChat({ body, headers: lastEventId ? { 'Last-Event-ID': lastEventId } : {} })
168
+ for await (const event of result) {
169
+ lastEventId = result.lastEventId
170
+ yield event
171
+ }
172
+ return
173
+ } catch (error) {
174
+ if (attempt === attempts || ResponseError.is(error) || error instanceof ParseError) throw error
175
+ }
176
+ }
177
+ }
178
+
179
+ for await (const event of resumeChat()) render(event)
180
+ ```
181
+
182
+ The loop retries a failed connect and a dropped connection. It rethrows the last failure, so a cut stream never looks complete. It also rethrows a `ResponseError` and a `ParseError` at once, because a retry cannot fix them and would skip the failing event. Rethrow your abort reason the same way when you pass `signal`. An error from `render` is thrown outside the generator, so it is never retried.
183
+
184
+ For cleared IDs and resuming with `returnType: 'data'`, see [Event IDs when you resume](#event-ids-when-you-resume).
185
+
186
+ ## Handle errors
187
+
188
+ | What happens | Where it fails |
189
+ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
190
+ | Non-2xx response | The call throws a `ResponseError`. |
191
+ | Non-2xx response with `throwOnError: false` | The call resolves with `status` and `error`. `data` is `undefined`, and the stream yields nothing. |
192
+ | 2xx response whose body is not a stream, such as JSON | The call throws a `TypeError` with the body as its `cause`. |
193
+ | 2xx response with an empty body | No error. The stream is empty. |
194
+ | Dropped connection or abort | The loop throws. |
195
+ | An item fails its schema | The loop throws a `ParseError`, unless `onValidationError` returns `{ value }`. |
196
+ | An event is larger than `maxEventSize` | The loop throws a `RangeError`. |
197
+ | A JSON line is not valid JSON | The loop throws a `SyntaxError`. |
198
+
199
+ ```typescript
200
+ const result = await streamChat({ body, throwOnError: false })
201
+
202
+ if (!result.data) console.error('stream rejected', result.status, result.error)
203
+ else for await (const event of result.data) render(event)
204
+ ```
205
+
206
+ An error thrown from the loop skips `client.interceptors.error`. `.unwrap()` resolves to the items, as on a regular call.
207
+
208
+ ## JSON or an event stream
209
+
210
+ When the success response declares `text/event-stream` next to another type, such as `application/json`, Kubb generates a normal call that sends `Accept: text/event-stream`. Pass `contentType: { response: 'application/json' }` to ask for JSON. When the server streams, `data` is the raw `ReadableStream<Uint8Array>`, so read it with `parseEventStream`, or `parseJsonLines({ stream })` for JSON Lines:
211
+
212
+ ```typescript
213
+ import { parseEventStream } from './gen/.kubb/client'
214
+
215
+ const result = await getRecentChanges({ signal })
216
+
217
+ if (result.contentType === 'text/event-stream') {
218
+ for await (const { data } of parseEventStream(result.data)) render(data)
219
+ } else {
220
+ render(result.data) // the JSON body
221
+ }
222
+ ```
223
+
224
+ ## Stream with the client
225
+
226
+ `client.stream(config)` sends a stream request by hand. It runs the same interceptors and transport as `client(config)`, and validates each item with `validator.response`. Type it with the responses record, `ThrowOnError`, and the item type:
227
+
228
+ ```typescript
229
+ import { client, type SuccessOf } from './gen/.kubb/client'
230
+ import type { StreamLogsResponses } from './gen/types/StreamLogs'
231
+
232
+ const result = await client.stream<StreamLogsResponses, true, SuccessOf<StreamLogsResponses>>({
233
+ method: 'GET',
234
+ url: '/logs',
235
+ contentType: { response: 'application/jsonl' },
236
+ })
237
+ ```
238
+
239
+ Without `contentType.response` or an `Accept` header, `client.stream` sends `Accept: text/event-stream`.
240
+
241
+ The item type defaults to `ServerSentEvent` around the success body. To stream another format, register a `stream` handler, as [Add a media type](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/serialization#add-a-media-type) shows.
242
+
243
+ Import the stream helpers and types from `.kubb/client`, and do not edit the `.kubb/` files: Kubb rewrites them on each run.
244
+
245
+ ## Less common cases
246
+
247
+ ### JSON in a `data` string
248
+
249
+ When an event's `data` is a string with `contentMediaType: application/json` and a `contentSchema`, Kubb types and parses it as that schema. See [How Kubb detects a stream](#how-kubb-detects-a-stream) for the item schemas.
250
+
251
+ ### Stream result types
252
+
253
+ When you type a variable that holds a stream result, the type depends on the response and on `returnType`:
254
+
255
+ | Setting | The call returns |
256
+ | ------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
257
+ | Default | `Unwrappable<StreamResult<…>>` |
258
+ | The response declares headers | `Unwrappable<StreamResultWithHeaders<…>>`, so `headers.get` suggests their names |
259
+ | `returnType: 'data'` | `Promise<UnwrappedStreamResult<…>>`: the items, or the full result with `throwOnError: false` |
260
+ | `returnType: 'data'`, and the response declares headers | `Promise<UnwrappedStreamResultWithHeaders<…>>` |
261
+
262
+ [The generated function](#the-generated-function) shows the default signature.
263
+
264
+ ### Stream options Kubb sets
265
+
266
+ When you call [`client.stream`](#stream-with-the-client) yourself, pass the options a generated stream call gets from the document:
267
+
268
+ | Option | What it does |
269
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
270
+ | `eventShape` | Whether the validator checks the whole event (`'event'`) or its `data` (`'data'`). |
271
+ | `rawData` | Keeps `data` as text, for every event or for a list of event names. Kubb sets it when the document types `data` as a string. Otherwise `data` is parsed as JSON when it parses. |
272
+
273
+ ### Event names, IDs, and JSON Lines
274
+
275
+ When the server leaves a field out of an event, or sends JSON Lines:
276
+
277
+ - An event takes `message` as its name when the server sends none.
278
+ - The `id` carries over to later events, and `retry` holds the server's reconnect hint.
279
+ - A JSON Lines stream has no event IDs, and `transform` does not apply to it.
280
+ - An `application/json-seq` record must fit on one line.
281
+
282
+ ### Event IDs when you resume
283
+
284
+ When you [resume a stream](#stop-abort-and-resume):
285
+
286
+ - The runtime does not reconnect, because many streams end on purpose and the retry policy belongs to your app.
287
+ - `lastEventId` is empty until the server sends an `id`, and an empty `id:` clears it.
288
+ - The resume loop copies `lastEventId` after each event, so after a clear it sends no `Last-Event-ID`. A connection that drops before its first event keeps the ID from the connection before.
289
+ - With `returnType: 'data'`, the items alone carry no `lastEventId`, so pass `throwOnError: false` to get the full result.
290
+
291
+ ### Interceptors on a stream call
292
+
293
+ When a response interceptor runs on a stream call, `data` in its `DecodedResponse` is the raw body stream. See [Add interceptors](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/configure-requests#add-interceptors).
294
+
295
+ ### Stream runtime files
296
+
297
+ When you look for a stream helper or type, import it from `.kubb/client`:
298
+
299
+ - `.kubb/sse.ts` holds `parseEventStream`, `parseJsonLines`, and the stream media types, and `.kubb/client.ts` re-exports it.
300
+ - The stream types, such as `ServerSentEvent`, `TypedEvent`, `StreamOptions`, and `StreamResult`, live in `.kubb/core.ts`.
@@ -0,0 +1,92 @@
1
+ # Use a custom transport
2
+
3
+ Send the generated client through your own Ky instance, or replace the network send with your own function.
4
+
5
+ The client still builds the URL, serializes parameters, resolves auth, runs interceptors, and decodes the result. `client.interceptors` handlers keep running, whatever the transport.
6
+
7
+ ## Write a transport function
8
+
9
+ A transport gets the resolved request and returns a web `Response` with its body unread:
10
+
11
+ ```typescript
12
+ type Transport = (request: ResolvedRequest) => Promise<Response | TransportResult>
13
+
14
+ type ResolvedRequest = {
15
+ url: string // built, with the query
16
+ method: string
17
+ headers: Record<string, string> // auth headers included
18
+ body?: RequestBody // already encoded
19
+ signal?: AbortSignal
20
+ credentials?: RequestCredentials
21
+ options?: NativeOptions // Ky options
22
+ stream?: boolean // the call streams the response, so do not buffer the body
23
+ }
24
+
25
+ type TransportResult = { webResponse: Response; request: Request; response: Response }
26
+ ```
27
+
28
+ Return a `TransportResult` to set the native `request` and `response` that results and errors carry. See [Results from a plain `Response`](#results-from-a-plain-response).
29
+
30
+ ## Use your own Ky instance
31
+
32
+ `createKyTransport` sends through a Ky instance and keeps its defaults and hooks:
33
+
34
+ ```typescript
35
+ import ky from 'ky'
36
+ import { client, createKyTransport } from './gen/.kubb/client'
37
+
38
+ const instance = ky.create({ timeout: 5000, hooks: { beforeRequest: [({ request }) => request.headers.set('traceparent', currentTraceparent())] } })
39
+
40
+ client.setConfig({ transport: createKyTransport(instance) })
41
+ ```
42
+
43
+ > [!NOTE]
44
+ > Leave `prefix`, `baseUrl`, `json`, and `searchParams` off the instance, and set the base URL with [`baseURL`](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/configure-requests#set-the-base-url). The transport sets `throwHttpErrors: false`. Your instance keeps Ky's own `retry` default of 2, so pass `retry: 0` to `ky.create` to send each call once, as the default client does.
45
+
46
+ ## Wrap the default transport
47
+
48
+ `defaultTransport` is the Ky send the client uses when no transport is set. Wrap it to add tracing, timing, or headers:
49
+
50
+ ```typescript
51
+ import { client, defaultTransport } from './gen/.kubb/client'
52
+
53
+ client.setConfig({
54
+ transport: (request) => withSpan(request, () => defaultTransport(request)),
55
+ })
56
+ ```
57
+
58
+ ## Mock the network in tests
59
+
60
+ Return a fixed `Response` from a separate client, and pass it to the call or to a query plugin:
61
+
62
+ ```typescript
63
+ import { createClient } from './gen/.kubb/client'
64
+ import { getPetById } from './gen/clients/getPetById'
65
+
66
+ const testClient = createClient({ transport: async () => Response.json({ id: 1, name: 'Fluffy' }) })
67
+
68
+ const { data } = await getPetById({ path: { petId: 1 }, client: testClient })
69
+ // ^ { id: 1, name: 'Fluffy' }
70
+ ```
71
+
72
+ ## Where to set it
73
+
74
+ | Scope | How |
75
+ | ----------------- | --------------------------------- |
76
+ | Every call | `client.setConfig({ transport })` |
77
+ | A separate client | `createClient({ transport })` |
78
+ | One call | `transport` on the call |
79
+
80
+ A client from `createClient()` copies the shared `transport` at creation, so a later `client.setConfig({ transport })` does not reach it. Without a `transport`, it sends with `ky`.
81
+
82
+ ## Less common cases
83
+
84
+ ### Results from a plain `Response`
85
+
86
+ The default transport and `createKyTransport` return a plain `Response`, so `request` on a result or an error lacks the headers that instance defaults or Ky hooks add.
87
+
88
+ When a transport returns a plain `Response`, results and errors carry it as `response`. Their `request` is a `Request` built from the resolved request without its body, or the resolved request itself when `Request` cannot parse the URL, such as a relative URL in Node.js. Return a `TransportResult` to set both, as [Write a transport function](#write-a-transport-function) shows.
89
+
90
+ ### What Ky's timeout covers
91
+
92
+ Ky's `timeout` only waits for the response headers and never ends a started body or stream. To bound the whole call, pass `signal: AbortSignal.timeout(ms)`.
@@ -0,0 +1,209 @@
1
+ # Options
2
+
3
+ Pass these options to `pluginKy()`. Shared options link to [Shared plugin options](https://kubb.dev/docs/5.x/reference/plugin-options).
4
+
5
+ ## Options overview
6
+
7
+ | Option | Purpose | Default |
8
+ | ------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------ |
9
+ | [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written. | `{ path: 'clients', barrel: { type: 'named' } }` |
10
+ | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path. | None |
11
+ | [`baseURL`](#baseurl) | Base URL the client starts with. | None |
12
+ | [`throwOnErrorDefault`](#throwonerrordefault) | Throw on a non-2xx response unless a call says otherwise. | `true` |
13
+ | [`validator`](#validator) | Validate requests and responses with Zod. | `false` |
14
+ | [`auth`](#auth) | How generated functions take `auth`. | None |
15
+ | [`auth.mode`](#auth) | Optional `auth`, or required when a token is needed. | `'optional'` |
16
+ | [`returnType`](#returntype) | What a call resolves to. | `'full'` |
17
+ | [`sdk`](#sdk) | Generate classes instead of standalone functions. | None |
18
+ | [`sdk.mode`](#sdk) | One class per tag, or one class with every operation. | `'tag'` |
19
+ | [`sdk.name`](#sdk) | Name and file of the root or flat class. | None, or `'sdk'` with `mode: 'flat'` |
20
+ | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
21
+ | [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
22
+ | [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Options per pattern, except `throwOnErrorDefault`. | `[]` |
23
+ | [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver) | Generated names and paths, plus the [SDK names](#resolver). | `resolverClient` |
24
+ | [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]`, run after the built-in client macros |
25
+
26
+ ## Option details
27
+
28
+ ### baseURL
29
+
30
+ The base URL the client starts with. `client.setConfig({ baseURL })` replaces it at runtime.
31
+
32
+ | | |
33
+ | -------- | -------- |
34
+ | Type | `string` |
35
+ | Required | `false` |
36
+
37
+ A `${...}` interpolation becomes a template literal, so it reads the environment at runtime:
38
+
39
+ ```typescript
40
+ pluginKy({ baseURL: '${process.env.API_URL}' })
41
+ ```
42
+
43
+ > [!NOTE]
44
+ > The spec's top-level `servers` URL is never used. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/configure-requests#set-the-base-url).
45
+
46
+ ### throwOnErrorDefault
47
+
48
+ The `throwOnError` a generated function or SDK method uses when the call leaves it out. Neither `override` nor `client.setConfig({ throwOnError })` changes it. Query hooks always pass `throwOnError: true`.
49
+
50
+ | | |
51
+ | -------- | --------- |
52
+ | Type | `boolean` |
53
+ | Required | `false` |
54
+ | Default | `true` |
55
+
56
+ ```typescript
57
+ // with pluginKy({ throwOnErrorDefault: false })
58
+ const result = await getPetById({ path: { petId: 1 } })
59
+ if (result.error !== undefined) console.error(result.status, result.error)
60
+ ```
61
+
62
+ ### validator
63
+
64
+ Checks requests and responses against the schemas of `@kubb/plugin-zod`, so add `pluginZod()` too. A value that fails its schema throws a `ParseError`.
65
+
66
+ | | |
67
+ | -------- | ------------------------------------------------------------------------- |
68
+ | Type | `false \| 'zod' \| { request?: 'zod'; params?: 'zod'; response?: 'zod' }` |
69
+ | Required | `false` |
70
+ | Default | `false` |
71
+
72
+ ::field-group
73
+
74
+ :::field{name="false"}
75
+ Default value. No validation. The response is cast to the generated type.
76
+ :::
77
+
78
+ :::field{name="'zod'"}
79
+ Validates the success body, and an error body against the schema of its status.
80
+ :::
81
+
82
+ :::field{name="{ request?: 'zod', params?: 'zod', response?: 'zod' }"}
83
+ Opts in per part. `request` checks the body and `params` the path, query, header, and cookie params before the send. `response` works as `'zod'`.
84
+ :::
85
+
86
+ ::
87
+
88
+ ```typescript [kubb.config.ts]
89
+ import { defineConfig } from 'kubb/config'
90
+ import { pluginTs } from '@kubb/plugin-ts'
91
+ import { pluginZod } from '@kubb/plugin-zod'
92
+ import { pluginKy } from '@kubb/plugin-ky'
93
+
94
+ export default defineConfig({
95
+ input: './petStore.yaml',
96
+ output: { path: './src/gen' },
97
+ plugins: [pluginTs(), pluginZod(), pluginKy({ validator: { request: 'zod', params: 'zod', response: 'zod' } })],
98
+ })
99
+ ```
100
+
101
+ See [Turn validation off at runtime](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/error-handling#turn-validation-off-at-runtime) and [Parameter validation](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/serialization#parameter-validation).
102
+
103
+ ### auth
104
+
105
+ Sets how generated functions take the `auth` option.
106
+
107
+ | | |
108
+ | -------- | ------------------------------------- |
109
+ | Type | `{ mode?: 'optional' \| 'required' }` |
110
+ | Required | `false` |
111
+
112
+ ::field-group
113
+
114
+ :::field{name="mode: 'optional'"}
115
+ Default value. Every generated function takes `auth` as an optional option. Use it when `client.setConfig({ auth })` supplies the token, and with the query-hook plugins, which pass a partial config to the function.
116
+ :::
117
+
118
+ :::field{name="mode: 'required'"}
119
+ A generated function whose operation needs a security scheme takes `auth` as a required option, so a missing token fails at compile time. An operation without `security`, or one that allows `{}` (anonymous access), keeps `auth` optional.
120
+ :::
121
+
122
+ ::
123
+
124
+ SDK classes take `auth` in their constructor and ignore this option.
125
+
126
+ ```ts
127
+ // with pluginKy({ auth: { mode: 'required' } })
128
+ await addPet({ body, auth: () => getToken() })
129
+ await addPet({ body }) // Type error: `auth` is missing
130
+ ```
131
+
132
+ ### returnType
133
+
134
+ What a generated function or SDK method resolves to. The query plugins and `@kubb/plugin-mcp` read it too.
135
+
136
+ | | |
137
+ | -------- | ------------------ |
138
+ | Type | `'full' \| 'data'` |
139
+ | Required | `false` |
140
+ | Default | `'full'` |
141
+
142
+ ::field-group
143
+
144
+ :::field{name="'full'"}
145
+ Default value. The full result: `{ status, data, error, contentType, headers, request, response }`.
146
+ :::
147
+
148
+ :::field{name="'data'"}
149
+ The success body. With `throwOnError: false`, the full result, so the caller can tell an error from a success.
150
+ :::
151
+
152
+ ::
153
+
154
+ ```typescript
155
+ pluginKy({ returnType: 'data' })
156
+
157
+ const pet = await getPetById({ path: { petId: 1 } }) // Pet, not { status, data, ... }
158
+ ```
159
+
160
+ See [Read headers with `returnType: 'data'`](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/error-handling#read-headers-with-returntype-data).
161
+
162
+ ### sdk
163
+
164
+ Generates classes instead of standalone functions. Each instance builds its own client from its config, so two environments are two instances.
165
+
166
+ | | |
167
+ | -------- | ------------------------------------------- |
168
+ | Type | `{ mode?: 'tag' \| 'flat'; name?: string }` |
169
+ | Required | `false` |
170
+
171
+ ::field-group
172
+
173
+ :::field{name="mode: 'tag'"}
174
+ Default value. One class per tag, such as `PetClient`. With `name`, a root class also shares one client with every tag: `new PetStore(config).pet.getPetById(...)`. Throws [`KUBB_INVALID_PLUGIN_OPTIONS`](https://kubb.dev/docs/5.x/reference/diagnostics#kubb-invalid-plugin-options) with single-file output.
175
+ :::
176
+
177
+ :::field{name="mode: 'flat'"}
178
+ One class named by `name`, with every operation as a method. Without `name`, the class is `Sdk` in `sdk.ts`. Works with single-file output.
179
+ :::
180
+
181
+ ::
182
+
183
+ Methods take the same options and return the same result as the standalone functions. Interceptors on the root class's `client` reach every tag:
184
+
185
+ ```typescript
186
+ const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
187
+ api.client.interceptors.request.use((request) => request)
188
+ await api.pet.getPetById({ path: { petId: 1 } })
189
+
190
+ const pets = new PetClient(api.client) // a tag class also accepts an existing client
191
+ ```
192
+
193
+ > [!WARNING]
194
+ > The query plugins and `@kubb/plugin-mcp` call the standalone functions, so leave `sdk` unset for them.
195
+
196
+ ### resolver
197
+
198
+ Adds three members to the shared [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver). Members you leave out keep `resolverClient`.
199
+
200
+ | | |
201
+ | -------- | ------------------------------- |
202
+ | Type | `ResolverPatch<ResolverClient>` |
203
+ | Required | `false` |
204
+
205
+ | Member | Names | Example |
206
+ | -------------------- | --------------------------------------------------------------------- | ------------------------------------ |
207
+ | `className(name)` | The root class, the flat class, and the class of untagged operations. | `className('petStore')` → `PetStore` |
208
+ | `groupName(name)` | A tag class. | `groupName('pet')` → `PetClient` |
209
+ | `propertyName(name)` | The field a tag class has on the root class. | `propertyName('pet')` → `pet` |
@@ -0,0 +1,60 @@
1
+ # Ky
2
+
3
+ Generates one typed async function per OpenAPI operation that sends the request with [Ky](https://github.com/sindresorhus/ky) and returns a result keyed by status code.
4
+
5
+ Each function takes grouped `path`, `query`, `headers`, `cookies`, and `body` options, plus Ky options such as `retry`, `timeout`, and `hooks`. The query plugins and `@kubb/plugin-mcp` call these functions. The runtime is copied into `.kubb/`, so the generated code imports only `ky`.
6
+
7
+ ## Setup
8
+
9
+ - Add `@kubb/plugin-ts` for the operation types, or `@kubb/plugin-zod` with `inferred: true`.
10
+ - Add `@kubb/plugin-zod` and install `zod` v4 when you set `validator`. Generation fails without the plugin.
11
+ - Install `ky` 2.0 or a later 2.x release in the app that runs the generated code.
12
+
13
+ ## Options worth knowing
14
+
15
+ | Option | Set it to |
16
+ | --------------------- | ------------------------------------------------------------------------------------------ |
17
+ | `baseURL` | The starting host. The spec's top-level `servers` URL is not used. |
18
+ | `validator` | `'zod'` to check response bodies, or `{ request, params, response }` per part. |
19
+ | `throwOnErrorDefault` | `false` to return non-2xx responses as values. |
20
+ | `returnType` | `'data'` to resolve to the success body instead of the full result. |
21
+ | `sdk` | Classes instead of functions. Leave it unset for the query plugins and `@kubb/plugin-mcp`. |
22
+
23
+ Next, [call operations](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/calling-operations), or see every option and its default in [Options](https://kubb.dev/extensions/kubb-labs/plugin-ky/options).
24
+
25
+ ## Example
26
+
27
+ ::code-group
28
+
29
+ ```typescript [kubb.config.ts]
30
+ import { defineConfig } from 'kubb/config'
31
+ import { adapterOas } from '@kubb/adapter-oas'
32
+ import { pluginTs } from '@kubb/plugin-ts'
33
+ import { pluginKy } from '@kubb/plugin-ky'
34
+
35
+ export default defineConfig({
36
+ input: './petStore.yaml',
37
+ output: { path: './src/gen' },
38
+ adapter: adapterOas({ integerType: 'number' }),
39
+ plugins: [pluginTs(), pluginKy({ baseURL: 'https://petstore.swagger.io/v2' })],
40
+ })
41
+ ```
42
+
43
+ ```typescript [src/app.ts]
44
+ import { getPetById } from './gen/clients/getPetById'
45
+
46
+ const { data } = await getPetById({ path: { petId: 1 } })
47
+ ```
48
+
49
+ ```text [Generated files]
50
+ src/gen/
51
+ ├── .kubb/ # the runtime: client.ts, core.ts, config.ts, serializers/, ...
52
+ ├── clients/
53
+ │ ├── getPetById.ts
54
+ │ └── index.ts
55
+ └── types/
56
+ ```
57
+
58
+ ::
59
+
60
+ With [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype), an `int64` id such as `petId` is a `number`. With the default `bigint`, pass `1n`.