@amritk/helpers 0.10.0 → 0.10.2

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.
Files changed (37) hide show
  1. package/dist/escape-regex-pattern.d.ts +15 -5
  2. package/dist/escape-regex-pattern.js +48 -10
  3. package/dist/generate-index-barrel.js +3 -2
  4. package/dist/generate-type-definition.js +72 -53
  5. package/dist/multiple-of-check.d.ts +4 -0
  6. package/dist/multiple-of-check.js +30 -0
  7. package/dist/parse-documentation.js +6 -2
  8. package/dist/ref-to-name.js +17 -2
  9. package/dist/resolve-dynamic-refs.js +24 -0
  10. package/dist/safe-accessor.d.ts +3 -3
  11. package/dist/safe-accessor.js +10 -6
  12. package/dist/validate-record.js +11 -1
  13. package/dist/walk-ref-graph.js +4 -2
  14. package/package.json +4 -2
  15. package/src/build-dynamic-ref-map.ts +42 -0
  16. package/src/derive-root-type-name.ts +42 -0
  17. package/src/escape-regex-pattern.ts +59 -0
  18. package/src/extract-dynamic-anchor-defs.ts +33 -0
  19. package/src/extract-refs.ts +73 -0
  20. package/src/generate-index-barrel.ts +63 -0
  21. package/src/generate-type-definition.ts +599 -0
  22. package/src/has-ref.ts +10 -0
  23. package/src/is-object.ts +15 -0
  24. package/src/mjst-extension.ts +81 -0
  25. package/src/multiple-of-check.ts +32 -0
  26. package/src/parse-documentation.ts +177 -0
  27. package/src/ref-to-filename.ts +116 -0
  28. package/src/ref-to-name.ts +54 -0
  29. package/src/resolve-dynamic-refs.ts +74 -0
  30. package/src/resolve-ref.ts +82 -0
  31. package/src/safe-accessor.ts +53 -0
  32. package/src/schema-guards.ts +195 -0
  33. package/src/unknown-key-check.ts +68 -0
  34. package/src/upgrade-draft07-schema.ts +179 -0
  35. package/src/validate-array.ts +15 -0
  36. package/src/validate-record.ts +28 -0
  37. package/src/walk-ref-graph.ts +186 -0
