@kubb/plugin-fetch 5.13.0-canary.20261105T105941 → 5.13.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.
@@ -1,481 +1,2 @@
1
- export type HeaderValue = string | number | boolean | null | undefined | object
2
- export type HeadersInit = Array<[string, HeaderValue]> | Record<string, HeaderValue>
3
-
4
- /**
5
- * The request body type `fetch` accepts, derived from `RequestInit` instead of the global `BodyInit`
6
- * name, which a Node-only project (`@types/node` without the `dom` lib) does not declare.
7
- */
8
- export type RequestBody = NonNullable<RequestInit['body']>
9
-
10
- /**
11
- * The OpenAPI query-parameter serialization style. `form` is the default; `spaceDelimited` and
12
- * `pipeDelimited` join arrays with a space or pipe, and `deepObject` renders objects as
13
- * `key[prop]=value`.
14
- */
15
- export type QueryStyle = 'form' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject'
16
-
17
- /**
18
- * The serialization metadata shared by the styled parameter locations: the OpenAPI `style` (typed per
19
- * location through `TStyle`), `explode`, and `allowReserved` (keeps RFC 3986 reserved characters
20
- * unencoded, used by query and request bodies).
21
- */
22
- export type SerializationStyle<TStyle = string> = {
23
- style?: TStyle
24
- explode?: boolean
25
- allowReserved?: boolean
26
- }
27
-
28
- /** The media type of a parameter described with `content`; JSON sends one JSON-encoded value. */
29
- export type ParamContentType = {
30
- contentType?: string
31
- }
32
-
33
- /**
34
- * The per-parameter query serialization metadata carried by the generated request.
35
- */
36
- export type QueryParamStyle = SerializationStyle<QueryStyle> & ParamContentType
37
-
38
- /**
39
- * Serializes the query object into a search string. The optional second argument carries the
40
- * per-parameter OpenAPI `style` / `explode` / `allowReserved` metadata; without it arrays explode
41
- * into repeated keys and nested objects use the `deepObject` style.
42
- */
43
- export type QuerySerializer = (params: Record<string, unknown>, options?: Record<string, QueryParamStyle>) => string
44
-
45
- /**
46
- * The per-parameter cookie serialization metadata carried by the generated request. Cookies use the
47
- * OpenAPI `form` style, so only `explode` is configurable.
48
- */
49
- export type CookieParamStyle = ParamContentType & {
50
- explode?: boolean
51
- }
52
-
53
- /**
54
- * The per-parameter header serialization metadata carried by the generated request. Headers use the
55
- * OpenAPI `simple` style, so only `explode` is configurable.
56
- *
57
- * @example
58
- * ```ts
59
- * // styles.header: { 'X-Ids': { explode: false } }, header [3, 4] -> 'X-Ids: 3,4'
60
- * // styles.header: { 'X-Filter': { explode: true } }, header { role: 'admin' } -> 'X-Filter: role=admin'
61
- * ```
62
- */
63
- export type HeaderParamStyle = ParamContentType & {
64
- explode?: boolean
65
- }
66
-
67
- /**
68
- * The per-property `encoding` metadata for an `application/x-www-form-urlencoded` or
69
- * `multipart/form-data` request body. `contentType` overrides the part's media type; `style` /
70
- * `explode` / `allowReserved` follow the OpenAPI query rules for urlencoded bodies.
71
- */
72
- export type BodyEncoding = SerializationStyle<QueryStyle> & {
73
- contentType?: string
74
- }
75
-
76
- /**
77
- * Serializes the request body. JSON by default; `FormData`, `URLSearchParams`, `Blob`,
78
- * `ArrayBuffer`, and string bodies pass through untouched. The optional `encoding` argument carries
79
- * the per-property OpenAPI `encoding` metadata for form bodies.
80
- */
81
- export type BodySerializer = (args: { body: unknown; contentType?: string; encoding?: Record<string, BodyEncoding> }) => RequestBody | undefined
82
-
83
- /**
84
- * The OpenAPI path-parameter serialization style. `simple` is the default and emits the bare value;
85
- * `label` prefixes a `.` and `matrix` prefixes a `;name=` segment.
86
- */
87
- export type PathStyle = 'simple' | 'label' | 'matrix'
88
-
89
- /**
90
- * The per-parameter serialization metadata carried by the generated request. `style` selects the
91
- * OpenAPI style and `explode` controls how arrays and objects expand.
92
- */
93
- export type PathParamStyle = SerializationStyle<PathStyle>
94
-
95
- /**
96
- * Serializes a single path parameter for interpolation into the URL, honoring the OpenAPI `style` /
97
- * `explode` passed as `options`. Defaults to `simple` style with `explode: false`: primitives are
98
- * URL-encoded, arrays join their members with commas, and objects flatten to `key,value` pairs.
99
- */
100
- export type PathSerializer = (args: { name: string; value: unknown; options?: PathParamStyle }) => string
101
-
102
- /**
103
- * The per-concern serializers, grouped so they can be set in one place and overridden per client or
104
- * per call. Each field falls back to the matching `default*Serializer` when omitted.
105
- */
106
- export type Serializers = {
107
- query?: QuerySerializer
108
- body?: BodySerializer
109
- path?: PathSerializer
110
- }
111
-
112
- /**
113
- * The per-parameter OpenAPI `style` / `explode` metadata a generated request carries, grouped by
114
- * location and keyed by parameter name. Mirrors the `serializer` grouping and feeds the default
115
- * serializers; `body` carries the form `encoding` for a urlencoded or multipart body.
116
- */
117
- export type Styles = {
118
- path?: Record<string, PathParamStyle>
119
- query?: Record<string, QueryParamStyle>
120
- header?: Record<string, HeaderParamStyle>
121
- cookie?: Record<string, CookieParamStyle>
122
- body?: Record<string, BodyEncoding>
123
- }
124
-
125
- function isFormBody(body: unknown): body is RequestBody {
126
- return (
127
- body instanceof FormData ||
128
- body instanceof URLSearchParams ||
129
- body instanceof Blob ||
130
- body instanceof ArrayBuffer ||
131
- ArrayBuffer.isView(body) ||
132
- typeof body === 'string'
133
- )
134
- }
135
-
136
- export function isDefaultJsonBody(body: unknown): boolean {
137
- return body !== undefined && body !== null && !isFormBody(body)
138
- }
139
-
140
- /**
141
- * Emits a `bigint` (`format: int64`) as a JSON number, which `JSON.stringify` refuses to do itself.
142
- * Past the safe-integer range it throws, so an id never goes out silently truncated.
143
- */
144
- function jsonReplacer(_key: string, value: unknown): unknown {
145
- if (typeof value !== 'bigint') return value
146
- if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)
147
- throw new TypeError(`Cannot serialize ${value}n as JSON without losing precision, register a serializer.body to send it another way.`)
148
- return Number(value)
149
- }
150
-
151
- function appendFormDataValue({ formData, key, value, contentType }: { formData: FormData; key: string; value: unknown; contentType?: string }): void {
152
- if (value === undefined || value === null) return
153
- if (value instanceof Blob) {
154
- formData.append(key, value)
155
- return
156
- }
157
- if (typeof value === 'object' && !(value instanceof Date)) {
158
- const json = JSON.stringify(value, jsonReplacer)
159
- // A part's media type can only be set by wrapping the value in a typed Blob.
160
- formData.append(key, contentType ? new Blob([json], { type: contentType }) : json)
161
- return
162
- }
163
- formData.append(key, toValue(value))
164
- }
165
-
166
- /**
167
- * Default body serializer: passes binary/form bodies through and JSON-serializes everything else.
168
- * For `multipart/form-data` plain objects become `FormData` and for
169
- * `application/x-www-form-urlencoded` they become `URLSearchParams`. When `encoding` is supplied each
170
- * urlencoded property follows its OpenAPI `style` / `explode` / `allowReserved`.
171
- *
172
- * @example
173
- * ```ts
174
- * defaultBodySerializer({ body: { name: 'odie' } }) // '{"name":"odie"}'
175
- * defaultBodySerializer({ body: { field: 'x' }, contentType: 'multipart/form-data' }) // FormData
176
- * defaultBodySerializer({ body: { tags: ['a', 'b'] }, contentType: 'application/x-www-form-urlencoded', encoding: { tags: { explode: false } } }) // 'tags=a,b'
177
- * defaultBodySerializer({ body: { meta: { a: 1 } }, contentType: 'multipart/form-data', encoding: { meta: { contentType: 'application/json' } } }) // FormData with a typed Blob part
178
- * ```
179
- */
180
- export const defaultBodySerializer: BodySerializer = ({ body, contentType, encoding }) => {
181
- if (body === undefined || body === null) return undefined
182
- if (typeof body === 'string' && isJsonMediaType(contentType)) return JSON.stringify(body)
183
- if (isFormBody(body)) return body as RequestBody
184
- const normalizedContentType = contentType?.toLowerCase()
185
- if (normalizedContentType?.includes('multipart/form-data')) {
186
- const formData = new FormData()
187
- for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
188
- const partContentType = encoding?.[key]?.contentType
189
- if (Array.isArray(value)) {
190
- for (const item of value) appendFormDataValue({ formData, key, value: item, contentType: partContentType })
191
- continue
192
- }
193
- appendFormDataValue({ formData, key, value, contentType: partContentType })
194
- }
195
- return formData
196
- }
197
- if (normalizedContentType?.includes('application/x-www-form-urlencoded')) {
198
- if (encoding) return serializeUrlencodedBody(body as Record<string, unknown>, encoding)
199
- return new URLSearchParams(serializeUrlencodedBody(body as Record<string, unknown>, {}))
200
- }
201
- return JSON.stringify(body, jsonReplacer)
202
- }
203
-
204
- function serializeUrlencodedBody(body: Record<string, unknown>, encoding: Record<string, BodyEncoding>): string {
205
- const parts: Array<string> = []
206
- for (const [key, value] of Object.entries(body)) {
207
- const propertyEncoding = encoding[key]
208
- parts.push(...(propertyEncoding ? serializeStyledQueryParam({ key, value, options: propertyEncoding }) : serializeDefaultQueryParam(key, value)))
209
- }
210
- return parts.join('&')
211
- }
212
-
213
- function isJsonMediaType(contentType: string | undefined): boolean {
214
- const type = contentType?.split(';')[0]?.trim().toLowerCase()
215
- return type === 'application/json' || !!type?.endsWith('+json')
216
- }
217
-
218
- function serializeCookie({ name, value, explode }: { name: string; value: unknown; explode: boolean }): string {
219
- if (Array.isArray(value)) {
220
- const items = value.filter(notNullish).map((item) => encodeURIComponent(toValue(item)))
221
- return explode ? items.map((item) => `${name}=${item}`).join('; ') : `${name}=${items.join(',')}`
222
- }
223
- if (isRecord(value)) {
224
- const entries = Object.entries(value).filter(([, item]) => notNullish(item))
225
- if (explode) return entries.map(([key, item]) => `${key}=${encodeURIComponent(toValue(item))}`).join('; ')
226
- return `${name}=${entries
227
- .flatMap(([key, item]) => [key, item])
228
- .map((item) => encodeURIComponent(toValue(item)))
229
- .join(',')}`
230
- }
231
- return `${name}=${encodeURIComponent(toValue(value))}`
232
- }
233
-
234
- /**
235
- * Serializes cookie parameters into a `Cookie` header value using the OpenAPI `form` style, joined
236
- * with `; `. Values are URL-encoded and `explode` is honored per parameter.
237
- *
238
- * @example
239
- * ```ts
240
- * serializeCookies({ session: 'abc', ids: [1, 2] }) // 'session=abc; ids=1,2'
241
- * serializeCookies({ ids: [1, 2] }, { ids: { explode: true } }) // 'ids=1; ids=2'
242
- * ```
243
- */
244
- export function serializeCookies(cookies: Record<string, unknown>, styles?: Record<string, CookieParamStyle>): string {
245
- const parts: Array<string> = []
246
- for (const [name, value] of Object.entries(cookies)) {
247
- if (value === undefined || value === null) continue
248
- const style = styles?.[name]
249
- if (isJsonMediaType(style?.contentType)) {
250
- parts.push(`${name}=${encodeURIComponent(JSON.stringify(value, jsonReplacer))}`)
251
- continue
252
- }
253
- parts.push(serializeCookie({ name, value, explode: style?.explode ?? false }))
254
- }
255
- return parts.join('; ')
256
- }
257
-
258
- function appendQueryValue({ search, key, value }: { search: URLSearchParams; key: string; value: unknown }): void {
259
- if (value === undefined || value === null) return
260
- if (Array.isArray(value)) {
261
- for (const item of value) appendQueryValue({ search, key, value: item })
262
- return
263
- }
264
- if (isRecord(value)) {
265
- for (const [prop, propValue] of Object.entries(value)) {
266
- appendQueryValue({ search, key: `${key}[${prop}]`, value: propValue })
267
- }
268
- return
269
- }
270
- search.append(key, toValue(value))
271
- }
272
-
273
- const queryDelimiters: Record<QueryStyle, string> = { form: ',', spaceDelimited: '%20', pipeDelimited: '|', deepObject: ',' }
274
-
275
- function notNullish(value: unknown): boolean {
276
- return value !== undefined && value !== null
277
- }
278
-
279
- /**
280
- * Renders a primitive parameter value as a string, serializing `Date` to ISO-8601 so dates are
281
- * stable across path, query, cookie, and header locations rather than locale-dependent.
282
- */
283
- function toValue(value: unknown): string {
284
- return value instanceof Date ? value.toISOString() : String(value)
285
- }
286
-
287
- /**
288
- * Percent-encodes a value, keeping RFC 3986 reserved characters intact (used when `allowReserved` is set).
289
- */
290
- function encodeReserved(value: unknown): string {
291
- return encodeURI(toValue(value))
292
- }
293
-
294
- /**
295
- * Percent-encodes a value, escaping reserved characters (the default query/path encoder).
296
- */
297
- function encodeComponent(value: unknown): string {
298
- return encodeURIComponent(toValue(value))
299
- }
300
-
301
- /**
302
- * Whether a value should expand into bracketed/keyed parts. Arrays and `Date` are excluded so they
303
- * are serialized as a unit (a `Date` becomes an ISO string, not its enumerable own properties).
304
- */
305
- function isRecord(value: unknown): value is Record<string, unknown> {
306
- return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
307
- }
308
-
309
- /**
310
- * Expands an object or array into `deepObject` query parts, recursing into nested values so
311
- * `{ a: { b: { c: 1 } } }` becomes `a[b][c]=1`. Primitives terminate the recursion.
312
- */
313
- function serializeDeepObject({ key, value, encode }: { key: string; value: unknown; encode: (value: unknown) => string }): Array<string> {
314
- if (value === undefined || value === null) return []
315
- if (Array.isArray(value)) return value.flatMap((item, index) => serializeDeepObject({ key: `${key}[${index}]`, value: item, encode }))
316
- if (isRecord(value)) {
317
- return Object.entries(value)
318
- .filter(([, item]) => notNullish(item))
319
- .flatMap(([prop, item]) => serializeDeepObject({ key: `${key}[${prop}]`, value: item, encode }))
320
- }
321
- return [`${encode(key)}=${encode(value)}`]
322
- }
323
-
324
- function serializeStyledQueryArray({
325
- key,
326
- value,
327
- options,
328
- encode,
329
- }: {
330
- key: string
331
- value: Array<unknown>
332
- options: QueryParamStyle
333
- encode: (value: unknown) => string
334
- }): Array<string> {
335
- const items = value.filter(notNullish)
336
- if (options.explode ?? true) return items.map((item) => `${encode(key)}=${encode(item)}`)
337
- return [`${encode(key)}=${items.map(encode).join(queryDelimiters[options.style ?? 'form'])}`]
338
- }
339
-
340
- function serializeStyledQueryObject({
341
- key,
342
- value,
343
- options,
344
- encode,
345
- }: {
346
- key: string
347
- value: Record<string, unknown>
348
- options: QueryParamStyle
349
- encode: (value: unknown) => string
350
- }): Array<string> {
351
- if ((options.style ?? 'form') === 'deepObject') return serializeDeepObject({ key, value, encode })
352
- const entries = Object.entries(value).filter(([, item]) => notNullish(item))
353
- if (options.explode ?? true) return entries.map(([prop, item]) => `${encode(prop)}=${encode(item)}`)
354
- return [
355
- `${encode(key)}=${entries
356
- .flatMap(([prop, item]) => [prop, item])
357
- .map(encode)
358
- .join(',')}`,
359
- ]
360
- }
361
-
362
- function serializeStyledQueryParam({ key, value, options }: { key: string; value: unknown; options: QueryParamStyle }): Array<string> {
363
- if (value === undefined || value === null) return []
364
- const encode = options.allowReserved ? encodeReserved : encodeComponent
365
- if (Array.isArray(value)) return serializeStyledQueryArray({ key, value, options, encode })
366
- if (isRecord(value)) return serializeStyledQueryObject({ key, value, options, encode })
367
- return [`${encode(key)}=${encode(value)}`]
368
- }
369
-
370
- function serializeDefaultQueryParam(key: string, value: unknown): Array<string> {
371
- const search = new URLSearchParams()
372
- appendQueryValue({ search, key, value })
373
- const result = search.toString()
374
- return result ? [result] : []
375
- }
376
-
377
- /**
378
- * Default query serializer. Members with `options` metadata follow their OpenAPI `style` / `explode`
379
- * / `allowReserved`. Members without it keep the defaults: arrays explode into repeated keys and
380
- * nested objects use the `deepObject` style (`key[prop]=value`).
381
- *
382
- * @example
383
- * ```ts
384
- * defaultQuerySerializer({ id: [3, 4, 5] }) // 'id=3&id=4&id=5'
385
- * defaultQuerySerializer({ id: [3, 4, 5] }, { id: { style: 'form', explode: false } }) // 'id=3,4,5'
386
- * defaultQuerySerializer({ id: [3, 4, 5] }, { id: { style: 'spaceDelimited', explode: false } }) // 'id=3%204%205'
387
- * defaultQuerySerializer({ id: [3, 4, 5] }, { id: { style: 'pipeDelimited', explode: false } }) // 'id=3|4|5'
388
- * defaultQuerySerializer({ a: { b: 1 } }, { a: { style: 'deepObject' } }) // 'a%5Bb%5D=1'
389
- * defaultQuerySerializer({ a: { b: { c: 1 } } }, { a: { style: 'deepObject' } }) // 'a%5Bb%5D%5Bc%5D=1'
390
- * ```
391
- */
392
- export const defaultQuerySerializer: QuerySerializer = (params, options) => {
393
- const parts: Array<string> = []
394
- for (const [key, value] of Object.entries(params)) {
395
- const paramOptions = options?.[key]
396
- if (notNullish(value) && isJsonMediaType(paramOptions?.contentType)) {
397
- parts.push(`${encodeComponent(key)}=${encodeComponent(JSON.stringify(value, jsonReplacer))}`)
398
- continue
399
- }
400
- parts.push(...(paramOptions ? serializeStyledQueryParam({ key, value, options: paramOptions }) : serializeDefaultQueryParam(key, value)))
401
- }
402
- return parts.join('&')
403
- }
404
-
405
- function serializePathPrimitive({ name, value, style }: { name: string; value: unknown; style: PathStyle }): string {
406
- const encoded = encodeComponent(value)
407
- if (style === 'label') return `.${encoded}`
408
- if (style === 'matrix') return `;${name}=${encoded}`
409
- return encoded
410
- }
411
-
412
- function serializePathArray({ name, value, style, explode }: { name: string; value: Array<unknown>; style: PathStyle; explode: boolean }): string {
413
- const items = value.map(encodeComponent)
414
- if (style === 'label') return `.${items.join(explode ? '.' : ',')}`
415
- if (style === 'matrix') return explode ? items.map((item) => `;${name}=${item}`).join('') : `;${name}=${items.join(',')}`
416
- return items.join(',')
417
- }
418
-
419
- function serializePathObject({ name, value, style, explode }: { name: string; value: Record<string, unknown>; style: PathStyle; explode: boolean }): string {
420
- const members = Object.entries(value).map(([key, item]) =>
421
- explode ? `${encodeComponent(key)}=${encodeComponent(item)}` : `${encodeComponent(key)},${encodeComponent(item)}`,
422
- )
423
- if (style === 'label') return `.${members.join(explode ? '.' : ',')}`
424
- if (style === 'matrix') return explode ? members.map((member) => `;${member}`).join('') : `;${name}=${members.join(',')}`
425
- return members.join(',')
426
- }
427
-
428
- /**
429
- * Default path serializer honoring the OpenAPI `style` / `explode` metadata. Without metadata it
430
- * falls back to `simple` style with `explode: false`. Replaces the previous `String(value)`
431
- * interpolation, which emitted `[object Object]` for object path params.
432
- *
433
- * @example
434
- * ```ts
435
- * defaultPathSerializer({ name: 'id', value: [3, 4, 5] }) // '3,4,5'
436
- * defaultPathSerializer({ name: 'id', value: [3, 4, 5], options: { style: 'label', explode: true } }) // '.3.4.5'
437
- * defaultPathSerializer({ name: 'id', value: [3, 4, 5], options: { style: 'matrix', explode: true } }) // ';id=3;id=4;id=5'
438
- * defaultPathSerializer({ name: 'pt', value: { x: 1, y: 2 } }) // 'x,1,y,2'
439
- * ```
440
- */
441
- export const defaultPathSerializer: PathSerializer = ({ name, value, options }) => {
442
- if (value === undefined || value === null) return ''
443
- const style = options?.style ?? 'simple'
444
- const explode = options?.explode ?? false
445
- if (Array.isArray(value)) return serializePathArray({ name, value, style, explode })
446
- if (isRecord(value)) return serializePathObject({ name, value, style, explode })
447
- return serializePathPrimitive({ name, value, style })
448
- }
449
-
450
- function serializeHeaderValue(value: unknown, explode: boolean): string {
451
- if (Array.isArray(value)) return value.filter(notNullish).map(toValue).join(',')
452
- if (!isRecord(value)) return toValue(value)
453
- const entries = Object.entries(value).filter(([, item]) => notNullish(item))
454
- if (explode) return entries.map(([key, item]) => `${key}=${toValue(item)}`).join(',')
455
- return entries
456
- .flatMap(([key, item]) => [key, item])
457
- .map(toValue)
458
- .join(',')
459
- }
460
-
461
- /** Header values must be Latin-1, so non-ASCII characters become JSON `\uXXXX` escapes. */
462
- function toAsciiJson(value: unknown): string {
463
- return JSON.stringify(value, jsonReplacer).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
464
- }
465
-
466
- /**
467
- * Serializes array and object header parameters with the OpenAPI `simple` style before they are
468
- * merged. Header values are not URL-encoded. Primitive values and headers without metadata pass
469
- * through untouched.
470
- */
471
- export function applyHeaderStyles(headers: HeadersInit | undefined, styles: Record<string, HeaderParamStyle> | undefined): HeadersInit | undefined {
472
- if (!headers || !styles) return headers
473
- const entries = Array.isArray(headers) ? headers : Object.entries(headers)
474
- return entries.map(([key, value]) => {
475
- const style = styles[key]
476
- if (!style || value === undefined || value === null) return [key, value] as [string, HeaderValue]
477
- if (isJsonMediaType(style.contentType)) return [key, toAsciiJson(value)] as [string, HeaderValue]
478
- if (typeof value !== 'object') return [key, value] as [string, HeaderValue]
479
- return [key, serializeHeaderValue(value, style.explode ?? false)] as [string, HeaderValue]
480
- })
481
- }
1
+ // Resolves `./serializers.ts` for the client template next to it. The generator copies the file from `@kubb/plugin-client` into `.kubb/serializers.ts`.
2
+ export * from '@kubb/plugin-client/templates/serializers.ts'
@@ -1,109 +1,2 @@
1
- /**
2
- * A Standard Schema-compatible validator: a minimal duck-type covering Zod v3/v4, valibot, and
3
- * arktype schemas. Only the `~standard.validate` method is required at runtime.
4
- */
5
- export type StandardSchemaValidator<TOutput = unknown> = {
6
- readonly '~standard': {
7
- validate(value: unknown): StandardSchemaResult<TOutput> | Promise<StandardSchemaResult<TOutput>>
8
- }
9
- }
10
-
11
- /**
12
- * The two possible outcomes of a Standard Schema `validate` call. A successful result carries
13
- * `value`; a failed result carries `issues`.
14
- */
15
- export type StandardSchemaResult<TOutput> = { readonly value: TOutput; readonly issues?: undefined } | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
16
-
17
- /**
18
- * One validation issue from a Standard Schema `validate` call.
19
- */
20
- export type StandardSchemaIssue = {
21
- readonly message?: string
22
- readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>
23
- }
24
-
25
- /**
26
- * Thrown by `validateStandardSchema` when validation fails. Carries the raw `issues` array from
27
- * the schema's `validate` result so callers receive a uniform error shape regardless of which
28
- * schema library is in use.
29
- */
30
- export class ParseError extends Error {
31
- readonly issues: ReadonlyArray<StandardSchemaIssue>
32
-
33
- constructor({ issues, message }: { issues: ReadonlyArray<StandardSchemaIssue>; message?: string }) {
34
- super(message ?? 'Validation failed')
35
- this.name = 'ParseError'
36
- this.issues = issues
37
- }
38
- }
39
-
40
- /**
41
- * Validates `value` against a Standard Schema-compatible `schema`. Returns the parsed output on
42
- * success; throws `ParseError` with the schema's `issues` on failure. Handles both sync and async
43
- * `validate` implementations transparently.
44
- *
45
- * @example
46
- * const pet = await validateStandardSchema(PetSchema, rawData)
47
- */
48
- export async function validateStandardSchema<TOutput>(schema: StandardSchemaValidator<TOutput>, value: unknown): Promise<TOutput> {
49
- const result = await schema['~standard'].validate(value)
50
- if (result.issues) {
51
- throw new ParseError({ issues: result.issues })
52
- }
53
- return (result as { value: TOutput }).value
54
- }
55
-
56
- /**
57
- * Wraps an object schema so its keys match case-insensitively.
58
- * Keys the schema does not declare pass through untouched.
59
- * The declared keys are validated with `schema` under their declared names.
60
- * Every key, and every issue path, keeps the casing the caller used.
61
- *
62
- * @param schema Standard Schema-compatible object schema.
63
- * @param entries The record of keys the passed object schema validates.
64
- * @example
65
- * ```ts
66
- * validator: { headers: toHeadersStandardSchema(putEventHeadersSchema, putEventHeadersSchema.shape) }
67
- * ```
68
- */
69
- export function toHeadersStandardSchema(schema: StandardSchemaValidator, entries: Record<string, unknown>): StandardSchemaValidator {
70
- const declared = new Map(Object.keys(entries).map((name) => [name.toLowerCase(), name]))
71
-
72
- function validate(value: unknown): StandardSchemaResult<unknown> | Promise<StandardSchemaResult<unknown>> {
73
- if (typeof value !== 'object' || value === null) {
74
- return { issues: [{ message: 'Expected an object' }] }
75
- }
76
-
77
- const originalKeys = new Map<string, string>()
78
- const declaredValues: Record<string, unknown> = {}
79
- const undeclaredValues: Record<string, unknown> = {}
80
- for (const [key, entry] of Object.entries(value)) {
81
- const name = declared.get(key.toLowerCase())
82
- if (name === undefined) {
83
- undeclaredValues[key] = entry
84
- continue
85
- }
86
- originalKeys.set(name, key)
87
- declaredValues[name] = entry
88
- }
89
-
90
- const toOriginal = (key: string) => originalKeys.get(key) ?? key
91
- const settle = (result: StandardSchemaResult<unknown>): StandardSchemaResult<unknown> => {
92
- if (result.issues) {
93
- return {
94
- issues: result.issues.map((issue): StandardSchemaIssue => ({
95
- ...issue,
96
- path: issue.path?.map((segment, index) => (index === 0 && typeof segment === 'string' ? toOriginal(segment) : segment)),
97
- })),
98
- }
99
- }
100
- const validated = Object.entries((result.value ?? {}) as Record<string, unknown>).map(([key, entry]) => [toOriginal(key), entry])
101
- return { value: { ...undeclaredValues, ...Object.fromEntries(validated) } }
102
- }
103
-
104
- const result = schema['~standard'].validate(declaredValues)
105
- return result instanceof Promise ? result.then(settle) : settle(result)
106
- }
107
-
108
- return { '~standard': { validate } }
109
- }
1
+ // Resolves `./standardSchema.ts` for the client template next to it. The generator copies the file from `@kubb/plugin-client` into `.kubb/standardSchema.ts`.
2
+ export * from '@kubb/plugin-client/templates/standardSchema.ts'