@amritk/helpers 0.6.2 → 0.7.1

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 (67) hide show
  1. package/dist/build-dynamic-ref-map.d.ts +1 -0
  2. package/dist/build-dynamic-ref-map.d.ts.map +1 -0
  3. package/dist/build-dynamic-ref-map.js +31 -107
  4. package/dist/derive-root-type-name.d.ts +1 -0
  5. package/dist/derive-root-type-name.d.ts.map +1 -0
  6. package/dist/derive-root-type-name.js +37 -17
  7. package/dist/extract-dynamic-anchor-defs.d.ts +20 -0
  8. package/dist/extract-dynamic-anchor-defs.d.ts.map +1 -0
  9. package/dist/extract-dynamic-anchor-defs.js +30 -0
  10. package/dist/extract-refs.d.ts +1 -0
  11. package/dist/extract-refs.d.ts.map +1 -0
  12. package/dist/extract-refs.js +64 -33
  13. package/dist/generate-index-barrel.d.ts +29 -0
  14. package/dist/generate-index-barrel.d.ts.map +1 -0
  15. package/dist/generate-index-barrel.js +43 -0
  16. package/dist/generate-type-definition.d.ts +1 -0
  17. package/dist/generate-type-definition.d.ts.map +1 -0
  18. package/dist/generate-type-definition.js +449 -567
  19. package/dist/has-ref.d.ts +1 -0
  20. package/dist/has-ref.d.ts.map +1 -0
  21. package/dist/has-ref.js +7 -6
  22. package/dist/is-object.d.ts +1 -0
  23. package/dist/is-object.d.ts.map +1 -0
  24. package/dist/is-object.js +14 -5
  25. package/dist/mjst-extension.d.ts +1 -0
  26. package/dist/mjst-extension.d.ts.map +1 -0
  27. package/dist/mjst-extension.js +50 -122
  28. package/dist/parse-documentation.d.ts +1 -0
  29. package/dist/parse-documentation.d.ts.map +1 -0
  30. package/dist/parse-documentation.js +124 -87
  31. package/dist/ref-to-filename.d.ts +1 -0
  32. package/dist/ref-to-filename.d.ts.map +1 -0
  33. package/dist/ref-to-filename.js +106 -42
  34. package/dist/ref-to-name.d.ts +1 -0
  35. package/dist/ref-to-name.d.ts.map +1 -0
  36. package/dist/ref-to-name.js +39 -53
  37. package/dist/resolve-dynamic-refs.d.ts +1 -0
  38. package/dist/resolve-dynamic-refs.d.ts.map +1 -0
  39. package/dist/resolve-dynamic-refs.js +36 -28
  40. package/dist/resolve-ref.d.ts +1 -0
  41. package/dist/resolve-ref.d.ts.map +1 -0
  42. package/dist/resolve-ref.js +74 -39
  43. package/dist/safe-accessor.d.ts +1 -0
  44. package/dist/safe-accessor.d.ts.map +1 -0
  45. package/dist/safe-accessor.js +42 -19
  46. package/dist/schema-guards.d.ts +2 -1
  47. package/dist/schema-guards.d.ts.map +1 -0
  48. package/dist/schema-guards.js +119 -120
  49. package/dist/upgrade-draft07-schema.d.ts +1 -0
  50. package/dist/upgrade-draft07-schema.d.ts.map +1 -0
  51. package/dist/upgrade-draft07-schema.js +152 -130
  52. package/dist/validate-array.d.ts +1 -0
  53. package/dist/validate-array.d.ts.map +1 -0
  54. package/dist/validate-array.js +12 -14
  55. package/dist/validate-record.d.ts +1 -0
  56. package/dist/validate-record.d.ts.map +1 -0
  57. package/dist/validate-record.js +15 -17
  58. package/dist/walk-ref-graph.d.ts +54 -0
  59. package/dist/walk-ref-graph.d.ts.map +1 -0
  60. package/dist/walk-ref-graph.js +123 -0
  61. package/package.json +9 -88
  62. package/src/extract-dynamic-anchor-defs.test.ts +29 -0
  63. package/src/extract-dynamic-anchor-defs.ts +33 -0
  64. package/src/generate-index-barrel.test.ts +41 -0
  65. package/src/generate-index-barrel.ts +62 -0
  66. package/src/walk-ref-graph.test.ts +118 -0
  67. package/src/walk-ref-graph.ts +184 -0
@@ -0,0 +1,184 @@
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
+ while (queue.length > 0) {
154
+ const ref = queue.shift()
155
+ if (!ref || processedRefs.has(ref)) continue
156
+ processedRefs.add(ref)
157
+
158
+ const resolved = cachedResolveRef(cache, ref)
159
+ if (!resolved) {
160
+ console.warn(`Warning: Could not resolve ref: ${ref}`)
161
+ continue
162
+ }
163
+
164
+ const filename = refToFilename(ref)
165
+ if (!processedFilenames.has(filename)) {
166
+ processedFilenames.add(filename)
167
+ visit({
168
+ ref,
169
+ typeName: refToName(ref, typeSuffix),
170
+ filename,
171
+ schema: resolveDynamicRefs(resolved as JSONSchema, dynamicRefMap),
172
+ rootSchema: upgraded,
173
+ isRoot: false,
174
+ })
175
+ }
176
+
177
+ // Always queue nested refs from the resolved schema, even when its file was
178
+ // a duplicate: two ref strings can share a filename yet reach different
179
+ // sub-definitions (e.g. a URI key and its short-name alias).
180
+ for (const nested of cachedExtractRefs(cache, resolved as JSONSchema)) {
181
+ if (!processedRefs.has(nested)) queue.push(nested)
182
+ }
183
+ }
184
+ }