@@ -0,0 +1,195 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
+
3
+ type SchemaObject = Exclude<JSONSchema, false | boolean>
4
+
5
+ /** Type guard to check if schema is not false */
6
+ export const isSchemaObject = (schema: JSONSchema): schema is SchemaObject => {
7
+ return typeof schema === 'object' && schema !== null && typeof schema !== 'boolean'
8
+ }
9
+
10
+ /** Type guard to check if schema has a type property */
11
+ export const hasType = (schema: JSONSchema): schema is SchemaObject & { type: string } => {
12
+ return isSchemaObject(schema) && 'type' in schema && typeof schema.type === 'string'
13
+ }
14
+
15
+ /** Type guard to check if schema is an object schema */
16
+ export const isObjectSchema = (schema: JSONSchema): schema is JSONSchema.Object => {
17
+ return isSchemaObject(schema) && (('type' in schema && schema.type === 'object') || 'properties' in schema)
18
+ }
19
+
20
+ /** Type guard to check if schema has properties */
21
+ export const hasProperties = (
22
+ schema: JSONSchema,
23
+ ): schema is SchemaObject & { properties: Record<string, JSONSchema> } => {
24
+ return (
25
+ isSchemaObject(schema) &&
26
+ 'properties' in schema &&
27
+ typeof schema.properties === 'object' &&
28
+ schema.properties !== null
29
+ )
30
+ }
31
+
32
+ /** Type guard to check if schema has enum */
33
+ export const hasEnum = (schema: JSONSchema): schema is SchemaObject & { enum: readonly unknown[] } => {
34
+ return isSchemaObject(schema) && 'enum' in schema && Array.isArray(schema.enum)
35
+ }
36
+
37
+ /** Type guard to check if schema has const */
38
+ export const hasConst = (schema: JSONSchema): schema is SchemaObject & { const: unknown } => {
39
+ return isSchemaObject(schema) && 'const' in schema
40
+ }
41
+
42
+ /** Type guard to check if schema has pattern */
43
+ export const hasPattern = (schema: JSONSchema): schema is SchemaObject & { pattern: string } => {
44
+ return isSchemaObject(schema) && 'pattern' in schema && typeof schema.pattern === 'string'
45
+ }
46
+
47
+ /** Type guard to check if schema has format */
48
+ export const hasFormat = (schema: JSONSchema): schema is SchemaObject & { format: string } => {
49
+ return isSchemaObject(schema) && 'format' in schema && typeof schema.format === 'string'
50
+ }
51
+
52
+ /** Type guard to check if schema has default */
53
+ export const hasDefault = (schema: JSONSchema): schema is SchemaObject & { default: unknown } => {
54
+ return isSchemaObject(schema) && 'default' in schema
55
+ }
56
+
57
+ /** Type guard to check if schema has examples */
58
+ export const hasExamples = (schema: JSONSchema): schema is SchemaObject & { examples: readonly unknown[] } => {
59
+ return isSchemaObject(schema) && 'examples' in schema && Array.isArray(schema.examples)
60
+ }
61
+
62
+ /** Type guard to check if schema has oneOf */
63
+ export const hasOneOf = (schema: JSONSchema): schema is SchemaObject & { oneOf: readonly JSONSchema[] } => {
64
+ return isSchemaObject(schema) && 'oneOf' in schema && Array.isArray(schema.oneOf)
65
+ }
66
+
67
+ /** Type guard to check if schema has anyOf */
68
+ export const hasAnyOf = (schema: JSONSchema): schema is SchemaObject & { anyOf: readonly JSONSchema[] } => {
69
+ return isSchemaObject(schema) && 'anyOf' in schema && Array.isArray(schema.anyOf)
70
+ }
71
+
72
+ /** Type guard to check if schema has allOf */
73
+ export const hasAllOf = (schema: JSONSchema): schema is SchemaObject & { allOf: readonly JSONSchema[] } => {
74
+ return isSchemaObject(schema) && 'allOf' in schema && Array.isArray(schema.allOf)
75
+ }
76
+
77
+ /** Type guard to check if schema has required */
78
+ export const hasRequired = (schema: JSONSchema): schema is SchemaObject & { required: readonly string[] } => {
79
+ return isSchemaObject(schema) && 'required' in schema && Array.isArray(schema.required)
80
+ }
81
+
82
+ /** Type guard to check if schema has items (and it's not just boolean) */
83
+ export const hasItems = (schema: JSONSchema): schema is SchemaObject & { items: SchemaObject } => {
84
+ return (
85
+ isSchemaObject(schema) &&
86
+ 'items' in schema &&
87
+ typeof schema.items === 'object' &&
88
+ schema.items !== null &&
89
+ typeof schema.items !== 'boolean'
90
+ )
91
+ }
92
+
93
+ /** Type guard to check if schema has additionalProperties */
94
+ export const hasAdditionalProperties = (
95
+ schema: JSONSchema,
96
+ ): schema is SchemaObject & { additionalProperties: JSONSchema | boolean } => {
97
+ return isSchemaObject(schema) && 'additionalProperties' in schema
98
+ }
99
+
100
+ /** Type guard to check if schema has minLength */
101
+ export const hasMinLength = (schema: JSONSchema): schema is SchemaObject & { minLength: number } => {
102
+ return isSchemaObject(schema) && 'minLength' in schema && typeof schema.minLength === 'number'
103
+ }
104
+
105
+ /** Type guard to check if schema has maxLength */
106
+ export const hasMaxLength = (schema: JSONSchema): schema is SchemaObject & { maxLength: number } => {
107
+ return isSchemaObject(schema) && 'maxLength' in schema && typeof schema.maxLength === 'number'
108
+ }
109
+
110
+ /** Type guard to check if schema has minimum */
111
+ export const hasMinimum = (schema: JSONSchema): schema is SchemaObject & { minimum: number } => {
112
+ return isSchemaObject(schema) && 'minimum' in schema && typeof schema.minimum === 'number'
113
+ }
114
+
115
+ /** Type guard to check if schema has maximum */
116
+ export const hasMaximum = (schema: JSONSchema): schema is SchemaObject & { maximum: number } => {
117
+ return isSchemaObject(schema) && 'maximum' in schema && typeof schema.maximum === 'number'
118
+ }
119
+
120
+ /** Type guard to check if schema has exclusiveMinimum */
121
+ export const hasExclusiveMinimum = (schema: JSONSchema): schema is SchemaObject & { exclusiveMinimum: number } => {
122
+ return isSchemaObject(schema) && 'exclusiveMinimum' in schema && typeof schema.exclusiveMinimum === 'number'
123
+ }
124
+
125
+ /** Type guard to check if schema has exclusiveMaximum */
126
+ export const hasExclusiveMaximum = (schema: JSONSchema): schema is SchemaObject & { exclusiveMaximum: number } => {
127
+ return isSchemaObject(schema) && 'exclusiveMaximum' in schema && typeof schema.exclusiveMaximum === 'number'
128
+ }
129
+
130
+ /**
131
+ * Draft-04 expressed a strict lower bound as a boolean `exclusiveMinimum: true`
132
+ * paired with `minimum`, where draft-06+ uses a standalone numeric keyword. True
133
+ * only for that legacy boolean form, so callers can tighten the `minimum` compare.
134
+ */
135
+ export const hasStrictExclusiveMinimum = (schema: JSONSchema): boolean => {
136
+ if (!isSchemaObject(schema)) return false
137
+ const flag: unknown = schema.exclusiveMinimum
138
+ return flag === true
139
+ }
140
+
141
+ /** Draft-04 boolean `exclusiveMaximum: true` paired with `maximum`. See {@link hasStrictExclusiveMinimum}. */
142
+ export const hasStrictExclusiveMaximum = (schema: JSONSchema): boolean => {
143
+ if (!isSchemaObject(schema)) return false
144
+ const flag: unknown = schema.exclusiveMaximum
145
+ return flag === true
146
+ }
147
+
148
+ /** Type guard to check if schema has multipleOf */
149
+ export const hasMultipleOf = (schema: JSONSchema): schema is SchemaObject & { multipleOf: number } => {
150
+ return isSchemaObject(schema) && 'multipleOf' in schema && typeof schema.multipleOf === 'number'
151
+ }
152
+
153
+ /** Type guard to check if schema has minItems */
154
+ export const hasMinItems = (schema: JSONSchema): schema is SchemaObject & { minItems: number } => {
155
+ return isSchemaObject(schema) && 'minItems' in schema && typeof schema.minItems === 'number'
156
+ }
157
+
158
+ /** Type guard to check if schema has maxItems */
159
+ export const hasMaxItems = (schema: JSONSchema): schema is SchemaObject & { maxItems: number } => {
160
+ return isSchemaObject(schema) && 'maxItems' in schema && typeof schema.maxItems === 'number'
161
+ }
162
+
163
+ /** Type guard to check if schema has uniqueItems */
164
+ export const hasUniqueItems = (schema: JSONSchema): schema is SchemaObject & { uniqueItems: boolean } => {
165
+ return isSchemaObject(schema) && 'uniqueItems' in schema && typeof schema.uniqueItems === 'boolean'
166
+ }
167
+
168
+ /** Type guard to check if schema has minProperties */
169
+ export const hasMinProperties = (schema: JSONSchema): schema is SchemaObject & { minProperties: number } => {
170
+ return isSchemaObject(schema) && 'minProperties' in schema && typeof schema.minProperties === 'number'
171
+ }
172
+
173
+ /** Type guard to check if schema has maxProperties */
174
+ export const hasMaxProperties = (schema: JSONSchema): schema is SchemaObject & { maxProperties: number } => {
175
+ return isSchemaObject(schema) && 'maxProperties' in schema && typeof schema.maxProperties === 'number'
176
+ }
177
+
178
+ /** Type guard to check if schema has dependentRequired (2020-12). */
179
+ export const hasDependentRequired = (
180
+ schema: JSONSchema,
181
+ ): schema is SchemaObject & { dependentRequired: Record<string, readonly string[]> } => {
182
+ return (
183
+ isSchemaObject(schema) &&
184
+ 'dependentRequired' in schema &&
185
+ typeof schema.dependentRequired === 'object' &&
186
+ schema.dependentRequired !== null
187
+ )
188
+ }
189
+
190
+ /** Type guard to check if schema has a propertyNames subschema. */
191
+ export const hasPropertyNames = (schema: JSONSchema): schema is SchemaObject & { propertyNames: JSONSchema } => {
192
+ return isSchemaObject(schema) && 'propertyNames' in schema
193
+ }
194
+
195
+ export { hasRef } from './has-ref'
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Default key-count cutoff below which an unknown-key sweep inlines `!==`
3
+ * comparisons instead of a hoisted `Set`. Chosen so typical schema objects stay
4
+ * on the faster inline path while pathologically wide objects fall back to the
5
+ * `Set`'s O(1) lookup.
6
+ */
7
+ export const INLINE_KEY_LIMIT = 16
8
+
9
+ /** The pieces a caller needs to emit an `additionalProperties: false` sweep. */
10
+ export type UnknownKeyCheck = {
11
+ /**
12
+ * Declarations to emit once before the sweep — a single hoisted `Set` when the
13
+ * key count exceeds the inline limit, otherwise empty (the inline form is
14
+ * stateless). Each entry is a full statement with no trailing `;` or newline,
15
+ * so callers can punctuate to match their surrounding style.
16
+ */
17
+ readonly declarations: readonly string[]
18
+ /**
19
+ * Builds the boolean expression that is true when `keyVar` is NOT one of the
20
+ * known keys — an inline chain of `!==` comparisons, a `Set.has` miss, or the
21
+ * constant `true` when there are no known keys (every key is undeclared).
22
+ */
23
+ readonly isUnknown: (keyVar: string) => string
24
+ /**
25
+ * The complement of {@link isUnknown}: true when `keyVar` IS a known key — an
26
+ * inline chain of `===` comparisons, a `Set.has` hit, or the constant `false`
27
+ * when there are no known keys.
28
+ */
29
+ readonly isKnown: (keyVar: string) => string
30
+ }
31
+
32
+ /**
33
+ * Builds the "is this an undeclared key" test used by `additionalProperties:
34
+ * false` sweeps in the generated parsers and validators.
35
+ *
36
+ * For a small number of known keys V8 evaluates a chain of `!==` string
37
+ * comparisons faster than `Set.has` (which has to hash the string), and the
38
+ * inline form skips the per-module `Set` allocation — the same shape Ajv and
39
+ * TypeBox compile to. Above `inlineLimit` the chain grows long enough that the
40
+ * `Set`'s O(1) lookup wins, so a `Set` named `setName` is hoisted instead.
41
+ *
42
+ * @example
43
+ * const check = unknownKeyCheck(['id', 'name'], '_knownKeys0')
44
+ * check.declarations // []
45
+ * check.isUnknown('_k') // '_k !== "id" && _k !== "name"'
46
+ * check.isKnown('_k') // '_k === "id" || _k === "name"'
47
+ */
48
+ export const unknownKeyCheck = (
49
+ knownKeys: readonly string[],
50
+ setName: string,
51
+ inlineLimit: number = INLINE_KEY_LIMIT,
52
+ ): UnknownKeyCheck => {
53
+ if (knownKeys.length === 0) {
54
+ return { declarations: [], isUnknown: () => 'true', isKnown: () => 'false' }
55
+ }
56
+ if (knownKeys.length <= inlineLimit) {
57
+ return {
58
+ declarations: [],
59
+ isUnknown: (keyVar) => knownKeys.map((key) => `${keyVar} !== ${JSON.stringify(key)}`).join(' && '),
60
+ isKnown: (keyVar) => knownKeys.map((key) => `${keyVar} === ${JSON.stringify(key)}`).join(' || '),
61
+ }
62
+ }
63
+ return {
64
+ declarations: [`const ${setName} = new Set(${JSON.stringify(knownKeys)})`],
65
+ isUnknown: (keyVar) => `!${setName}.has(${keyVar})`,
66
+ isKnown: (keyVar) => `${setName}.has(${keyVar})`,
67
+ }
68
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Upgrades a JSON Schema draft-07 document to be compatible with the
3
+ * draft 2020-12 conventions used by the build pipeline.
4
+ *
5
+ * Draft-07 schemas differ from 2020-12 in two ways that affect our pipeline:
6
+ * - They use `definitions` instead of `$defs`
7
+ * - Their `definitions` keys (and `$ref` values) may be full URIs
8
+ * (e.g. `http://asyncapi.com/definitions/3.1.0/channel.json`) rather than
9
+ * short names (e.g. `channel`)
10
+ *
11
+ * This function:
12
+ * 1. Renames `definitions` → `$defs` at the root level only
13
+ * 2. Hoists any nested `$defs` (originally `definitions` inside sub-schemas)
14
+ * up to the root `$defs` with a prefixed name, rewriting internal refs
15
+ * so they resolve correctly from the root
16
+ * 3. Rewrites bare `$ref: "#"` self-references within each definition to
17
+ * point back to that definition's root-level `$defs` entry
18
+ *
19
+ * Only applied when the schema declares `$schema: http://json-schema.org/draft-07/schema`.
20
+ */
21
+
22
+ import { refToFilename, toKebabCase } from './ref-to-filename'
23
+
24
+ /**
25
+ * Returns true if the schema is a draft-07 document that needs upgrading.
26
+ */
27
+ export const isDraft07Schema = (schema: Record<string, unknown>): boolean =>
28
+ typeof schema['$schema'] === 'string' && schema['$schema'].includes('draft-07')
29
+
30
+ /**
31
+ * Rewrites `$ref` values in a schema tree using an explicit string→string map.
32
+ * Also rewrites bare `$ref: "#"` to the given `selfRef` path when provided.
33
+ */
34
+ const rewriteRefs = (obj: unknown, refMap: ReadonlyMap<string, string>, selfRef?: string): unknown => {
35
+ if (typeof obj !== 'object' || obj === null) return obj
36
+ if (Array.isArray(obj)) return obj.map((item) => rewriteRefs(item, refMap, selfRef))
37
+
38
+ const record = obj as Record<string, unknown>
39
+ const result: Record<string, unknown> = {}
40
+
41
+ for (const [key, value] of Object.entries(record)) {
42
+ if (key === '$ref' && typeof value === 'string') {
43
+ if (refMap.has(value)) {
44
+ result[key] = refMap.get(value)
45
+ } else if (value === '#' && selfRef) {
46
+ result[key] = selfRef
47
+ } else {
48
+ result[key] = value
49
+ }
50
+ } else {
51
+ result[key] = rewriteRefs(value, refMap, selfRef)
52
+ }
53
+ }
54
+
55
+ return result
56
+ }
57
+
58
+ /**
59
+ * Hoists nested `$defs` from each root-level definition up to the root `$defs`.
60
+ *
61
+ * When a definition contains its own `$defs` (originally `definitions` in draft-07,
62
+ * e.g. the json-schema meta-schema or avro schema), those nested defs are moved to
63
+ * the root with a `parentName-childName` prefix. All internal `#/$defs/X` refs
64
+ * within the parent and its nested defs are rewritten to `#/$defs/parentName-X`.
65
+ * Bare `$ref: "#"` within nested defs is rewritten to `#/$defs/parentName`.
66
+ */
67
+ const hoistNestedDefs = (defs: Record<string, unknown>): Record<string, unknown> => {
68
+ const hoisted: Record<string, unknown> = {}
69
+
70
+ for (const [parentName, parentSchema] of Object.entries(defs)) {
71
+ if (typeof parentSchema !== 'object' || parentSchema === null) {
72
+ hoisted[parentName] = parentSchema
73
+ continue
74
+ }
75
+
76
+ const parentObj = parentSchema as Record<string, unknown>
77
+ const nestedDefs = parentObj['$defs'] as Record<string, unknown> | undefined
78
+
79
+ if (!nestedDefs || typeof nestedDefs !== 'object') {
80
+ hoisted[parentName] = parentSchema
81
+ continue
82
+ }
83
+
84
+ // Derive a short kebab-case prefix from the parent name (which may be a URI)
85
+ const parentPrefix =
86
+ parentName.startsWith('http://') || parentName.startsWith('https://') ? refToFilename(parentName) : parentName
87
+
88
+ // Build a map from local ref → hoisted ref for every nested def
89
+ const localToHoisted = new Map<string, string>()
90
+ for (const localName of Object.keys(nestedDefs)) {
91
+ const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`
92
+ localToHoisted.set(`#/$defs/${localName}`, `#/$defs/${hoistedName}`)
93
+ }
94
+
95
+ const selfRef = `#/$defs/${parentPrefix}`
96
+
97
+ // Rewrite refs in the parent. Keep the nested $defs in place so that
98
+ // URI-with-fragment refs (e.g. "http://foo.json#/$defs/queue") can still
99
+ // navigate into the parent's nested defs after resolution.
100
+ const rewrittenParent = rewriteRefs(parentObj, localToHoisted, selfRef) as Record<string, unknown>
101
+ hoisted[parentName] = rewrittenParent
102
+
103
+ // Hoist each nested def, rewriting its internal refs too
104
+ for (const [localName, localSchema] of Object.entries(nestedDefs)) {
105
+ const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`
106
+ hoisted[hoistedName] = rewriteRefs(localSchema, localToHoisted, selfRef)
107
+ }
108
+ }
109
+
110
+ return hoisted
111
+ }
112
+
113
+ /**
114
+ * Upgrades a draft-07 schema so it is compatible with the build pipeline.
115
+ * If the schema is not draft-07, it is returned unchanged.
116
+ *
117
+ * @param schema - The raw JSON Schema (any draft)
118
+ * @returns The schema with `definitions` renamed to `$defs` at the root,
119
+ * nested defs hoisted to the root, and internal refs rewritten
120
+ */
121
+ export const upgradeDraft07Schema = (schema: Record<string, unknown>): Record<string, unknown> => {
122
+ if (!isDraft07Schema(schema)) return schema
123
+
124
+ // Rename root-level `definitions` to `$defs` (keep all other keys as-is)
125
+ const { definitions, $schema: _, ...rest } = schema
126
+ const rawDefs = (definitions ?? {}) as Record<string, unknown>
127
+
128
+ // Recursively rename `definitions` → `$defs` inside each definition's body
129
+ // so nested defs are accessible before hoisting
130
+ const renamedDefs: Record<string, unknown> = {}
131
+ for (const [key, value] of Object.entries(rawDefs)) {
132
+ renamedDefs[key] = renameNestedDefs(value)
133
+ }
134
+
135
+ // Hoist nested $defs up to root so the pipeline can resolve all refs flatly
136
+ const hoistedDefs = hoistNestedDefs(renamedDefs)
137
+
138
+ // Add short-name aliases for URI-keyed definitions so that internal refs
139
+ // like `#/$defs/draft-07-schema` (produced by self-ref rewriting in hoistNestedDefs)
140
+ // resolve correctly alongside the original URI key lookups.
141
+ for (const key of Object.keys(hoistedDefs)) {
142
+ if (key.startsWith('http://') || key.startsWith('https://')) {
143
+ const shortName = refToFilename(key)
144
+ if (shortName && !(shortName in hoistedDefs)) {
145
+ hoistedDefs[shortName] = hoistedDefs[key]
146
+ }
147
+ }
148
+ }
149
+
150
+ return {
151
+ ...rest,
152
+ $defs: hoistedDefs,
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Recursively renames `definitions` → `$defs` within a schema value and
158
+ * rewrites `$ref: "#/definitions/X"` to `$ref: "#/$defs/X"` so that
159
+ * `hoistNestedDefs` can map them to their hoisted root-level equivalents.
160
+ * Does NOT hoist — hoisting is done separately at the root level.
161
+ */
162
+ const renameNestedDefs = (obj: unknown): unknown => {
163
+ if (typeof obj !== 'object' || obj === null) return obj
164
+ if (Array.isArray(obj)) return obj.map(renameNestedDefs)
165
+
166
+ const record = obj as Record<string, unknown>
167
+ const result: Record<string, unknown> = {}
168
+
169
+ for (const [key, value] of Object.entries(record)) {
170
+ if (key === '$ref' && typeof value === 'string' && value.startsWith('#/definitions/')) {
171
+ result[key] = value.replace('#/definitions/', '#/$defs/')
172
+ } else {
173
+ const outKey = key === 'definitions' ? '$defs' : key
174
+ result[outKey] = renameNestedDefs(value)
175
+ }
176
+ }
177
+
178
+ return result
179
+ }
@@ -0,0 +1,15 @@
1
+ /** Parses the items of an array with a parser function */
2
+ export const validateArray = (input: unknown, parser: (input: unknown) => unknown) => {
3
+ if (!Array.isArray(input)) {
4
+ return []
5
+ }
6
+
7
+ // Pre-allocate the result array for better performance than push()
8
+ const len = input.length
9
+ const result = new Array(len)
10
+ for (let i = 0; i < len; i++) {
11
+ result[i] = parser(input[i])
12
+ }
13
+
14
+ return result
15
+ }
@@ -0,0 +1,28 @@
1
+ import { isObject } from './is-object'
2
+
3
+ /**
4
+ * Parses the values of a record with a parser function.
5
+ * Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
6
+ */
7
+ export const validateRecord = (input: unknown, parser: (input: unknown) => unknown) => {
8
+ if (!isObject(input)) {
9
+ return {}
10
+ }
11
+
12
+ const record = input as Record<string, unknown>
13
+ const result: Record<string, unknown> = {}
14
+ for (const key in record) {
15
+ const value = parser(record[key])
16
+ // A plain assignment of `__proto__` invokes the prototype setter and
17
+ // corrupts `result`'s prototype (a prototype-pollution vector for untrusted
18
+ // input). Define it as an own data property instead so it round-trips as a
19
+ // normal key, matching every other property.
20
+ if (key === '__proto__') {
21
+ Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true })
22
+ } else {
23
+ result[key] = value
24
+ }
25
+ }
26
+
27
+ return result
28
+ }
@@ -0,0 +1,186 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
+
3
+ import { buildDynamicRefMap } from './build-dynamic-ref-map'
4
+ import { extractDynamicAnchorDefs } from './extract-dynamic-anchor-defs'
5
+ import { extractRefs } from './extract-refs'
6
+ import { refToFilename } from './ref-to-filename'
7
+ import { refToName } from './ref-to-name'
8
+ import { resolveDynamicRefs } from './resolve-dynamic-refs'
9
+ import { resolveRef } from './resolve-ref'
10
+ import { upgradeDraft07Schema } from './upgrade-draft07-schema'
11
+
12
+ /**
13
+ * One node of the `$ref` graph, handed to the `visit` callback. Everything a
14
+ * generator needs to emit a single output file is pre-computed here so the
15
+ * traversal, naming, and `$dynamicRef` rewriting live in one place instead of
16
+ * being copy-pasted into every generator.
17
+ */
18
+ export type RefNode = {
19
+ /** The `$ref` string this node was reached through, or `undefined` for the root schema. */
20
+ ref: string | undefined
21
+ /** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
22
+ typeName: string
23
+ /** kebab-case filename without extension — the lowercased root type name, or `refToFilename(ref)`. */
24
+ filename: string
25
+ /** The subschema to generate, with any `$dynamicRef` already rewritten to `$ref`. */
26
+ schema: JSONSchema
27
+ /** The upgraded root document, for callers that resolve imports against it. */
28
+ rootSchema: Record<string, unknown>
29
+ /** True for the root schema node, which is always visited first. */
30
+ isRoot: boolean
31
+ }
32
+
33
+ /** Options controlling how `$ref`-derived names are produced. */
34
+ export type WalkRefGraphOptions = {
35
+ /**
36
+ * Suffix appended to every `$ref`-derived type name (e.g. `'Object'` →
37
+ * `ContactObject`). The root type name is used verbatim and is not affected.
38
+ * Defaults to `''`.
39
+ */
40
+ readonly typeSuffix?: string
41
+ }
42
+
43
+ /**
44
+ * The reusable, schema-scoped work the walker memoizes. Keyed by the *original*
45
+ * root schema object so repeated walks of the same document — the parsers,
46
+ * validators, and examples generators all running over one loaded schema —
47
+ * pay for the draft-07 upgrade, the dynamic-ref map, and each `resolveRef` /
48
+ * `extractRefs` exactly once. JSON Schema inputs are treated as immutable here;
49
+ * the `WeakMap` drops the entry once the caller releases the schema.
50
+ */
51
+ type RootCache = {
52
+ upgraded: Record<string, unknown>
53
+ dynamicRefMap: Record<string, string>
54
+ resolveRefCache: Map<string, Record<string, unknown> | undefined>
55
+ extractRefsCache: WeakMap<object, Set<string>>
56
+ }
57
+
58
+ const rootCaches = new WeakMap<object, RootCache>()
59
+
60
+ const getRootCache = (rootSchema: JSONSchema): RootCache => {
61
+ // Only object roots can key a WeakMap. A boolean root has no refs to walk and
62
+ // the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
63
+ if (typeof rootSchema !== 'object' || rootSchema === null) {
64
+ const upgraded = rootSchema as unknown as Record<string, unknown>
65
+ return { upgraded, dynamicRefMap: {}, resolveRefCache: new Map(), extractRefsCache: new WeakMap() }
66
+ }
67
+
68
+ const existing = rootCaches.get(rootSchema)
69
+ if (existing) return existing
70
+
71
+ const upgraded = upgradeDraft07Schema(rootSchema as Record<string, unknown>)
72
+ const cache: RootCache = {
73
+ upgraded,
74
+ dynamicRefMap: buildDynamicRefMap(upgraded as JSONSchema),
75
+ resolveRefCache: new Map(),
76
+ extractRefsCache: new WeakMap(),
77
+ }
78
+ rootCaches.set(rootSchema, cache)
79
+ return cache
80
+ }
81
+
82
+ /** Memoized `resolveRef` keyed by ref string within a single root document. */
83
+ const cachedResolveRef = (cache: RootCache, ref: string): Record<string, unknown> | undefined => {
84
+ if (cache.resolveRefCache.has(ref)) return cache.resolveRefCache.get(ref)
85
+ const resolved = resolveRef(ref, cache.upgraded)
86
+ cache.resolveRefCache.set(ref, resolved)
87
+ return resolved
88
+ }
89
+
90
+ /** Memoized `extractRefs` keyed by the (stable) resolved subschema identity. */
91
+ const cachedExtractRefs = (cache: RootCache, schema: JSONSchema): Set<string> => {
92
+ if (typeof schema !== 'object' || schema === null) return extractRefs(schema)
93
+ const existing = cache.extractRefsCache.get(schema)
94
+ if (existing) return existing
95
+ const refs = extractRefs(schema)
96
+ cache.extractRefsCache.set(schema, refs)
97
+ return refs
98
+ }
99
+
100
+ /**
101
+ * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
102
+ * `visit` once per distinct output file: first the root, then every reachable
103
+ * definition (breadth-first). This is the single, shared traversal the parser,
104
+ * validator, and example generators were each re-implementing.
105
+ *
106
+ * For every node the walker has already upgraded draft-07 inputs, resolved the
107
+ * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
108
+ * callers only have to turn `node.schema` into file content. Definitions
109
+ * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
110
+ * code imports goes ungenerated. A ref that fails to resolve is reported via
111
+ * `console.warn` and skipped, matching the generators' prior behavior.
112
+ *
113
+ * Resolution work is memoized per root document (see {@link RootCache}), so
114
+ * running several generators over the same loaded schema does the expensive
115
+ * walking once.
116
+ *
117
+ * @param rootSchema - The root JSON Schema to walk.
118
+ * @param rootTypeName - The name for the root type (e.g. `'Document'`).
119
+ * @param options - Naming options ({@link WalkRefGraphOptions}).
120
+ * @param visit - Called once per output file with a fully prepared {@link RefNode}.
121
+ */
122
+ export const walkRefGraph = (
123
+ rootSchema: JSONSchema,
124
+ rootTypeName: string,
125
+ options: WalkRefGraphOptions,
126
+ visit: (node: RefNode) => void,
127
+ ): void => {
128
+ const typeSuffix = options.typeSuffix ?? ''
129
+ const cache = getRootCache(rootSchema)
130
+ const { upgraded, dynamicRefMap } = cache
131
+
132
+ const processedRefs = new Set<string>()
133
+ const processedFilenames = new Set<string>()
134
+
135
+ // Root node first — its filename reserves a slot so a later ref that maps to
136
+ // the same name does not emit a duplicate file.
137
+ const rootFilename = rootTypeName.toLowerCase()
138
+ processedFilenames.add(rootFilename)
139
+ visit({
140
+ ref: undefined,
141
+ typeName: rootTypeName,
142
+ filename: rootFilename,
143
+ schema: resolveDynamicRefs(upgraded as JSONSchema, dynamicRefMap),
144
+ rootSchema: upgraded,
145
+ isRoot: true,
146
+ })
147
+
148
+ const queue: string[] = [
149
+ ...cachedExtractRefs(cache, upgraded as JSONSchema),
150
+ ...extractDynamicAnchorDefs(upgraded as JSONSchema),
151
+ ]
152
+
153
+ // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
154
+ // makes draining a large ref graph quadratic.
155
+ for (let head = 0; head < queue.length; head++) {
156
+ const ref = queue[head]
157
+ if (!ref || processedRefs.has(ref)) continue
158
+ processedRefs.add(ref)
159
+
160
+ const resolved = cachedResolveRef(cache, ref)
161
+ if (!resolved) {
162
+ console.warn(`Warning: Could not resolve ref: ${ref}`)
163
+ continue
164
+ }
165
+
166
+ const filename = refToFilename(ref)
167
+ if (!processedFilenames.has(filename)) {
168
+ processedFilenames.add(filename)
169
+ visit({
170
+ ref,
171
+ typeName: refToName(ref, typeSuffix),
172
+ filename,
173
+ schema: resolveDynamicRefs(resolved as JSONSchema, dynamicRefMap),
174
+ rootSchema: upgraded,
175
+ isRoot: false,
176
+ })
177
+ }
178
+
179
+ // Always queue nested refs from the resolved schema, even when its file was
180
+ // a duplicate: two ref strings can share a filename yet reach different
181
+ // sub-definitions (e.g. a URI key and its short-name alias).
182
+ for (const nested of cachedExtractRefs(cache, resolved as JSONSchema)) {
183
+ if (!processedRefs.has(nested)) queue.push(nested)
184
+ }
185
+ }
186
+ }