@amritk/helpers 0.10.1 → 0.10.3

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 (38) 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 +44 -48
  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.d.ts +6 -1
  14. package/dist/walk-ref-graph.js +54 -4
  15. package/package.json +4 -2
  16. package/src/build-dynamic-ref-map.ts +42 -0
  17. package/src/derive-root-type-name.ts +42 -0
  18. package/src/escape-regex-pattern.ts +59 -0
  19. package/src/extract-dynamic-anchor-defs.ts +33 -0
  20. package/src/extract-refs.ts +73 -0
  21. package/src/generate-index-barrel.ts +63 -0
  22. package/src/generate-type-definition.ts +599 -0
  23. package/src/has-ref.ts +10 -0
  24. package/src/is-object.ts +15 -0
  25. package/src/mjst-extension.ts +81 -0
  26. package/src/multiple-of-check.ts +32 -0
  27. package/src/parse-documentation.ts +177 -0
  28. package/src/ref-to-filename.ts +116 -0
  29. package/src/ref-to-name.ts +54 -0
  30. package/src/resolve-dynamic-refs.ts +74 -0
  31. package/src/resolve-ref.ts +82 -0
  32. package/src/safe-accessor.ts +53 -0
  33. package/src/schema-guards.ts +195 -0
  34. package/src/unknown-key-check.ts +68 -0
  35. package/src/upgrade-draft07-schema.ts +179 -0
  36. package/src/validate-array.ts +15 -0
  37. package/src/validate-record.ts +28 -0
  38. package/src/walk-ref-graph.ts +241 -0
