@kubb/adapter-oas 5.0.0-beta.75 → 5.0.0-beta.76

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/src/refs.ts DELETED
@@ -1,59 +0,0 @@
1
- import { isReference } from './guards.ts'
2
- import type { Document } from './types.ts'
3
-
4
- /**
5
- * Resolves a local JSON pointer reference from a document.
6
- *
7
- * Accepts `#/...` refs. Returns `null` for empty or non-local refs.
8
- * Throws when the pointer cannot be resolved.
9
- *
10
- * @example
11
- * ```ts
12
- * resolveRef<SchemaObject>(document, '#/components/schemas/Pet') // SchemaObject | null
13
- * ```
14
- */
15
- export function resolveRef<T = unknown>(document: Document, $ref: string): T | null {
16
- const origRef = $ref
17
- $ref = $ref.trim()
18
- if ($ref === '') {
19
- return null
20
- }
21
- if ($ref.startsWith('#')) {
22
- $ref = globalThis.decodeURIComponent($ref.substring(1))
23
- } else {
24
- return null
25
- }
26
- const current = $ref
27
- .split('/')
28
- .filter(Boolean)
29
- .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)
30
-
31
- if (!current) {
32
- throw new Error(`Could not find a definition for ${origRef}.`)
33
- }
34
- return current as T
35
- }
36
-
37
- /**
38
- * Resolves a `$ref` object while preserving the original `$ref` field on the result.
39
- *
40
- * Useful for parser flows that need both dereferenced fields and pointer
41
- * identity (for naming/import purposes). Non-reference values are returned as-is.
42
- *
43
- * @example
44
- * ```ts
45
- * dereferenceWithRef(document, { $ref: '#/components/schemas/Pet' })
46
- * // { $ref: '#/components/schemas/Pet', type: 'object', properties: { ... } }
47
- * ```
48
- */
49
- export function dereferenceWithRef<T = unknown>(document: Document, schema?: T): T {
50
- if (isReference(schema)) {
51
- return {
52
- ...schema,
53
- ...resolveRef(document, schema.$ref),
54
- $ref: schema.$ref,
55
- }
56
- }
57
-
58
- return schema as T
59
- }
package/src/resolvers.ts DELETED
@@ -1,544 +0,0 @@
1
- import { pascalCase } from '@internals/utils'
2
- import { ast } from '@kubb/core'
3
- import type { ParameterObject, ServerObject } from 'oas/types'
4
- import { isRef } from 'oas/types'
5
- import { matchesMimeType } from 'oas/utils'
6
- import { formatMap, SCHEMA_REF_PREFIX, structuralKeys } from './constants.ts'
7
- import { isReference } from './guards.ts'
8
- import { dereferenceWithRef, resolveRef } from './refs.ts'
9
- import type { ContentType, Document, MediaTypeObject, Operation, ResponseObject, SchemaObject } from './types.ts'
10
-
11
- /**
12
- * Replaces `{variable}` placeholders in an OpenAPI server URL with provided values.
13
- * Resolution order: `overrides[key]` → `variable.default` → left unreplaced.
14
- * Throws if an override value is not in the variable's `enum` list.
15
- *
16
- * @example
17
- * ```ts
18
- * resolveServerUrl(
19
- * { url: 'https://{env}.api.example.com', variables: { env: { default: 'dev', enum: ['dev', 'prod'] } } },
20
- * { env: 'prod' },
21
- * )
22
- * // 'https://prod.api.example.com'
23
- * ```
24
- */
25
- export function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string {
26
- if (!server.variables) {
27
- return server.url
28
- }
29
-
30
- let url = server.url
31
- for (const [key, variable] of Object.entries(server.variables)) {
32
- const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : undefined)
33
- if (value === undefined) {
34
- continue
35
- }
36
-
37
- if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) {
38
- throw new Error(`Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`)
39
- }
40
-
41
- url = url.replaceAll(`{${key}}`, value)
42
- }
43
-
44
- return url
45
- }
46
-
47
- /**
48
- * Returns the Kubb `SchemaType` for a given OAS `format` string, or `null` if not found.
49
- * Formats not in `formatMap` (e.g., `int64`, `date-time`) are handled separately by parser options.
50
- */
51
- export function getSchemaType(format: string): ast.SchemaType | null {
52
- return formatMap[format as keyof typeof formatMap] ?? null
53
- }
54
-
55
- /**
56
- * Converts an OAS primitive type string to its `PrimitiveSchemaType` equivalent.
57
- * Numeric types (`number`, `integer`, `bigint`) pass through unchanged. `boolean` maps to `'boolean'`. Everything else becomes `'string'`.
58
- */
59
- export function getPrimitiveType(type: string | undefined): ast.PrimitiveSchemaType {
60
- if (type === 'number' || type === 'integer' || type === 'bigint') return type
61
- if (type === 'boolean') return 'boolean'
62
-
63
- return 'string'
64
- }
65
-
66
- /**
67
- * Narrows a content-type string to the `MediaType` union Kubb recognizes, or returns `null`.
68
- */
69
- export function getMediaType(contentType: string): ast.MediaType | null {
70
- return Object.values(ast.mediaTypes).includes(contentType as ast.MediaType) ? (contentType as ast.MediaType) : null
71
- }
72
-
73
- export type OperationsOptions = {
74
- contentType?: ContentType
75
- }
76
-
77
- /**
78
- * Returns all parameters for an operation, merging path-level and operation-level entries.
79
- * Operation-level parameters override path-level ones with the same `in:name` key.
80
- * `$ref` parameters resolve via `dereferenceWithRef` for backward compatibility.
81
- *
82
- * @example
83
- * ```ts
84
- * getParameters(document, operation)
85
- * // [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' } }]
86
- * ```
87
- */
88
- export function getParameters(document: Document, operation: Operation): Array<ParameterObject> {
89
- const resolveParams = (params: unknown[]): Array<ParameterObject> =>
90
- params.map((p) => dereferenceWithRef(document, p)).filter((p): p is ParameterObject => !!p && typeof p === 'object' && 'in' in p && 'name' in p)
91
-
92
- const operationParams = resolveParams(operation.schema?.parameters || [])
93
- const pathItem = document.paths?.[operation.path]
94
- const pathLevelParams = resolveParams(pathItem && !isReference(pathItem) && pathItem.parameters ? pathItem.parameters : [])
95
-
96
- const paramMap = new Map<string, ParameterObject>()
97
- for (const p of pathLevelParams) {
98
- if (p.name && p.in) {
99
- paramMap.set(`${p.in}:${p.name}`, p)
100
- }
101
- }
102
- for (const p of operationParams) {
103
- if (p.name && p.in) {
104
- paramMap.set(`${p.in}:${p.name}`, p)
105
- }
106
- }
107
-
108
- return Array.from(paramMap.values())
109
- }
110
-
111
- function getResponseBody(responseBody: boolean | ResponseObject, contentType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]] {
112
- if (!responseBody) return false
113
- if (isReference(responseBody)) return false
114
-
115
- const body = responseBody as ResponseObject
116
- if (!body.content) return false
117
-
118
- if (contentType) {
119
- if (!(contentType in body.content)) return false
120
- return body.content[contentType]!
121
- }
122
-
123
- let availableContentType: string | undefined
124
- const contentTypes = Object.keys(body.content)
125
- for (const mt of contentTypes) {
126
- if (matchesMimeType.json(mt)) {
127
- availableContentType = mt
128
- break
129
- }
130
- }
131
-
132
- if (!availableContentType) {
133
- availableContentType = contentTypes[0]
134
- }
135
-
136
- if (availableContentType) {
137
- return [availableContentType, body.content[availableContentType]!, ...(body.description ? [body.description] : [])]
138
- }
139
-
140
- return false
141
- }
142
-
143
- /**
144
- * Returns the response schema for a given operation and HTTP status code.
145
- *
146
- * Returns an empty object `{}` when no response body schema is available.
147
- *
148
- * @example
149
- * ```ts
150
- * getResponseSchema(document, operation, 200) // SchemaObject
151
- * getResponseSchema(document, operation, '4XX') // {}
152
- * ```
153
- */
154
- export function getResponseSchema(document: Document, operation: Operation, statusCode: string | number, options: OperationsOptions = {}): SchemaObject {
155
- if (operation.schema.responses) {
156
- const responses = operation.schema.responses
157
- for (const key in responses) {
158
- const schema = responses[key]
159
- if (schema && isReference(schema)) {
160
- responses[key] = resolveRef<any>(document, schema.$ref)
161
- }
162
- }
163
- }
164
-
165
- const responseBody = getResponseBody(operation.getResponseByStatusCode(statusCode), options.contentType)
166
-
167
- if (responseBody === false) {
168
- return {}
169
- }
170
-
171
- const schema = Array.isArray(responseBody) ? responseBody[1].schema : responseBody.schema
172
-
173
- if (!schema) {
174
- return {}
175
- }
176
-
177
- return dereferenceWithRef(document, schema)
178
- }
179
-
180
- /**
181
- * Returns the request body schema for an operation, or `null` when absent.
182
- *
183
- * @example
184
- * ```ts
185
- * getRequestSchema(document, operation) // SchemaObject | null
186
- * ```
187
- */
188
- export function getRequestSchema(document: Document, operation: Operation, options: OperationsOptions = {}): SchemaObject | null {
189
- if (operation.schema.requestBody) {
190
- operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)
191
- }
192
-
193
- const requestBody = operation.getRequestBody(options.contentType)
194
-
195
- if (requestBody === false) {
196
- return null
197
- }
198
-
199
- const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema
200
-
201
- if (!schema) {
202
- return null
203
- }
204
-
205
- return dereferenceWithRef(document, schema)
206
- }
207
-
208
- /**
209
- * The three component sections Kubb reads schemas from.
210
- */
211
- type SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'
212
-
213
- /**
214
- * A schema annotated with its component section source and original name. Used by `resolveNameCollisions` for cross-source collision resolution.
215
- */
216
- export type SchemaWithMetadata = {
217
- schema: SchemaObject
218
- source: SchemaSourceMode
219
- originalName: string
220
- }
221
-
222
- export type GetSchemasOptions = {
223
- contentType?: ContentType
224
- }
225
-
226
- export type GetSchemasResult = {
227
- schemas: Record<string, SchemaObject>
228
- nameMapping: Map<string, string>
229
- }
230
-
231
- /**
232
- * Flattens a keyword-only `allOf` into its parent schema.
233
- *
234
- * Only flattens when every member is a plain fragment — no `$ref` and no structural keywords
235
- * (see `structuralKeys`). Outer schema values take precedence over fragment values.
236
- * Returns `null` for a `null` input, and the original schema unchanged when flattening is unsafe.
237
- *
238
- * @example
239
- * ```ts
240
- * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })
241
- * // { type: 'object', properties: {}, description: 'A pet' }
242
- *
243
- * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })
244
- * // returned unchanged — contains a $ref
245
- * ```
246
- */
247
- /**
248
- * Returns `true` when `fragment` carries any JSON Schema keyword that makes it
249
- * structurally significant on its own (see `structuralKeys`).
250
- *
251
- * A fragment with a structural keyword can't be safely merged into a parent schema.
252
- */
253
- function hasStructuralKeywords(fragment: SchemaObject): boolean {
254
- for (const key in fragment) {
255
- if (structuralKeys.has(key as 'properties')) return true
256
- }
257
- return false
258
- }
259
-
260
- export function flattenSchema(schema: SchemaObject | null): SchemaObject | null {
261
- if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null
262
-
263
- const allOfFragments = schema.allOf as SchemaObject[]
264
- if (allOfFragments.some((item) => isRef(item))) return schema
265
- if (allOfFragments.some(hasStructuralKeywords)) return schema
266
-
267
- const merged: SchemaObject = { ...schema }
268
- delete merged.allOf
269
-
270
- for (const fragment of allOfFragments) {
271
- for (const [key, value] of Object.entries(fragment)) {
272
- if (merged[key as keyof typeof merged] === undefined) {
273
- merged[key as keyof typeof merged] = value
274
- }
275
- }
276
- }
277
-
278
- return merged
279
- }
280
-
281
- /**
282
- * Extracts the inline schema from a media-type `content` map.
283
- *
284
- * Prefers `preferredContentType` when given; otherwise uses the first key in the map.
285
- * Returns `null` when `content` is absent, the schema is missing, or the schema is a `$ref`.
286
- *
287
- * @example
288
- * ```ts
289
- * extractSchemaFromContent(operation.content, 'application/json')
290
- * // SchemaObject | null
291
- * ```
292
- */
293
- export function extractSchemaFromContent(content: Record<string, unknown> | undefined, preferredContentType?: ContentType): SchemaObject | null {
294
- if (!content) return null
295
-
296
- const firstContentType = Object.keys(content)[0] ?? 'application/json'
297
- const targetContentType = preferredContentType ?? firstContentType
298
- const contentSchema = content[targetContentType] as { schema?: SchemaObject } | undefined
299
- const schema = contentSchema?.schema
300
-
301
- if (schema && '$ref' in schema) return null
302
- return schema ?? null
303
- }
304
-
305
- /**
306
- * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.
307
- */
308
- function collectRefs(schema: unknown, refs = new Set<string>()): Set<string> {
309
- if (Array.isArray(schema)) {
310
- for (const item of schema) collectRefs(item, refs)
311
- return refs
312
- }
313
-
314
- if (schema && typeof schema === 'object') {
315
- for (const key in schema) {
316
- const value = (schema as Record<string, unknown>)[key]
317
- if (key === '$ref' && typeof value === 'string') {
318
- if (value.startsWith(SCHEMA_REF_PREFIX)) {
319
- const name = value.slice(SCHEMA_REF_PREFIX.length)
320
- if (name) refs.add(name)
321
- }
322
- } else {
323
- collectRefs(value, refs)
324
- }
325
- }
326
- }
327
-
328
- return refs
329
- }
330
-
331
- /**
332
- * Returns a copy of `schemas` topologically sorted by `$ref` dependency.
333
- *
334
- * Referenced schemas appear before the schemas that depend on them, so code generators
335
- * can emit types in the correct order. Cycles are silently skipped.
336
- *
337
- * @example
338
- * ```ts
339
- * const sorted = sortSchemas({ Order: orderSchema, Pet: petSchema })
340
- * // Pet appears before Order when Order.$ref points at Pet
341
- * ```
342
- */
343
- export function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {
344
- const deps = new Map<string, string[]>()
345
-
346
- for (const [name, schema] of Object.entries(schemas)) {
347
- deps.set(name, Array.from(collectRefs(schema)))
348
- }
349
-
350
- const sorted: string[] = []
351
- const visited = new Set<string>()
352
-
353
- function visit(name: string, stack: Set<string>) {
354
- if (visited.has(name) || stack.has(name)) return
355
- stack.add(name)
356
- for (const child of deps.get(name) ?? []) {
357
- if (deps.has(child)) visit(child, stack)
358
- }
359
- stack.delete(name)
360
- visited.add(name)
361
- sorted.push(name)
362
- }
363
-
364
- for (const name of Object.keys(schemas)) {
365
- visit(name, new Set())
366
- }
367
-
368
- const result: Record<string, SchemaObject> = {}
369
- for (const name of sorted) result[name] = schemas[name]!
370
- return result
371
- }
372
-
373
- const semanticSuffixes: Record<SchemaSourceMode, string> = {
374
- schemas: 'Schema',
375
- responses: 'Response',
376
- requestBodies: 'Request',
377
- }
378
-
379
- function getSemanticSuffix(source: SchemaSourceMode): string {
380
- return semanticSuffixes[source]
381
- }
382
-
383
- function resolveSchemaRef(document: Document, schema: SchemaObject): SchemaObject {
384
- if (!isReference(schema)) return schema
385
- const resolved = resolveRef<SchemaObject>(document, schema.$ref)
386
- return resolved && !isReference(resolved) ? resolved : schema
387
- }
388
-
389
- /**
390
- * Collects component schemas from one or more sources and resolves name collisions.
391
- *
392
- * Sources default to `['schemas', 'requestBodies', 'responses']`. Returned schemas are
393
- * topologically sorted by `$ref` dependency so generators emit types in the correct order.
394
- *
395
- * When two or more schemas normalize to the same PascalCase name:
396
- * - Same source → numeric suffix (`2`, `3`, …).
397
- * - Different sources → semantic suffix (`Schema`, `Response`, `Request`).
398
- *
399
- * @example
400
- * ```ts
401
- * const { schemas, nameMapping } = getSchemas(document, { contentType: 'application/json' })
402
- * ```
403
- */
404
- export function getSchemas(document: Document, { contentType }: GetSchemasOptions): GetSchemasResult {
405
- const components = document.components
406
-
407
- const candidates: SchemaWithMetadata[] = [
408
- ...Object.entries((components?.schemas as Record<string, SchemaObject>) ?? {}).map(([name, schema]) => ({
409
- schema: resolveSchemaRef(document, schema),
410
- source: 'schemas' as const,
411
- originalName: name,
412
- })),
413
- ...(['responses', 'requestBodies'] as const).flatMap((source) =>
414
- Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {
415
- const schema = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)
416
- return schema
417
- ? [
418
- {
419
- schema: resolveSchemaRef(document, schema),
420
- source,
421
- originalName: name,
422
- },
423
- ]
424
- : []
425
- }),
426
- ),
427
- ]
428
-
429
- const normalizedNames = new Map<string, SchemaWithMetadata[]>()
430
- for (const item of candidates) {
431
- const key = pascalCase(item.originalName)
432
- const bucket = normalizedNames.get(key) ?? []
433
- bucket.push(item)
434
- normalizedNames.set(key, bucket)
435
- }
436
-
437
- const schemas: Record<string, SchemaObject> = {}
438
- const nameMapping = new Map<string, string>()
439
-
440
- for (const [, items] of normalizedNames) {
441
- const isSingle = items.length === 1
442
- let hasMultipleSources = false
443
- if (!isSingle) {
444
- const firstSource = items[0]!.source
445
- for (let i = 1; i < items.length; i++) {
446
- if (items[i]!.source !== firstSource) {
447
- hasMultipleSources = true
448
- break
449
- }
450
- }
451
- }
452
-
453
- items.forEach((item, index) => {
454
- const suffix = isSingle ? '' : hasMultipleSources ? getSemanticSuffix(item.source) : index === 0 ? '' : String(index + 1)
455
- const uniqueName = item.originalName + suffix
456
- schemas[uniqueName] = item.schema
457
- nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)
458
- })
459
- }
460
-
461
- return { schemas: sortSchemas(schemas), nameMapping }
462
- }
463
-
464
- /**
465
- * Resolves the AST type descriptor for a date/time format, honoring the `dateType` option.
466
- * Returns `null` when `dateType: false`, signalling the format should fall through to `string`.
467
- */
468
- export function getDateType(
469
- options: ast.ParserOptions,
470
- format: 'date-time' | 'date' | 'time',
471
- ): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | null {
472
- if (!options.dateType) {
473
- return null
474
- }
475
-
476
- if (format === 'date-time') {
477
- if (options.dateType === 'date') {
478
- return { type: 'date', representation: 'date' }
479
- }
480
- if (options.dateType === 'stringOffset') {
481
- return { type: 'datetime', offset: true }
482
- }
483
- if (options.dateType === 'stringLocal') {
484
- return { type: 'datetime', local: true }
485
- }
486
- return { type: 'datetime', offset: false }
487
- }
488
-
489
- if (format === 'date') {
490
- return {
491
- type: 'date',
492
- representation: options.dateType === 'date' ? 'date' : 'string',
493
- }
494
- }
495
-
496
- // time
497
- return {
498
- type: 'time',
499
- representation: options.dateType === 'date' ? 'date' : 'string',
500
- }
501
- }
502
-
503
- /**
504
- * Collects the shared metadata fields passed to every `createSchema` call.
505
- */
506
- export function buildSchemaNode(schema: SchemaObject, name: string | null | undefined, nullable: true | undefined, defaultValue: unknown) {
507
- return {
508
- name,
509
- nullable,
510
- title: schema.title,
511
- description: schema.description,
512
- deprecated: schema.deprecated,
513
- readOnly: schema.readOnly,
514
- writeOnly: schema.writeOnly,
515
- default: defaultValue,
516
- example: schema.example,
517
- } as const
518
- }
519
-
520
- /**
521
- * Returns all request body content type keys for an operation.
522
- *
523
- * The requestBody is dereferenced **in-place** when it is a `$ref` — the same mutation
524
- * that `getRequestSchema` already performs — so that the returned list accurately reflects
525
- * the available content types even for referenced bodies.
526
- *
527
- * @example
528
- * ```ts
529
- * getRequestBodyContentTypes(document, operation)
530
- * // ['application/json', 'multipart/form-data']
531
- * ```
532
- */
533
- export function getRequestBodyContentTypes(document: Document, operation: Operation): string[] {
534
- if (operation.schema.requestBody) {
535
- operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)
536
- }
537
-
538
- const body = operation.schema.requestBody as { content?: Record<string, unknown> } | undefined
539
- if (!body) return []
540
-
541
- // dereferenceWithRef keeps $ref but spreads all resolved fields (including `content`).
542
- // Do not bail out on isReference — the content is already present on the merged object.
543
- return body.content ? Object.keys(body.content) : []
544
- }