@kubb/adapter-oas 5.0.0-alpha.2 → 5.0.0-alpha.20
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 +989 -1070
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +83 -128
- package/dist/index.js +988 -1069
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/src/adapter.ts +79 -63
- package/src/constants.ts +63 -63
- package/src/discriminator.ts +99 -0
- package/src/factory.ts +151 -0
- package/src/guards.ts +68 -0
- package/src/index.ts +1 -0
- package/src/parser.ts +352 -667
- package/src/refs.ts +57 -0
- package/src/resolvers.ts +490 -0
- package/src/types.ts +178 -56
- package/src/oas/Oas.ts +0 -616
- package/src/oas/resolveServerUrl.ts +0 -47
- package/src/oas/types.ts +0 -52
- package/src/oas/utils.ts +0 -402
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/adapter-oas",
|
|
3
|
-
"version": "5.0.0-alpha.
|
|
3
|
+
"version": "5.0.0-alpha.20",
|
|
4
4
|
"description": "OpenAPI / Swagger adapter for Kubb — converts OAS input into a @kubb/ast RootNode.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"openapi",
|
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
"!/**/__snapshots__/**"
|
|
37
37
|
],
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@kubb/fabric-core": "0.
|
|
40
|
-
"@redocly/openapi-core": "^2.
|
|
39
|
+
"@kubb/fabric-core": "0.15.1",
|
|
40
|
+
"@redocly/openapi-core": "^2.25.1",
|
|
41
41
|
"@stoplight/yaml": "^4.3.0",
|
|
42
42
|
"fflate": "^0.8.2",
|
|
43
43
|
"jsonpointer": "^5.0.1",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"openapi-types": "^12.1.3",
|
|
47
47
|
"remeda": "^2.33.6",
|
|
48
48
|
"swagger2openapi": "^7.0.8",
|
|
49
|
-
"@kubb/ast": "5.0.0-alpha.
|
|
50
|
-
"@kubb/core": "5.0.0-alpha.
|
|
49
|
+
"@kubb/ast": "5.0.0-alpha.20",
|
|
50
|
+
"@kubb/core": "5.0.0-alpha.20"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/swagger2openapi": "^7.0.4",
|
package/src/adapter.ts
CHANGED
|
@@ -1,105 +1,121 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import type {
|
|
1
|
+
import { collectImports, createRoot } from '@kubb/ast'
|
|
2
|
+
import { createAdapter } from '@kubb/core'
|
|
3
|
+
import { DEFAULT_PARSER_OPTIONS } from './constants.ts'
|
|
4
|
+
import { applyDiscriminatorInheritance } from './discriminator.ts'
|
|
5
|
+
import { parseFromConfig, validateDocument } from './factory.ts'
|
|
6
|
+
import { parseOas } from './parser.ts'
|
|
7
|
+
import { resolveServerUrl } from './resolvers.ts'
|
|
8
|
+
import type { AdapterOas, Document } from './types.ts'
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Stable string identifier for the OAS adapter used in Kubb's adapter registry.
|
|
12
|
+
*/
|
|
13
|
+
export const adapterOasName = 'oas' satisfies AdapterOas['name']
|
|
11
14
|
|
|
12
15
|
/**
|
|
13
|
-
* Creates
|
|
16
|
+
* Creates the default OpenAPI / Swagger adapter for Kubb.
|
|
14
17
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
18
|
+
* Parses the spec, optionally validates it, resolves the base URL, and converts
|
|
19
|
+
* everything into a `RootNode` that downstream plugins consume.
|
|
17
20
|
*
|
|
18
21
|
* @example
|
|
19
22
|
* ```ts
|
|
20
23
|
* import { defineConfig } from '@kubb/core'
|
|
21
24
|
* import { adapterOas } from '@kubb/adapter-oas'
|
|
25
|
+
* import { pluginTs } from '@kubb/plugin-ts'
|
|
22
26
|
*
|
|
23
27
|
* export default defineConfig({
|
|
24
|
-
* adapter: adapterOas({
|
|
25
|
-
* input:
|
|
26
|
-
* plugins: [pluginTs()
|
|
28
|
+
* adapter: adapterOas({ dateType: 'date', serverIndex: 0 }),
|
|
29
|
+
* input: { path: './openapi.yaml' },
|
|
30
|
+
* plugins: [pluginTs()],
|
|
27
31
|
* })
|
|
28
32
|
* ```
|
|
29
33
|
*/
|
|
30
|
-
export const adapterOas =
|
|
34
|
+
export const adapterOas = createAdapter<AdapterOas>((options) => {
|
|
31
35
|
const {
|
|
32
36
|
validate = true,
|
|
33
|
-
oasClass,
|
|
34
37
|
contentType,
|
|
35
38
|
serverIndex,
|
|
36
39
|
serverVariables,
|
|
37
40
|
discriminator = 'strict',
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
emptySchemaType = unknownType,
|
|
41
|
+
dateType = DEFAULT_PARSER_OPTIONS.dateType,
|
|
42
|
+
integerType = DEFAULT_PARSER_OPTIONS.integerType,
|
|
43
|
+
unknownType = DEFAULT_PARSER_OPTIONS.unknownType,
|
|
44
|
+
enumSuffix = DEFAULT_PARSER_OPTIONS.enumSuffix,
|
|
45
|
+
emptySchemaType = unknownType || DEFAULT_PARSER_OPTIONS.emptySchemaType,
|
|
43
46
|
} = options
|
|
44
47
|
|
|
48
|
+
// Let-binding so parse() can replace it with a simple reassignment (no clear+loop).
|
|
49
|
+
let nameMapping = new Map<string, string>()
|
|
50
|
+
let parsedDocument: Document | undefined
|
|
51
|
+
|
|
45
52
|
return {
|
|
46
53
|
name: adapterOasName,
|
|
47
|
-
options
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
54
|
+
get options() {
|
|
55
|
+
return {
|
|
56
|
+
validate,
|
|
57
|
+
contentType,
|
|
58
|
+
serverIndex,
|
|
59
|
+
serverVariables,
|
|
60
|
+
discriminator,
|
|
61
|
+
dateType,
|
|
62
|
+
integerType,
|
|
63
|
+
unknownType,
|
|
64
|
+
emptySchemaType,
|
|
65
|
+
enumSuffix,
|
|
66
|
+
nameMapping,
|
|
67
|
+
}
|
|
59
68
|
},
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
69
|
+
get document() {
|
|
70
|
+
return parsedDocument
|
|
71
|
+
},
|
|
72
|
+
getImports(node, resolve) {
|
|
73
|
+
return collectImports({
|
|
74
|
+
node,
|
|
75
|
+
nameMapping,
|
|
76
|
+
resolve: (schemaName) => {
|
|
77
|
+
const result = resolve(schemaName)
|
|
78
|
+
if (!result) return
|
|
63
79
|
|
|
64
|
-
|
|
80
|
+
return { name: [result.name], path: result.path }
|
|
81
|
+
},
|
|
82
|
+
})
|
|
83
|
+
},
|
|
84
|
+
async parse(source) {
|
|
85
|
+
const document = await parseFromConfig(source)
|
|
65
86
|
|
|
66
87
|
if (validate) {
|
|
67
|
-
|
|
68
|
-
await oas.validate()
|
|
69
|
-
} catch (_err) {
|
|
70
|
-
// Validation failures are non-fatal — mirror plugin-oas behavior
|
|
71
|
-
}
|
|
88
|
+
await validateDocument(document)
|
|
72
89
|
}
|
|
73
90
|
|
|
74
|
-
const server = serverIndex !== undefined ?
|
|
91
|
+
const server = serverIndex !== undefined ? document.servers?.at(serverIndex) : undefined
|
|
75
92
|
const baseURL = server?.url ? resolveServerUrl(server, serverVariables) : undefined
|
|
76
93
|
|
|
77
|
-
const
|
|
78
|
-
|
|
94
|
+
const { root: parsedRoot, nameMapping: parsedNameMapping } = parseOas(document, {
|
|
95
|
+
contentType,
|
|
96
|
+
dateType,
|
|
97
|
+
integerType,
|
|
98
|
+
unknownType,
|
|
99
|
+
emptySchemaType,
|
|
100
|
+
enumSuffix,
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
const root = discriminator === 'inherit' ? applyDiscriminatorInheritance(parsedRoot) : parsedRoot
|
|
104
|
+
|
|
105
|
+
// This must happen after parseOas() because legacy enum remapping is finalized there.
|
|
106
|
+
nameMapping = parsedNameMapping
|
|
107
|
+
// Expose the raw document so consumers (e.g. plugin-redoc) can access it.
|
|
108
|
+
parsedDocument = document
|
|
79
109
|
|
|
80
110
|
return createRoot({
|
|
81
111
|
...root,
|
|
82
112
|
meta: {
|
|
83
|
-
title:
|
|
84
|
-
|
|
113
|
+
title: document.info?.title,
|
|
114
|
+
description: document.info?.description,
|
|
115
|
+
version: document.info?.version,
|
|
85
116
|
baseURL,
|
|
86
117
|
},
|
|
87
118
|
})
|
|
88
119
|
},
|
|
89
120
|
}
|
|
90
121
|
})
|
|
91
|
-
|
|
92
|
-
// TODO: remove once parseFromConfig accepts AdapterSource directly
|
|
93
|
-
function sourceToFakeConfig(source: AdapterSource): Parameters<typeof parseFromConfig>[0] {
|
|
94
|
-
switch (source.type) {
|
|
95
|
-
case 'path':
|
|
96
|
-
return { root: path.dirname(source.path), input: { path: source.path } } as Parameters<typeof parseFromConfig>[0]
|
|
97
|
-
case 'data':
|
|
98
|
-
return { root: process.cwd(), input: { data: source.data } } as Parameters<typeof parseFromConfig>[0]
|
|
99
|
-
case 'paths':
|
|
100
|
-
return {
|
|
101
|
-
root: source.paths[0] ? path.dirname(source.paths[0]) : process.cwd(),
|
|
102
|
-
input: source.paths.map((p) => ({ path: p })),
|
|
103
|
-
} as Parameters<typeof parseFromConfig>[0]
|
|
104
|
-
}
|
|
105
|
-
}
|
package/src/constants.ts
CHANGED
|
@@ -1,41 +1,71 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type {
|
|
1
|
+
import { schemaTypes } from '@kubb/ast'
|
|
2
|
+
import type { ParserOptions, ScalarSchemaType, SchemaType } from '@kubb/ast/types'
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Default parser options applied when no explicit options are provided.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { DEFAULT_PARSER_OPTIONS } from '@kubb/adapter-oas'
|
|
10
|
+
*
|
|
11
|
+
* const parser = createOasParser(oas)
|
|
12
|
+
* const root = parser.parse({ ...DEFAULT_PARSER_OPTIONS, dateType: 'date' })
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_PARSER_OPTIONS = {
|
|
16
|
+
dateType: 'string',
|
|
17
|
+
integerType: 'number',
|
|
18
|
+
unknownType: 'any',
|
|
19
|
+
emptySchemaType: 'any',
|
|
20
|
+
enumSuffix: 'enum',
|
|
21
|
+
} as const satisfies ParserOptions
|
|
5
22
|
|
|
6
23
|
/**
|
|
7
|
-
* OpenAPI version string written into
|
|
24
|
+
* OpenAPI version string written into the stub document created during multi-spec merges.
|
|
8
25
|
*/
|
|
9
26
|
export const MERGE_OPENAPI_VERSION = '3.0.0' as const
|
|
10
27
|
|
|
11
28
|
/**
|
|
12
|
-
* Fallback `info.title`
|
|
29
|
+
* Fallback `info.title` placed in the stub document when merging multiple API files.
|
|
13
30
|
*/
|
|
14
31
|
export const MERGE_DEFAULT_TITLE = 'Merged API' as const
|
|
15
32
|
|
|
16
33
|
/**
|
|
17
|
-
* Fallback `info.version`
|
|
34
|
+
* Fallback `info.version` placed in the stub document when merging multiple API files.
|
|
18
35
|
*/
|
|
19
36
|
export const MERGE_DEFAULT_VERSION = '1.0.0' as const
|
|
20
37
|
|
|
21
|
-
// ─── Schema analysis ───────────────────────────────────────────────────────────
|
|
22
|
-
|
|
23
38
|
/**
|
|
24
|
-
* JSON Schema keywords that
|
|
25
|
-
*
|
|
26
|
-
*
|
|
39
|
+
* Set of JSON Schema keywords that prevent a schema fragment from being inlined during `allOf` flattening.
|
|
40
|
+
*
|
|
41
|
+
* A fragment that contains any of these keys carries structural meaning of its own and must stay as a separate
|
|
42
|
+
* intersection member rather than being merged into the parent.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { structuralKeys } from '@kubb/adapter-oas'
|
|
47
|
+
*
|
|
48
|
+
* const isStructural = Object.keys(fragment).some((key) => structuralKeys.has(key))
|
|
49
|
+
* // true when fragment has e.g. 'properties' or 'oneOf'
|
|
50
|
+
* ```
|
|
27
51
|
*/
|
|
28
|
-
export const structuralKeys = new Set
|
|
52
|
+
export const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)
|
|
29
53
|
|
|
30
54
|
/**
|
|
31
|
-
*
|
|
55
|
+
* Static map from OAS `format` strings to Kubb `SchemaType` values.
|
|
32
56
|
*
|
|
33
|
-
* Only formats
|
|
34
|
-
* `int64`, `date-time`, `date`,
|
|
35
|
-
*
|
|
57
|
+
* Only formats whose AST type differs from the OAS `type` field appear here.
|
|
58
|
+
* Formats that depend on runtime options (`int64`, `date-time`, `date`, `time`) are handled separately
|
|
59
|
+
* in the parser. `ipv4`, `ipv6`, and `hostname` map to `'url'` as the closest supported scalar.
|
|
36
60
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import { formatMap } from '@kubb/adapter-oas'
|
|
64
|
+
*
|
|
65
|
+
* formatMap['uuid'] // 'uuid'
|
|
66
|
+
* formatMap['binary'] // 'blob'
|
|
67
|
+
* formatMap['float'] // 'number'
|
|
68
|
+
* ```
|
|
39
69
|
*/
|
|
40
70
|
export const formatMap = {
|
|
41
71
|
uuid: 'uuid',
|
|
@@ -58,53 +88,23 @@ export const formatMap = {
|
|
|
58
88
|
} as const satisfies Record<string, SchemaType>
|
|
59
89
|
|
|
60
90
|
/**
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
'application/pdf',
|
|
70
|
-
'application/zip',
|
|
71
|
-
'application/graphql',
|
|
72
|
-
'multipart/form-data',
|
|
73
|
-
'text/plain',
|
|
74
|
-
'text/html',
|
|
75
|
-
'text/csv',
|
|
76
|
-
'text/xml',
|
|
77
|
-
'image/png',
|
|
78
|
-
'image/jpeg',
|
|
79
|
-
'image/gif',
|
|
80
|
-
'image/webp',
|
|
81
|
-
'image/svg+xml',
|
|
82
|
-
'audio/mpeg',
|
|
83
|
-
'video/mp4',
|
|
84
|
-
] as const satisfies ReadonlyArray<MediaType>
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Vendor extension keys used to attach human-readable labels to enum values.
|
|
88
|
-
* Checked in priority order: the first key found wins.
|
|
91
|
+
* Vendor extension keys that attach human-readable labels to enum values, checked in priority order.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { enumExtensionKeys } from '@kubb/adapter-oas'
|
|
96
|
+
*
|
|
97
|
+
* const key = enumExtensionKeys.find((k) => k in schema) // 'x-enumNames' | 'x-enum-varnames' | undefined
|
|
98
|
+
* ```
|
|
89
99
|
*/
|
|
90
100
|
export const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const
|
|
91
101
|
|
|
92
|
-
// ─── HTTP ──────────────────────────────────────────────────────────────────────
|
|
93
|
-
|
|
94
102
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* that the `oas` library uses internally.
|
|
98
|
-
*
|
|
99
|
-
* TODO(v5): remove — use `httpMethods` from `@kubb/ast`
|
|
103
|
+
* Maps `'any' | 'unknown' | 'void'` option strings to their `ScalarSchemaType` constant.
|
|
104
|
+
* Replaces a plain object lookup with a `Map` for explicit key membership testing via `.has()`.
|
|
100
105
|
*/
|
|
101
|
-
export const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
DELETE: 'delete',
|
|
107
|
-
HEAD: 'head',
|
|
108
|
-
OPTIONS: 'options',
|
|
109
|
-
TRACE: 'trace',
|
|
110
|
-
} as const satisfies Record<Uppercase<OASHttpMethods>, OASHttpMethods>
|
|
106
|
+
export const typeOptionMap = new Map<'any' | 'unknown' | 'void', ScalarSchemaType>([
|
|
107
|
+
['any', schemaTypes.any],
|
|
108
|
+
['unknown', schemaTypes.unknown],
|
|
109
|
+
['void', schemaTypes.void],
|
|
110
|
+
])
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createProperty, createSchema, narrowSchema, transform } from '@kubb/ast'
|
|
2
|
+
import type { RootNode } from '@kubb/ast/types'
|
|
3
|
+
|
|
4
|
+
type DiscriminatorTarget = { propertyName: string; enumValues: Array<string | number | boolean> }
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Injects discriminator enum values into child schemas so they know which value identifies them.
|
|
8
|
+
*
|
|
9
|
+
* Finds every union schema in `root.schemas` that has a `discriminatorPropertyName`, collects the
|
|
10
|
+
* enum value each union member is mapped to, then adds (or replaces) that property on the matching
|
|
11
|
+
* child object schema.
|
|
12
|
+
*
|
|
13
|
+
* Returns a new `RootNode` — the original is never mutated.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const { root } = parseOas(document, options)
|
|
18
|
+
* const next = applyDiscriminatorInheritance(root)
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export function applyDiscriminatorInheritance(root: RootNode): RootNode {
|
|
22
|
+
const childMap = new Map<string, DiscriminatorTarget>()
|
|
23
|
+
|
|
24
|
+
for (const schema of root.schemas) {
|
|
25
|
+
// Case 1: top-level schema is a union (oneOf/anyOf with discriminator)
|
|
26
|
+
// Case 2: top-level schema is an intersection wrapping a union (oneOf/anyOf + shared properties)
|
|
27
|
+
let unionNode = narrowSchema(schema, 'union')
|
|
28
|
+
|
|
29
|
+
if (!unionNode) {
|
|
30
|
+
const intersectionMembers = narrowSchema(schema, 'intersection')?.members
|
|
31
|
+
if (intersectionMembers) {
|
|
32
|
+
for (const m of intersectionMembers) {
|
|
33
|
+
const u = narrowSchema(m, 'union')
|
|
34
|
+
if (u) {
|
|
35
|
+
unionNode = u
|
|
36
|
+
break
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue
|
|
43
|
+
|
|
44
|
+
const { discriminatorPropertyName, members } = unionNode
|
|
45
|
+
|
|
46
|
+
for (const member of members) {
|
|
47
|
+
// Members with a discriminant value are intersections: [RefSchemaNode, ObjectSchemaNode]
|
|
48
|
+
const intersectionNode = narrowSchema(member, 'intersection')
|
|
49
|
+
if (!intersectionNode?.members) continue
|
|
50
|
+
|
|
51
|
+
let refNode: ReturnType<typeof narrowSchema<'ref'>> | undefined
|
|
52
|
+
let objNode: ReturnType<typeof narrowSchema<'object'>> | undefined
|
|
53
|
+
|
|
54
|
+
for (const m of intersectionNode.members) {
|
|
55
|
+
refNode ??= narrowSchema(m, 'ref')
|
|
56
|
+
objNode ??= narrowSchema(m, 'object')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (!refNode?.name || !objNode) continue
|
|
60
|
+
|
|
61
|
+
const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName)
|
|
62
|
+
const enumNode = prop ? narrowSchema(prop.schema, 'enum') : undefined
|
|
63
|
+
if (!enumNode?.enumValues?.length) continue
|
|
64
|
+
|
|
65
|
+
const enumValues = enumNode.enumValues.filter((v): v is string | number | boolean => v !== null)
|
|
66
|
+
if (!enumValues.length) continue
|
|
67
|
+
|
|
68
|
+
const existing = childMap.get(refNode.name)
|
|
69
|
+
if (existing) {
|
|
70
|
+
existing.enumValues.push(...enumValues)
|
|
71
|
+
} else {
|
|
72
|
+
childMap.set(refNode.name, { propertyName: discriminatorPropertyName, enumValues: [...enumValues] })
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (childMap.size === 0) return root
|
|
78
|
+
|
|
79
|
+
return transform(root, {
|
|
80
|
+
schema(node, { parent }) {
|
|
81
|
+
if (parent?.kind !== 'Root' || !node.name) return
|
|
82
|
+
|
|
83
|
+
const entry = childMap.get(node.name)
|
|
84
|
+
if (!entry) return
|
|
85
|
+
|
|
86
|
+
const objectNode = narrowSchema(node, 'object')
|
|
87
|
+
if (!objectNode) return
|
|
88
|
+
|
|
89
|
+
const { propertyName, enumValues } = entry
|
|
90
|
+
const enumSchema = createSchema({ type: 'enum', enumValues })
|
|
91
|
+
const newProp = createProperty({ name: propertyName, required: true, schema: enumSchema })
|
|
92
|
+
|
|
93
|
+
const existingIdx = objectNode.properties.findIndex((p) => p.name === propertyName)
|
|
94
|
+
const newProperties = existingIdx >= 0 ? objectNode.properties.map((p, i) => (i === existingIdx ? newProp : p)) : [...objectNode.properties, newProp]
|
|
95
|
+
|
|
96
|
+
return { ...objectNode, properties: newProperties }
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
}
|
package/src/factory.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { URLPath } from '@internals/utils'
|
|
3
|
+
import type { AdapterSource } from '@kubb/core'
|
|
4
|
+
import { bundle, loadConfig } from '@redocly/openapi-core'
|
|
5
|
+
import yaml from '@stoplight/yaml'
|
|
6
|
+
import OASNormalize from 'oas-normalize'
|
|
7
|
+
import { mergeDeep } from 'remeda'
|
|
8
|
+
import swagger2openapi from 'swagger2openapi'
|
|
9
|
+
import { MERGE_DEFAULT_TITLE, MERGE_DEFAULT_VERSION, MERGE_OPENAPI_VERSION } from './constants.ts'
|
|
10
|
+
import { isOpenApiV2Document } from './guards.ts'
|
|
11
|
+
import type { Document } from './types.ts'
|
|
12
|
+
|
|
13
|
+
export type ParseOptions = {
|
|
14
|
+
canBundle?: boolean
|
|
15
|
+
enablePaths?: boolean
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Loads and dereferences an OpenAPI document, returning the raw `Document`.
|
|
20
|
+
*
|
|
21
|
+
* Accepts a file path string or an already-parsed document object. File paths are bundled via
|
|
22
|
+
* Redocly to resolve external `$ref`s. Swagger 2.0 documents are automatically up-converted
|
|
23
|
+
* to OpenAPI 3.0 via `swagger2openapi`.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const document = await parseDocument('./openapi.yaml')
|
|
28
|
+
* const document = await parse(rawDocumentObject, { canBundle: false })
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export async function parseDocument(pathOrApi: string | Document, { canBundle = true, enablePaths = true }: ParseOptions = {}): Promise<Document> {
|
|
32
|
+
if (typeof pathOrApi === 'string' && canBundle) {
|
|
33
|
+
const config = await loadConfig()
|
|
34
|
+
const bundleResults = await bundle({ ref: pathOrApi, config, base: pathOrApi })
|
|
35
|
+
|
|
36
|
+
return parseDocument(bundleResults.bundle.parsed as string, { canBundle, enablePaths })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const oasNormalize = new OASNormalize(pathOrApi, {
|
|
40
|
+
enablePaths,
|
|
41
|
+
colorizeErrors: true,
|
|
42
|
+
})
|
|
43
|
+
const document = (await oasNormalize.load()) as Document
|
|
44
|
+
|
|
45
|
+
if (isOpenApiV2Document(document)) {
|
|
46
|
+
const { openapi } = await swagger2openapi.convertObj(document, {
|
|
47
|
+
anchors: true,
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
return openapi as Document
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return document
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Deep-merges multiple OpenAPI documents into a single `Document`.
|
|
58
|
+
*
|
|
59
|
+
* Each document is parsed independently then recursively merged with `remeda`'s `mergeDeep`.
|
|
60
|
+
* Throws when the input array is empty.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* const document = await mergeDocuments(['./pets.yaml', './orders.yaml'])
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export async function mergeDocuments(pathOrApi: Array<string | Document>): Promise<Document> {
|
|
68
|
+
const documents = await Promise.all(pathOrApi.map((p) => parseDocument(p, { enablePaths: false, canBundle: false })))
|
|
69
|
+
|
|
70
|
+
if (documents.length === 0) {
|
|
71
|
+
throw new Error('No OAS documents provided for merging.')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const seed: Document = {
|
|
75
|
+
openapi: MERGE_OPENAPI_VERSION,
|
|
76
|
+
info: { title: MERGE_DEFAULT_TITLE, version: MERGE_DEFAULT_VERSION },
|
|
77
|
+
paths: {},
|
|
78
|
+
components: { schemas: {} },
|
|
79
|
+
} as Document
|
|
80
|
+
|
|
81
|
+
const merged = documents.reduce((acc, current) => mergeDeep(acc, current as Document), seed)
|
|
82
|
+
|
|
83
|
+
return parseDocument(merged)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Creates a `Document` from an `AdapterSource`.
|
|
88
|
+
*
|
|
89
|
+
* Handles all three source types:
|
|
90
|
+
* - `{ type: 'path' }` — resolves and bundles a local file path or remote URL.
|
|
91
|
+
* - `{ type: 'paths' }` — merges multiple file paths into a single document.
|
|
92
|
+
* - `{ type: 'data' }` — parses an inline string (YAML/JSON) or raw object.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* const document = await parseFromConfig({ type: 'path', path: './openapi.yaml' })
|
|
97
|
+
* const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export function parseFromConfig(source: AdapterSource): Promise<Document> {
|
|
101
|
+
if (source.type === 'data') {
|
|
102
|
+
if (typeof source.data === 'object') {
|
|
103
|
+
return parseDocument(structuredClone(source.data) as Document)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
const api: string = yaml.parse(source.data as string)
|
|
108
|
+
return parseDocument(api)
|
|
109
|
+
} catch {
|
|
110
|
+
return parseDocument(source.data as string)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (source.type === 'paths') {
|
|
115
|
+
return mergeDocuments(source.paths)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// type === 'path'
|
|
119
|
+
if (new URLPath(source.path).isURL) {
|
|
120
|
+
return parseDocument(source.path)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return parseDocument(path.resolve(path.dirname(source.path), source.path))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Validates an OpenAPI document using `oas-normalize` with colorized error output.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* await validateDocument(document)
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
export async function validateDocument(document: Document): Promise<void> {
|
|
135
|
+
try {
|
|
136
|
+
const oasNormalize = new OASNormalize(document, {
|
|
137
|
+
enablePaths: true,
|
|
138
|
+
colorizeErrors: true,
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
await oasNormalize.validate({
|
|
142
|
+
parser: {
|
|
143
|
+
validate: {
|
|
144
|
+
errors: { colorize: true },
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
} catch (_err) {
|
|
149
|
+
// Validation failures are non-fatal — mirror plugin-oas behavior
|
|
150
|
+
}
|
|
151
|
+
}
|