@amritk/helpers 0.14.0 → 0.15.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 (65) 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/generate-index-barrel.js +13 -6
  15. package/dist/generate-type-definition.js +1 -4
  16. package/dist/graft-external-schemas.d.ts +83 -0
  17. package/dist/graft-external-schemas.js +70 -0
  18. package/dist/max-schema-depth.d.ts +22 -0
  19. package/dist/max-schema-depth.js +10 -0
  20. package/dist/mjst-extension.d.ts +4 -2
  21. package/dist/mjst-extension.js +11 -2
  22. package/dist/multiple-of-check.d.ts +31 -0
  23. package/dist/multiple-of-check.js +6 -10
  24. package/dist/normalize-ref-scopes.d.ts +29 -0
  25. package/dist/normalize-ref-scopes.js +53 -0
  26. package/dist/prune-external-schemas.d.ts +16 -0
  27. package/dist/prune-external-schemas.js +80 -0
  28. package/dist/ref-to-filename.d.ts +1 -0
  29. package/dist/ref-to-filename.js +19 -3
  30. package/dist/ref-to-name.js +7 -4
  31. package/dist/resolve-dynamic-refs.d.ts +10 -0
  32. package/dist/resolve-dynamic-refs.js +18 -16
  33. package/dist/resolve-ref.d.ts +4 -2
  34. package/dist/resolve-ref.js +32 -6
  35. package/dist/resolve-scoped-ref.d.ts +35 -0
  36. package/dist/resolve-scoped-ref.js +35 -0
  37. package/dist/safe-accessor.d.ts +38 -1
  38. package/dist/safe-accessor.js +15 -0
  39. package/dist/string-length-check.d.ts +8 -0
  40. package/dist/string-length-check.js +23 -0
  41. package/dist/upgrade-draft07-schema.js +9 -6
  42. package/dist/walk-ref-graph.d.ts +38 -3
  43. package/dist/walk-ref-graph.js +170 -23
  44. package/package.json +13 -3
  45. package/src/build-dynamic-ref-map.ts +0 -61
  46. package/src/derive-root-type-name.ts +0 -54
  47. package/src/escape-regex-pattern.ts +0 -87
  48. package/src/extract-dynamic-anchor-defs.ts +0 -25
  49. package/src/extract-refs.ts +0 -73
  50. package/src/fold-nullable.ts +0 -60
  51. package/src/generate-index-barrel.ts +0 -118
  52. package/src/generate-type-definition.ts +0 -784
  53. package/src/mjst-extension.ts +0 -81
  54. package/src/multiple-of-check.ts +0 -32
  55. package/src/parse-documentation.ts +0 -177
  56. package/src/quote-js-string.ts +0 -20
  57. package/src/ref-to-filename.ts +0 -116
  58. package/src/ref-to-name.ts +0 -54
  59. package/src/resolve-dynamic-refs.ts +0 -74
  60. package/src/resolve-ref.ts +0 -82
  61. package/src/safe-accessor.ts +0 -53
  62. package/src/schema-guards.ts +0 -234
  63. package/src/unknown-key-check.ts +0 -68
  64. package/src/upgrade-draft07-schema.ts +0 -179
  65. package/src/walk-ref-graph.ts +0 -257
@@ -1,257 +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
- /** Which ref claimed each filename, so a later collision can name both sides. */
171
- const filenameOwners = new Map<string, string>()
172
-
173
- // Root node first — its filename reserves a slot so a later ref that maps to
174
- // the same name does not emit a duplicate file.
175
- const rootFilename = rootTypeName.toLowerCase()
176
- processedFilenames.add(rootFilename)
177
- filenameOwners.set(rootFilename, `the root type ${rootTypeName}`)
178
-
179
- // An alias root (a document that is just `$ref: '#/$defs/x'`) whose derived
180
- // filename equals its target's would reserve the filename for a wrapper that
181
- // re-exports the target — and the target, mapping to the same file, would
182
- // then never be generated, leaving a file that imports itself. Generate the
183
- // *target's* schema under the root's name instead, carrying the ref so
184
- // generators can exclude the self-import.
185
- let rootNodeSchema = upgraded as JSONSchema
186
- let rootNodeRef: string | undefined
187
- const aliasRef = getAliasRootRef(upgraded as JSONSchema)
188
- if (aliasRef && refToFilename(aliasRef) === rootFilename) {
189
- const resolved = cachedResolveRef(cache, aliasRef)
190
- if (resolved) {
191
- rootNodeSchema = resolved as JSONSchema
192
- rootNodeRef = aliasRef
193
- }
194
- }
195
-
196
- visit({
197
- ref: rootNodeRef,
198
- typeName: rootTypeName,
199
- filename: rootFilename,
200
- schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
201
- rootSchema: upgraded,
202
- isRoot: true,
203
- })
204
-
205
- // Seed dynamic-anchor targets from the memoized map instead of calling
206
- // extractDynamicAnchorDefs (which would re-walk the whole document — the map
207
- // already holds exactly those refs as its values).
208
- const queue: string[] = [...cachedExtractRefs(cache, upgraded as JSONSchema), ...Object.values(dynamicRefMap)]
209
-
210
- // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
211
- // makes draining a large ref graph quadratic.
212
- for (let head = 0; head < queue.length; head++) {
213
- const ref = queue[head]
214
- if (!ref || processedRefs.has(ref)) continue
215
- processedRefs.add(ref)
216
-
217
- const resolved = cachedResolveRef(cache, ref)
218
- if (!resolved) {
219
- console.warn(`Warning: Could not resolve ref: ${ref}`)
220
- continue
221
- }
222
-
223
- const filename = refToFilename(ref)
224
- if (processedFilenames.has(filename)) {
225
- // Two definitions that reduce to one filename (`Pet`/`pet`, `foo-bar`/`foo.bar`)
226
- // silently collapse: the first one generated wins and the second is dropped,
227
- // so every reference to it gets the wrong type with no other signal. Warn
228
- // loudly — renaming the definition is the only fix, and it has to be the
229
- // caller's, since the name is what the emitted imports are keyed on.
230
- const owner = filenameOwners.get(filename)
231
- if (owner !== undefined && owner !== ref) {
232
- console.warn(
233
- `Warning: ${ref} and ${owner} both map to "${filename}.ts" — only ${owner} was generated, so ` +
234
- `every reference to the other resolves to the wrong type. Rename one so each gets its own file.`,
235
- )
236
- }
237
- } else {
238
- processedFilenames.add(filename)
239
- filenameOwners.set(filename, ref)
240
- visit({
241
- ref,
242
- typeName: refToName(ref, typeSuffix),
243
- filename,
244
- schema: resolveDynamicRefs(resolved as JSONSchema, dynamicRefMap),
245
- rootSchema: upgraded,
246
- isRoot: false,
247
- })
248
- }
249
-
250
- // Always queue nested refs from the resolved schema, even when its file was
251
- // a duplicate: two ref strings can share a filename yet reach different
252
- // sub-definitions (e.g. a URI key and its short-name alias).
253
- for (const nested of cachedExtractRefs(cache, resolved as JSONSchema)) {
254
- if (!processedRefs.has(nested)) queue.push(nested)
255
- }
256
- }
257
- }