@amritk/helpers 0.13.5 → 0.15.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.
- package/AI.md +13 -5
- package/README.md +4 -1
- package/dist/assert-id-scopes.d.ts +20 -0
- package/dist/assert-id-scopes.js +45 -0
- package/dist/build-anchor-map.d.ts +26 -0
- package/dist/build-anchor-map.js +35 -0
- package/dist/build-dynamic-ref-map.d.ts +8 -0
- package/dist/build-dynamic-ref-map.js +7 -5
- package/dist/build-resource-registry.d.ts +88 -0
- package/dist/build-resource-registry.js +90 -0
- package/dist/escape-regex-pattern.d.ts +27 -0
- package/dist/escape-regex-pattern.js +21 -1
- package/dist/extract-refs.js +6 -4
- package/dist/fold-nullable.d.ts +19 -0
- package/dist/fold-nullable.js +42 -0
- package/dist/generate-index-barrel.js +13 -6
- package/dist/generate-type-definition.d.ts +8 -0
- package/dist/generate-type-definition.js +249 -185
- package/dist/graft-external-schemas.d.ts +83 -0
- package/dist/graft-external-schemas.js +70 -0
- package/dist/max-schema-depth.d.ts +22 -0
- package/dist/max-schema-depth.js +10 -0
- package/dist/mjst-extension.d.ts +4 -2
- package/dist/mjst-extension.js +11 -2
- package/dist/multiple-of-check.d.ts +31 -0
- package/dist/multiple-of-check.js +6 -10
- package/dist/normalize-ref-scopes.d.ts +29 -0
- package/dist/normalize-ref-scopes.js +53 -0
- package/dist/prune-external-schemas.d.ts +16 -0
- package/dist/prune-external-schemas.js +80 -0
- package/dist/ref-to-filename.d.ts +1 -0
- package/dist/ref-to-filename.js +19 -3
- package/dist/ref-to-name.js +7 -4
- package/dist/resolve-dynamic-refs.d.ts +10 -0
- package/dist/resolve-dynamic-refs.js +18 -16
- package/dist/resolve-ref.d.ts +4 -2
- package/dist/resolve-ref.js +32 -6
- package/dist/resolve-scoped-ref.d.ts +35 -0
- package/dist/resolve-scoped-ref.js +35 -0
- package/dist/safe-accessor.d.ts +38 -1
- package/dist/safe-accessor.js +15 -0
- package/dist/string-length-check.d.ts +8 -0
- package/dist/string-length-check.js +23 -0
- package/dist/upgrade-draft07-schema.js +9 -6
- package/dist/walk-ref-graph.d.ts +38 -3
- package/dist/walk-ref-graph.js +173 -18
- package/package.json +16 -3
- package/src/build-dynamic-ref-map.ts +0 -61
- package/src/derive-root-type-name.ts +0 -54
- package/src/escape-regex-pattern.ts +0 -87
- package/src/extract-dynamic-anchor-defs.ts +0 -25
- package/src/extract-refs.ts +0 -73
- package/src/generate-index-barrel.ts +0 -118
- package/src/generate-type-definition.ts +0 -599
- package/src/mjst-extension.ts +0 -81
- package/src/multiple-of-check.ts +0 -32
- package/src/parse-documentation.ts +0 -177
- package/src/quote-js-string.ts +0 -20
- package/src/ref-to-filename.ts +0 -116
- package/src/ref-to-name.ts +0 -54
- package/src/resolve-dynamic-refs.ts +0 -74
- package/src/resolve-ref.ts +0 -82
- package/src/safe-accessor.ts +0 -53
- package/src/schema-guards.ts +0 -234
- package/src/unknown-key-check.ts +0 -68
- package/src/upgrade-draft07-schema.ts +0 -179
- package/src/walk-ref-graph.ts +0 -240
package/src/multiple-of-check.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
|
|
3
|
-
* interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
|
|
4
|
-
*
|
|
5
|
-
* The naive `x % m === 0` is float-wrong: IEEE-754 makes `0.3 % 0.1` evaluate to
|
|
6
|
-
* `0.0999…`, so `0.3` would spuriously fail `multipleOf: 0.1`. The interpreter
|
|
7
|
-
* instead divides and compares the quotient to its nearest integer within a
|
|
8
|
-
* tolerance that *scales with the quotient's magnitude* — a fixed epsilon falsely
|
|
9
|
-
* rejects large values (e.g. `1234567.89` against `multipleOf: 0.01`) whose
|
|
10
|
-
* representation error in the quotient already exceeds it. Keeping the emitted
|
|
11
|
-
* check identical to the interpreter's keeps generated validators/parsers and the
|
|
12
|
-
* interpreter from disagreeing on the same document.
|
|
13
|
-
*
|
|
14
|
-
* `valueExpr` is inlined three times, so it must be a side-effect-free expression
|
|
15
|
-
* (a property read or a cached variable — which is all the generators ever pass).
|
|
16
|
-
*/
|
|
17
|
-
const quotientTolerance = (valueExpr: string, divisor: number): { q: string; tol: string } => {
|
|
18
|
-
const q = `${valueExpr} / ${divisor}`
|
|
19
|
-
return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` }
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
|
|
23
|
-
export const multipleOfPassExpr = (valueExpr: string, divisor: number): string => {
|
|
24
|
-
const { q, tol } = quotientTolerance(valueExpr, divisor)
|
|
25
|
-
return `Math.abs(${q} - Math.round(${q})) <= ${tol}`
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
|
|
29
|
-
export const multipleOfFailExpr = (valueExpr: string, divisor: number): string => {
|
|
30
|
-
const { q, tol } = quotientTolerance(valueExpr, divisor)
|
|
31
|
-
return `Math.abs(${q} - Math.round(${q})) > ${tol}`
|
|
32
|
-
}
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
type PropertyDocumentation = {
|
|
2
|
-
description: string
|
|
3
|
-
isRequired: boolean
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
export type ObjectDocumentation = {
|
|
7
|
-
title: string
|
|
8
|
-
description: string
|
|
9
|
-
properties: Record<string, PropertyDocumentation>
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Fetches and parses OpenAPI specification documentation from the markdown source.
|
|
14
|
-
*
|
|
15
|
-
* When a section has no Fixed Fields table (e.g. Header Object delegates to Parameter Object),
|
|
16
|
-
* pass `fallbackCommentUrl` to inherit property documentation from another section.
|
|
17
|
-
*/
|
|
18
|
-
export const parseDocumentation = (
|
|
19
|
-
markdownDocumentation: string,
|
|
20
|
-
commentUrl: string,
|
|
21
|
-
fallbackCommentUrl?: string,
|
|
22
|
-
): ObjectDocumentation | null => {
|
|
23
|
-
try {
|
|
24
|
-
const markdown = markdownDocumentation
|
|
25
|
-
|
|
26
|
-
// Extract the fragment ID from the URL (e.g., #info-object)
|
|
27
|
-
const fragmentId = commentUrl.split('#')[1]
|
|
28
|
-
if (!fragmentId) {
|
|
29
|
-
return null
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Extract the base URL (everything before the #)
|
|
33
|
-
const baseUrl = commentUrl.split('#')[0]
|
|
34
|
-
|
|
35
|
-
// Convert fragment ID to title case (e.g., "info-object" -> "Info Object")
|
|
36
|
-
const titleWords = fragmentId.split('-')
|
|
37
|
-
let sectionTitle = ''
|
|
38
|
-
for (let i = 0; i < titleWords.length; i++) {
|
|
39
|
-
if (i > 0) sectionTitle += ' '
|
|
40
|
-
const word = titleWords[i] ?? ''
|
|
41
|
-
sectionTitle += word.charAt(0).toUpperCase() + word.slice(1)
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Detect the heading level used for object sections in this markdown file.
|
|
45
|
-
// OAS 3.1 uses #### while OAS 3.2 uses ###, so we probe for both.
|
|
46
|
-
const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m)
|
|
47
|
-
const headingHashes = headingLevelMatch?.[1] ?? '####'
|
|
48
|
-
const subHeadingHashes = headingHashes + '#'
|
|
49
|
-
|
|
50
|
-
// Find the section in the markdown
|
|
51
|
-
// Match the section heading and capture everything until the next same-level heading or end of file.
|
|
52
|
-
// `sectionTitle` comes from the URL fragment, so escape any regex metacharacters
|
|
53
|
-
// before interpolating — otherwise a fragment containing `+`, `(`, etc. throws a
|
|
54
|
-
// SyntaxError that the outer catch then mislabels as a fetch failure.
|
|
55
|
-
const escapedHashes = headingHashes.replace(/#/g, '\\#')
|
|
56
|
-
const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
57
|
-
const sectionRegex = new RegExp(
|
|
58
|
-
`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`,
|
|
59
|
-
'i',
|
|
60
|
-
)
|
|
61
|
-
const sectionMatch = markdown.match(sectionRegex)
|
|
62
|
-
|
|
63
|
-
if (!sectionMatch) {
|
|
64
|
-
return null
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const sectionContent = sectionMatch?.[1]
|
|
68
|
-
|
|
69
|
-
if (!sectionContent) {
|
|
70
|
-
return null
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Extract the description (paragraphs before the "Fixed Fields" sub-heading)
|
|
74
|
-
// \n? handles the case where sectionContent starts directly with the sub-heading (no leading newline),
|
|
75
|
-
// which happens when the section heading is followed by a blank line consumed by \s* in sectionRegex.
|
|
76
|
-
const escapedSubHashes = subHeadingHashes.replace(/#/g, '\\#')
|
|
77
|
-
const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`))
|
|
78
|
-
const description = descriptionMatch?.[1]?.trim().replace(/\n/g, ' ') || ''
|
|
79
|
-
|
|
80
|
-
// Extract all Fixed Fields tables within the section (some objects like Encoding Object
|
|
81
|
-
// split their fields across multiple sub-tables under different sub-sub-headings).
|
|
82
|
-
// Capture everything from the first "Fixed Fields" sub-heading to the end of the section —
|
|
83
|
-
// the section content is already bounded by the outer section regex so we don't need
|
|
84
|
-
// a stop condition here.
|
|
85
|
-
const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`)
|
|
86
|
-
const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex)
|
|
87
|
-
|
|
88
|
-
const properties: Record<string, PropertyDocumentation> = {}
|
|
89
|
-
|
|
90
|
-
if (fixedFieldsMatch?.[1]) {
|
|
91
|
-
const fixedFieldsContent = fixedFieldsMatch[1]
|
|
92
|
-
|
|
93
|
-
// Parse all markdown table rows across all sub-tables within the Fixed Fields section
|
|
94
|
-
const lines = fixedFieldsContent.split('\n')
|
|
95
|
-
let inTable = false
|
|
96
|
-
|
|
97
|
-
for (const line of lines) {
|
|
98
|
-
// Skip the header row and separator row
|
|
99
|
-
if (line.includes('Field Name') || line.includes('---|')) {
|
|
100
|
-
inTable = true
|
|
101
|
-
continue
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// A ###### sub-heading resets inTable so we re-enter on the next header row
|
|
105
|
-
if (line.startsWith('#')) {
|
|
106
|
-
inTable = false
|
|
107
|
-
continue
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
if (!inTable || !line.trim() || !line.includes('|')) {
|
|
111
|
-
continue
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Parse table row: | fieldName | type | description |
|
|
115
|
-
// First, replace escaped pipes (\|) with a placeholder to avoid splitting on them
|
|
116
|
-
const lineWithPlaceholder = line.replace(/\\\|/g, '___PIPE___')
|
|
117
|
-
const cells = lineWithPlaceholder
|
|
118
|
-
.split('|')
|
|
119
|
-
.map((cell) => cell.replace(/___PIPE___/g, '|').trim())
|
|
120
|
-
.filter((cell) => cell)
|
|
121
|
-
|
|
122
|
-
if (cells.length >= 3) {
|
|
123
|
-
const fieldName = cells[0]?.replace(/<[^>]*>/g, '').trim() // Remove HTML tags
|
|
124
|
-
// Some OpenAPI tables include an "Applies To" column before Description.
|
|
125
|
-
// We always want the right-most column as the property description.
|
|
126
|
-
const descriptionCellIndex = cells.length >= 4 ? 3 : 2
|
|
127
|
-
let fieldDescription = cells[descriptionCellIndex]?.trim() || ''
|
|
128
|
-
const isRequired = fieldDescription.includes('REQUIRED')
|
|
129
|
-
|
|
130
|
-
// Replace relative anchor links with full URLs using the base URL
|
|
131
|
-
fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`)
|
|
132
|
-
|
|
133
|
-
// Only accept field names that look like valid identifiers (camelCase or plain words).
|
|
134
|
-
// This filters out rows from non-field tables (e.g. type/contentType default tables)
|
|
135
|
-
// where the "field name" column contains type annotations like `string` or [_absent_].
|
|
136
|
-
const isValidFieldName =
|
|
137
|
-
fieldName &&
|
|
138
|
-
!fieldName.includes('Field Name') &&
|
|
139
|
-
!fieldName.startsWith('`') &&
|
|
140
|
-
!fieldName.startsWith('[') &&
|
|
141
|
-
/^[a-zA-Z]/.test(fieldName)
|
|
142
|
-
|
|
143
|
-
if (isValidFieldName) {
|
|
144
|
-
properties[fieldName] = {
|
|
145
|
-
description: fieldDescription,
|
|
146
|
-
isRequired,
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// Format title as "Info object" instead of "Info Object"
|
|
154
|
-
const title = sectionTitle.replace(/\sObject$/, ' object')
|
|
155
|
-
|
|
156
|
-
// If no properties were found and a fallback URL is provided, inherit properties from it
|
|
157
|
-
if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
|
|
158
|
-
const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl)
|
|
159
|
-
if (fallback && Object.keys(fallback.properties).length > 0) {
|
|
160
|
-
return {
|
|
161
|
-
title,
|
|
162
|
-
description,
|
|
163
|
-
properties: fallback.properties,
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
return {
|
|
169
|
-
title,
|
|
170
|
-
description,
|
|
171
|
-
properties,
|
|
172
|
-
}
|
|
173
|
-
} catch (error) {
|
|
174
|
-
console.error('Failed to fetch OpenAPI documentation:', error)
|
|
175
|
-
return null
|
|
176
|
-
}
|
|
177
|
-
}
|
package/src/quote-js-string.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// Characters that force the JSON.stringify escaping path below: quote,
|
|
2
|
-
// backslash, C0 controls, and the JS line separators. Anything else sits
|
|
3
|
-
// verbatim inside a double-quoted literal.
|
|
4
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: the C0 range is exactly the set that must never appear raw in a generated string literal
|
|
5
|
-
const NEEDS_ESCAPING = /["\\\u0000-\u001f\u2028\u2029]/
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Emits `text` as a double-quoted JS string literal for generated code.
|
|
9
|
-
*
|
|
10
|
-
* This is the one escape-or-quote decision for schema-controlled text
|
|
11
|
-
* (property names, patterns, enum values) embedded in generated source — a key
|
|
12
|
-
* like `it's` or a pattern with a quote or newline must never break out of the
|
|
13
|
-
* literal or inject code, so anything carrying such a character goes through
|
|
14
|
-
* `JSON.stringify`. The common all-plain string skips the full escaper: code
|
|
15
|
-
* generators emit one literal per assertion/message, and the stringify calls
|
|
16
|
-
* were a measurable slice of generation time. Centralized so the next
|
|
17
|
-
* generator wanting the fast path cannot get the security-sensitive regex
|
|
18
|
-
* subtly wrong.
|
|
19
|
-
*/
|
|
20
|
-
export const quoteJsString = (text: string): string => (NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`)
|
package/src/ref-to-filename.ts
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Converts a PascalCase or camelCase string to kebab-case.
|
|
3
|
-
* Handles consecutive uppercase sequences (e.g. "APIKey" → "api-key") and
|
|
4
|
-
* known mixed-case acronyms like "OAuth" that would otherwise split incorrectly.
|
|
5
|
-
*
|
|
6
|
-
* @example
|
|
7
|
-
* ```ts
|
|
8
|
-
* toKebabCase('ServerVariable') // 'server-variable'
|
|
9
|
-
* toKebabCase('APIKeySecurityScheme') // 'api-key-security-scheme'
|
|
10
|
-
* toKebabCase('OAuthFlows') // 'oauth-flows'
|
|
11
|
-
* toKebabCase('already-kebab') // 'already-kebab'
|
|
12
|
-
* ```
|
|
13
|
-
*/
|
|
14
|
-
export const toKebabCase = (value: string): string =>
|
|
15
|
-
value
|
|
16
|
-
// Collapse known mixed-case acronyms before splitting so they stay together
|
|
17
|
-
.replace(/OAuth/g, 'Oauth')
|
|
18
|
-
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
|
19
|
-
.replace(/([a-z\d])([A-Z])/g, '$1-$2')
|
|
20
|
-
.toLowerCase()
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Derives a unique kebab-case filename from a URI ref.
|
|
24
|
-
*
|
|
25
|
-
* For a plain URI (no fragment), uses the path segments after the host,
|
|
26
|
-
* stripping version numbers, `.json` extension, and joining with `-`.
|
|
27
|
-
* For a URI with a fragment, appends the fragment's last path segment.
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* ```ts
|
|
31
|
-
* uriRefToFilename('http://asyncapi.com/definitions/3.1.0/channel.json')
|
|
32
|
-
* // 'channel'
|
|
33
|
-
* uriRefToFilename('http://asyncapi.com/bindings/kafka/0.5.0/channel.json')
|
|
34
|
-
* // 'kafka-channel-binding'
|
|
35
|
-
* uriRefToFilename('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')
|
|
36
|
-
* // 'sns-channel-queue'
|
|
37
|
-
* ```
|
|
38
|
-
*/
|
|
39
|
-
const uriRefToFilename = (uri: string): string => {
|
|
40
|
-
const hashIndex = uri.indexOf('#')
|
|
41
|
-
const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex)
|
|
42
|
-
const fragment = hashIndex === -1 ? '' : uri.slice(hashIndex + 1)
|
|
43
|
-
|
|
44
|
-
// Strip protocol + host, remove .json extension
|
|
45
|
-
const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, '')
|
|
46
|
-
const withoutExt = withoutProtocol.replace(/\.json$/, '')
|
|
47
|
-
|
|
48
|
-
// Drop structural/noise segments:
|
|
49
|
-
// - "definitions" and "$defs" container keys
|
|
50
|
-
// - Version numbers that immediately follow "definitions" (e.g. "3.1.0" in "definitions/3.1.0/channel")
|
|
51
|
-
// but NOT version numbers in other positions (e.g. "0.5.0" in "bindings/kafka/0.5.0/channel")
|
|
52
|
-
// since those are needed to disambiguate multiple versions of the same binding
|
|
53
|
-
const rawSegments = withoutExt.split('/')
|
|
54
|
-
const SKIP_KEYS = new Set(['definitions', '$defs'])
|
|
55
|
-
const segments: string[] = []
|
|
56
|
-
for (let i = 0; i < rawSegments.length; i++) {
|
|
57
|
-
const s = rawSegments[i] as string
|
|
58
|
-
if (SKIP_KEYS.has(s)) continue
|
|
59
|
-
// Skip a version segment only if the previous (non-skipped) segment was "definitions"
|
|
60
|
-
const prevRaw = rawSegments[i - 1]
|
|
61
|
-
if (/^\d+\.\d+/.test(s) && prevRaw !== undefined && SKIP_KEYS.has(prevRaw)) continue
|
|
62
|
-
segments.push(s)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Join remaining segments, converting to kebab-case and replacing dots with dashes
|
|
66
|
-
const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, '-')).join('-')
|
|
67
|
-
|
|
68
|
-
if (!fragment) return baseName
|
|
69
|
-
|
|
70
|
-
// Append the last meaningful segment of the fragment, skipping structural keys
|
|
71
|
-
const fragSegments = fragment.split('/').filter((s) => s && !SKIP_KEYS.has(s) && s !== 'properties')
|
|
72
|
-
const fragLast = fragSegments[fragSegments.length - 1]
|
|
73
|
-
if (!fragLast) return baseName
|
|
74
|
-
|
|
75
|
-
return `${baseName}-${toKebabCase(fragLast)}`
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Converts a JSON Schema $ref to a filename.
|
|
80
|
-
*
|
|
81
|
-
* Handles three ref forms:
|
|
82
|
-
* - Internal `#/$defs/contact` → `contact`
|
|
83
|
-
* - Internal `#/definitions/ServerVariable` → `server-variable`
|
|
84
|
-
* - URI `http://example.com/definitions/3.1.0/channel.json` → `channel`
|
|
85
|
-
* - URI with fragment `http://example.com/channel.json#/definitions/queue` → `channel-queue`
|
|
86
|
-
*
|
|
87
|
-
* @param ref - The $ref string
|
|
88
|
-
* @returns The filename without extension
|
|
89
|
-
*
|
|
90
|
-
* @example
|
|
91
|
-
* ```ts
|
|
92
|
-
* refToFilename('#/$defs/contact') // 'contact'
|
|
93
|
-
* refToFilename('#/$defs/server-variable') // 'server-variable'
|
|
94
|
-
* refToFilename('#/definitions/ServerVariable') // 'server-variable'
|
|
95
|
-
* refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
|
|
96
|
-
* refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
export const refToFilename = (ref: string): string => {
|
|
100
|
-
// URI ref — derive name from URI path
|
|
101
|
-
if (ref.startsWith('http://') || ref.startsWith('https://')) {
|
|
102
|
-
return uriRefToFilename(ref)
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// Internal ref — extract the last segment after the last /
|
|
106
|
-
const segments = ref.split('/')
|
|
107
|
-
// Non-null assertion is safe here: split always returns at least one element
|
|
108
|
-
let filename = segments[segments.length - 1] as string
|
|
109
|
-
|
|
110
|
-
// Normalise PascalCase/camelCase keys (e.g. from draft-07 "definitions") to kebab-case
|
|
111
|
-
if (/[A-Z]/.test(filename)) {
|
|
112
|
-
filename = toKebabCase(filename)
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
return filename
|
|
116
|
-
}
|
package/src/ref-to-name.ts
DELETED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { refToFilename } from './ref-to-filename'
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Converts a filename-like string to a PascalCase TypeScript identifier,
|
|
5
|
-
* appending an optional suffix.
|
|
6
|
-
*
|
|
7
|
-
* Word boundaries are *any* run of characters that cannot appear in a JS
|
|
8
|
-
* identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
|
|
9
|
-
* becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
|
|
10
|
-
* A leading digit is prefixed with `_`, and an otherwise-empty result falls back
|
|
11
|
-
* to `_`, so the output is always a usable identifier.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```ts
|
|
15
|
-
* kebabToPascal('server-variable') // 'ServerVariable'
|
|
16
|
-
* kebabToPascal('channel') // 'Channel'
|
|
17
|
-
* kebabToPascal('channel', 'Object') // 'ChannelObject'
|
|
18
|
-
* kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
|
|
19
|
-
* kebabToPascal('123abc') // '_123abc'
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
const kebabToPascal = (kebab: string, suffix: string): string => {
|
|
23
|
-
const words = kebab.split(/[^A-Za-z0-9]+/)
|
|
24
|
-
let pascalCase = ''
|
|
25
|
-
for (const word of words) {
|
|
26
|
-
if (word === '') continue
|
|
27
|
-
pascalCase += word.charAt(0).toUpperCase() + word.slice(1)
|
|
28
|
-
}
|
|
29
|
-
if (pascalCase === '') pascalCase = '_'
|
|
30
|
-
else if (/^[0-9]/.test(pascalCase)) pascalCase = `_${pascalCase}`
|
|
31
|
-
return pascalCase + suffix
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Converts a JSON Schema $ref to a type name.
|
|
36
|
-
* Derives the filename via `refToFilename` then converts to PascalCase,
|
|
37
|
-
* appending an optional suffix.
|
|
38
|
-
*
|
|
39
|
-
* Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
|
|
40
|
-
*
|
|
41
|
-
* @param ref - The $ref string
|
|
42
|
-
* @param suffix - Optional suffix appended to the PascalCase name. Defaults to
|
|
43
|
-
* `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
|
|
44
|
-
* @returns The type name in PascalCase with the suffix applied
|
|
45
|
-
*
|
|
46
|
-
* @example
|
|
47
|
-
* ```ts
|
|
48
|
-
* refToName('#/$defs/contact') // 'Contact'
|
|
49
|
-
* refToName('#/$defs/server-variable') // 'ServerVariable'
|
|
50
|
-
* refToName('#/$defs/contact', 'Object') // 'ContactObject'
|
|
51
|
-
* refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
|
|
52
|
-
* ```
|
|
53
|
-
*/
|
|
54
|
-
export const refToName = (ref: string, suffix = ''): string => kebabToPascal(refToFilename(ref), suffix)
|
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Replaces $dynamicRef with $ref in a schema using the provided anchor-to-path map.
|
|
5
|
-
*
|
|
6
|
-
* This creates a deep clone of the schema to avoid mutating the original, then walks
|
|
7
|
-
* the clone and converts any { $dynamicRef: "#meta" } to { $ref: "#/$defs/schema" }
|
|
8
|
-
* (or whatever the dynamicRefMap dictates).
|
|
9
|
-
*
|
|
10
|
-
* Walks both object properties and array elements, so a `$dynamicRef` nested
|
|
11
|
-
* inside a keyword whose value is an array of subschemas (`allOf`, `anyOf`,
|
|
12
|
-
* `oneOf`, `prefixItems`, …) is rewritten too. The build system generates a
|
|
13
|
-
* separate file per `$def`, so each schema walked here is relatively shallow.
|
|
14
|
-
*/
|
|
15
|
-
export const resolveDynamicRefs = (schema: JSONSchema, dynamicRefMap: Record<string, string>): JSONSchema => {
|
|
16
|
-
if (typeof schema !== 'object' || schema === null) {
|
|
17
|
-
return schema
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// Skip if there are no dynamic refs to resolve
|
|
21
|
-
if (Object.keys(dynamicRefMap).length === 0) {
|
|
22
|
-
return schema
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// Cheap read-only pre-scan: most subschemas carry no `$dynamicRef`, so returning
|
|
26
|
-
// the original untouched avoids a full deep clone (and its allocation) on every
|
|
27
|
-
// node of every generator's walk when the document as a whole *does* use them.
|
|
28
|
-
if (!containsDynamicRef(schema)) {
|
|
29
|
-
return schema
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const clone = JSON.parse(JSON.stringify(schema)) as Record<string, unknown>
|
|
33
|
-
|
|
34
|
-
const walk = (obj: unknown): void => {
|
|
35
|
-
if (typeof obj !== 'object' || obj === null) {
|
|
36
|
-
return
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (Array.isArray(obj)) {
|
|
40
|
-
for (const item of obj) walk(item)
|
|
41
|
-
return
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const record = obj as Record<string, unknown>
|
|
45
|
-
|
|
46
|
-
if ('$dynamicRef' in record && typeof record['$dynamicRef'] === 'string') {
|
|
47
|
-
const resolved = dynamicRefMap[record['$dynamicRef'] as string]
|
|
48
|
-
if (resolved) {
|
|
49
|
-
record['$ref'] = resolved
|
|
50
|
-
delete record['$dynamicRef']
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
for (const key in record) {
|
|
55
|
-
walk(record[key])
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
walk(clone)
|
|
60
|
-
return clone as JSONSchema
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** True if `value` contains a `$dynamicRef` string anywhere in its subtree. */
|
|
64
|
-
const containsDynamicRef = (value: unknown): boolean => {
|
|
65
|
-
if (typeof value !== 'object' || value === null) return false
|
|
66
|
-
if (Array.isArray(value)) {
|
|
67
|
-
for (const item of value) if (containsDynamicRef(item)) return true
|
|
68
|
-
return false
|
|
69
|
-
}
|
|
70
|
-
const record = value as Record<string, unknown>
|
|
71
|
-
if (typeof record['$dynamicRef'] === 'string') return true
|
|
72
|
-
for (const key in record) if (containsDynamicRef(record[key])) return true
|
|
73
|
-
return false
|
|
74
|
-
}
|
package/src/resolve-ref.ts
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Navigates a JSON Pointer fragment (e.g. `/$defs/foo` or `/definitions/bar`)
|
|
3
|
-
* through a schema object, returning the target or undefined if not found.
|
|
4
|
-
*/
|
|
5
|
-
const navigatePointer = (pointer: string, schema: Record<string, unknown>): Record<string, unknown> | undefined => {
|
|
6
|
-
const parts = pointer.split('/').filter(Boolean)
|
|
7
|
-
let current = schema
|
|
8
|
-
|
|
9
|
-
for (const part of parts) {
|
|
10
|
-
const decodedPart = part.replace(/~1/g, '/').replace(/~0/g, '~')
|
|
11
|
-
|
|
12
|
-
if (current && typeof current === 'object' && decodedPart in current) {
|
|
13
|
-
const next = current[decodedPart as keyof typeof current]
|
|
14
|
-
if (typeof next === 'object' && next !== null) {
|
|
15
|
-
current = next as Record<string, unknown>
|
|
16
|
-
} else {
|
|
17
|
-
return undefined
|
|
18
|
-
}
|
|
19
|
-
} else {
|
|
20
|
-
return undefined
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
return current
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Resolves a JSON Schema $ref pointer to the actual schema definition.
|
|
29
|
-
*
|
|
30
|
-
* Supports three ref forms:
|
|
31
|
-
* - Internal: `#/$defs/contact` — navigates the root schema by JSON Pointer
|
|
32
|
-
* - URI key: `http://example.com/foo.json` — looks up the key directly in `$defs`
|
|
33
|
-
* - URI with fragment: `http://example.com/foo.json#/definitions/bar` — looks up
|
|
34
|
-
* the base URI in `$defs`, then navigates the fragment within that definition
|
|
35
|
-
*
|
|
36
|
-
* @param ref - The $ref string
|
|
37
|
-
* @param rootSchema - The root schema containing the definitions
|
|
38
|
-
* @returns The resolved schema or undefined if not found
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```ts
|
|
42
|
-
* const rootSchema = {
|
|
43
|
-
* $defs: {
|
|
44
|
-
* contact: { type: 'object', properties: { email: { type: 'string' } } },
|
|
45
|
-
* 'http://example.com/server.json': { type: 'object' },
|
|
46
|
-
* }
|
|
47
|
-
* }
|
|
48
|
-
* resolveRef('#/$defs/contact', rootSchema)
|
|
49
|
-
* resolveRef('http://example.com/server.json', rootSchema)
|
|
50
|
-
* ```
|
|
51
|
-
*/
|
|
52
|
-
export const resolveRef = (ref: string, rootSchema: Record<string, unknown>): Record<string, unknown> | undefined => {
|
|
53
|
-
// Internal reference: navigate from root by JSON Pointer
|
|
54
|
-
if (ref.startsWith('#')) {
|
|
55
|
-
return navigatePointer(ref.slice(1), rootSchema)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// URI ref: may have a fragment (e.g. "http://foo.com/bar.json#/definitions/baz")
|
|
59
|
-
// A trailing bare "#" (e.g. "http://foo.com/schema#") means "the whole document" — treat as no fragment
|
|
60
|
-
const hashIndex = ref.indexOf('#')
|
|
61
|
-
const baseUri = hashIndex === -1 ? ref : ref.slice(0, hashIndex)
|
|
62
|
-
const rawFragment = hashIndex === -1 ? '' : ref.slice(hashIndex + 1)
|
|
63
|
-
const fragment = rawFragment === '' || rawFragment === '/' ? '' : rawFragment
|
|
64
|
-
|
|
65
|
-
// Look up the base URI as a key in $defs
|
|
66
|
-
const defs = rootSchema['$defs']
|
|
67
|
-
if (typeof defs !== 'object' || defs === null) return undefined
|
|
68
|
-
|
|
69
|
-
const defsRecord = defs as Record<string, unknown>
|
|
70
|
-
const base = defsRecord[baseUri]
|
|
71
|
-
if (typeof base !== 'object' || base === null) return undefined
|
|
72
|
-
|
|
73
|
-
// No fragment — return the definition directly
|
|
74
|
-
if (!fragment) return base as Record<string, unknown>
|
|
75
|
-
|
|
76
|
-
// Normalize the fragment: draft-07 schemas use `/definitions/` but after
|
|
77
|
-
// upgradeDraft07Schema the key is renamed to `/$defs/`
|
|
78
|
-
const normalizedFragment = fragment.replace(/^\/definitions\//, '/$defs/')
|
|
79
|
-
|
|
80
|
-
// Navigate the fragment within the resolved definition
|
|
81
|
-
return navigatePointer(normalizedFragment, base as Record<string, unknown>)
|
|
82
|
-
}
|
package/src/safe-accessor.ts
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Checks whether a property name is a valid JavaScript identifier that can be
|
|
3
|
-
* accessed with dot notation. Property names containing hyphens, dots, or
|
|
4
|
-
* other special characters (e.g., "x-linkedin") must use bracket notation.
|
|
5
|
-
*/
|
|
6
|
-
const JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Generates a safe property accessor for a given key on an object variable.
|
|
10
|
-
* Uses dot notation for simple identifiers and bracket notation for keys
|
|
11
|
-
* that contain special characters like hyphens.
|
|
12
|
-
*
|
|
13
|
-
* @param variable - The variable name (e.g., "input", "input?")
|
|
14
|
-
* @param key - The property name to access
|
|
15
|
-
* @returns A valid JS property access expression
|
|
16
|
-
*
|
|
17
|
-
* @example
|
|
18
|
-
* safeAccessor("input", "name") // "input.name"
|
|
19
|
-
* safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
|
|
20
|
-
* safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
|
|
21
|
-
*/
|
|
22
|
-
export const safeAccessor = (variable: string, key: string): string => {
|
|
23
|
-
if (JS_IDENTIFIER.test(key)) {
|
|
24
|
-
return `${variable}.${key}`
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Bracket keys are schema-controlled, so escape via JSON.stringify — a key like
|
|
28
|
-
// `it's` or `a']; evil(); //` would otherwise break or hijack the generated code.
|
|
29
|
-
const literal = JSON.stringify(key)
|
|
30
|
-
|
|
31
|
-
// Handle optional chaining: "input?" -> "input?.['key']"
|
|
32
|
-
if (variable.endsWith('?')) {
|
|
33
|
-
return `${variable}.[${literal}]`
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return `${variable}[${literal}]`
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Generates a safe property key for use in object literals.
|
|
41
|
-
* Wraps keys that are not valid identifiers in quotes.
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* safeKey("name") // "name"
|
|
45
|
-
* safeKey("x-linkedin") // '"x-linkedin"'
|
|
46
|
-
*/
|
|
47
|
-
export const safeKey = (key: string): string => {
|
|
48
|
-
if (JS_IDENTIFIER.test(key)) {
|
|
49
|
-
return key
|
|
50
|
-
}
|
|
51
|
-
// Schema-controlled keys must be escaped; a bare-quoted `it's` produces broken TS.
|
|
52
|
-
return JSON.stringify(key)
|
|
53
|
-
}
|