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