@@ -0,0 +1,241 @@
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
+ /**
20
+ * The `$ref` string this node was reached through, or `undefined` for the
21
+ * root schema. Exception: an alias root (a bare `$ref` document) whose
22
+ * derived filename collides with its target's carries the target's ref, so
23
+ * generators can exclude self-imports from the merged file.
24
+ */
25
+ ref: string | undefined
26
+ /** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
27
+ typeName: string
28
+ /** kebab-case filename without extension — the lowercased root type name, or `refToFilename(ref)`. */
29
+ filename: string
30
+ /** The subschema to generate, with any `$dynamicRef` already rewritten to `$ref`. */
31
+ schema: JSONSchema
32
+ /** The upgraded root document, for callers that resolve imports against it. */
33
+ rootSchema: Record<string, unknown>
34
+ /** True for the root schema node, which is always visited first. */
35
+ isRoot: boolean
36
+ }
37
+
38
+ /** Options controlling how `$ref`-derived names are produced. */
39
+ export type WalkRefGraphOptions = {
40
+ /**
41
+ * Suffix appended to every `$ref`-derived type name (e.g. `'Object'` →
42
+ * `ContactObject`). The root type name is used verbatim and is not affected.
43
+ * Defaults to `''`.
44
+ */
45
+ readonly typeSuffix?: string
46
+ }
47
+
48
+ /**
49
+ * The reusable, schema-scoped work the walker memoizes. Keyed by the *original*
50
+ * root schema object so repeated walks of the same document — the parsers,
51
+ * validators, and examples generators all running over one loaded schema —
52
+ * pay for the draft-07 upgrade, the dynamic-ref map, and each `resolveRef` /
53
+ * `extractRefs` exactly once. JSON Schema inputs are treated as immutable here;
54
+ * the `WeakMap` drops the entry once the caller releases the schema.
55
+ */
56
+ type RootCache = {
57
+ upgraded: Record<string, unknown>
58
+ dynamicRefMap: Record<string, string>
59
+ resolveRefCache: Map<string, Record<string, unknown> | undefined>
60
+ extractRefsCache: WeakMap<object, Set<string>>
61
+ }
62
+
63
+ const rootCaches = new WeakMap<object, RootCache>()
64
+
65
+ /**
66
+ * Keywords that give a schema a shape of its own. A root carrying any of these
67
+ * next to its `$ref` is a real composition, not a pure alias, and keeps the
68
+ * default root handling.
69
+ */
70
+ const SHAPE_KEYWORDS = [
71
+ 'properties',
72
+ 'type',
73
+ 'oneOf',
74
+ 'anyOf',
75
+ 'allOf',
76
+ 'patternProperties',
77
+ 'additionalProperties',
78
+ 'enum',
79
+ 'const',
80
+ 'items',
81
+ 'prefixItems',
82
+ 'required',
83
+ 'if',
84
+ 'then',
85
+ 'else',
86
+ 'not',
87
+ ] as const
88
+
89
+ /** The `$ref` of a pure-alias root document (only `$ref` + metadata keys), or null. */
90
+ const getAliasRootRef = (schema: JSONSchema): string | null => {
91
+ if (typeof schema !== 'object' || schema === null) return null
92
+ const record = schema as Record<string, unknown>
93
+ if (typeof record['$ref'] !== 'string') return null
94
+ return SHAPE_KEYWORDS.some((key) => key in record) ? null : record['$ref']
95
+ }
96
+
97
+ const getRootCache = (rootSchema: JSONSchema): RootCache => {
98
+ // Only object roots can key a WeakMap. A boolean root has no refs to walk and
99
+ // the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
100
+ if (typeof rootSchema !== 'object' || rootSchema === null) {
101
+ const upgraded = rootSchema as unknown as Record<string, unknown>
102
+ return { upgraded, dynamicRefMap: {}, resolveRefCache: new Map(), extractRefsCache: new WeakMap() }
103
+ }
104
+
105
+ const existing = rootCaches.get(rootSchema)
106
+ if (existing) return existing
107
+
108
+ const upgraded = upgradeDraft07Schema(rootSchema as Record<string, unknown>)
109
+ const cache: RootCache = {
110
+ upgraded,
111
+ dynamicRefMap: buildDynamicRefMap(upgraded as JSONSchema),
112
+ resolveRefCache: new Map(),
113
+ extractRefsCache: new WeakMap(),
114
+ }
115
+ rootCaches.set(rootSchema, cache)
116
+ return cache
117
+ }
118
+
119
+ /** Memoized `resolveRef` keyed by ref string within a single root document. */
120
+ const cachedResolveRef = (cache: RootCache, ref: string): Record<string, unknown> | undefined => {
121
+ if (cache.resolveRefCache.has(ref)) return cache.resolveRefCache.get(ref)
122
+ const resolved = resolveRef(ref, cache.upgraded)
123
+ cache.resolveRefCache.set(ref, resolved)
124
+ return resolved
125
+ }
126
+
127
+ /** Memoized `extractRefs` keyed by the (stable) resolved subschema identity. */
128
+ const cachedExtractRefs = (cache: RootCache, schema: JSONSchema): Set<string> => {
129
+ if (typeof schema !== 'object' || schema === null) return extractRefs(schema)
130
+ const existing = cache.extractRefsCache.get(schema)
131
+ if (existing) return existing
132
+ const refs = extractRefs(schema)
133
+ cache.extractRefsCache.set(schema, refs)
134
+ return refs
135
+ }
136
+
137
+ /**
138
+ * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
139
+ * `visit` once per distinct output file: first the root, then every reachable
140
+ * definition (breadth-first). This is the single, shared traversal the parser,
141
+ * validator, and example generators were each re-implementing.
142
+ *
143
+ * For every node the walker has already upgraded draft-07 inputs, resolved the
144
+ * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
145
+ * callers only have to turn `node.schema` into file content. Definitions
146
+ * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
147
+ * code imports goes ungenerated. A ref that fails to resolve is reported via
148
+ * `console.warn` and skipped, matching the generators' prior behavior.
149
+ *
150
+ * Resolution work is memoized per root document (see {@link RootCache}), so
151
+ * running several generators over the same loaded schema does the expensive
152
+ * walking once.
153
+ *
154
+ * @param rootSchema - The root JSON Schema to walk.
155
+ * @param rootTypeName - The name for the root type (e.g. `'Document'`).
156
+ * @param options - Naming options ({@link WalkRefGraphOptions}).
157
+ * @param visit - Called once per output file with a fully prepared {@link RefNode}.
158
+ */
159
+ export const walkRefGraph = (
160
+ rootSchema: JSONSchema,
161
+ rootTypeName: string,
162
+ options: WalkRefGraphOptions,
163
+ visit: (node: RefNode) => void,
164
+ ): void => {
165
+ const typeSuffix = options.typeSuffix ?? ''
166
+ const cache = getRootCache(rootSchema)
167
+ const { upgraded, dynamicRefMap } = cache
168
+
169
+ const processedRefs = new Set<string>()
170
+ const processedFilenames = new Set<string>()
171
+
172
+ // Root node first — its filename reserves a slot so a later ref that maps to
173
+ // the same name does not emit a duplicate file.
174
+ const rootFilename = rootTypeName.toLowerCase()
175
+ processedFilenames.add(rootFilename)
176
+
177
+ // An alias root (a document that is just `$ref: '#/$defs/x'`) whose derived
178
+ // filename equals its target's would reserve the filename for a wrapper that
179
+ // re-exports the target — and the target, mapping to the same file, would
180
+ // then never be generated, leaving a file that imports itself. Generate the
181
+ // *target's* schema under the root's name instead, carrying the ref so
182
+ // generators can exclude the self-import.
183
+ let rootNodeSchema = upgraded as JSONSchema
184
+ let rootNodeRef: string | undefined
185
+ const aliasRef = getAliasRootRef(upgraded as JSONSchema)
186
+ if (aliasRef && refToFilename(aliasRef) === rootFilename) {
187
+ const resolved = cachedResolveRef(cache, aliasRef)
188
+ if (resolved) {
189
+ rootNodeSchema = resolved as JSONSchema
190
+ rootNodeRef = aliasRef
191
+ }
192
+ }
193
+
194
+ visit({
195
+ ref: rootNodeRef,
196
+ typeName: rootTypeName,
197
+ filename: rootFilename,
198
+ schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
199
+ rootSchema: upgraded,
200
+ isRoot: true,
201
+ })
202
+
203
+ const queue: string[] = [
204
+ ...cachedExtractRefs(cache, upgraded as JSONSchema),
205
+ ...extractDynamicAnchorDefs(upgraded as JSONSchema),
206
+ ]
207
+
208
+ // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
209
+ // makes draining a large ref graph quadratic.
210
+ for (let head = 0; head < queue.length; head++) {
211
+ const ref = queue[head]
212
+ if (!ref || processedRefs.has(ref)) continue
213
+ processedRefs.add(ref)
214
+
215
+ const resolved = cachedResolveRef(cache, ref)
216
+ if (!resolved) {
217
+ console.warn(`Warning: Could not resolve ref: ${ref}`)
218
+ continue
219
+ }
220
+
221
+ const filename = refToFilename(ref)
222
+ if (!processedFilenames.has(filename)) {
223
+ processedFilenames.add(filename)
224
+ visit({
225
+ ref,
226
+ typeName: refToName(ref, typeSuffix),
227
+ filename,
228
+ schema: resolveDynamicRefs(resolved as JSONSchema, dynamicRefMap),
229
+ rootSchema: upgraded,
230
+ isRoot: false,
231
+ })
232
+ }
233
+
234
+ // Always queue nested refs from the resolved schema, even when its file was
235
+ // a duplicate: two ref strings can share a filename yet reach different
236
+ // sub-definitions (e.g. a URI key and its short-name alias).
237
+ for (const nested of cachedExtractRefs(cache, resolved as JSONSchema)) {
238
+ if (!processedRefs.has(nested)) queue.push(nested)
239
+ }
240
+ }
241
+ }