@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
package/AI.md CHANGED
@@ -27,14 +27,22 @@ if (node && isObjectSchema(node) && hasProperties(node)) {
27
27
  1. **No barrel — import per subpath.** `@amritk/helpers/resolve-ref`, NOT
28
28
  `@amritk/helpers`. The subpath is the exact kebab-case filename with no `.ts`.
29
29
  2. **`resolveRef(ref, rootSchema)`** takes the ref first, root second, handles
30
- JSON-pointer `$ref`s only, and returns `undefined` on a miss (no throw) —
31
- guard the result.
32
- 3. **Two similar guards:** `isSchemaObject` narrows to a non-boolean schema;
30
+ JSON-pointer `$ref`s, plain `$anchor` names (`#named`), and URI keys in
31
+ `$defs`, and returns `undefined` on a miss (no throw) — guard the result.
32
+ 3. **`walkRefGraph` throws, it does not degrade.** An unresolvable `$ref`, a
33
+ `$dynamicRef` with no anchor, and two definitions that reduce to one filename
34
+ or one type name all fail generation. Each of those used to warn and carry on,
35
+ which shipped TypeScript that either did not compile or bound to the wrong
36
+ type. `$id` base-URI scoping is *resolved*, not refused — `normalizeRefScopes`
37
+ rewrites every ref to a document-root pointer first — and only the residue the
38
+ spec calls unresolvable (a fragment ref naming nothing in its own resource)
39
+ still throws, via `assertIdScopes`.
40
+ 4. **Two similar guards:** `isSchemaObject` narrows to a non-boolean schema;
33
41
  `isObjectSchema` narrows to a `type: object` schema. Don't confuse them.
34
- 4. **Some modules are copied verbatim into generated output** (`is-object`,
42
+ 5. **Some modules are copied verbatim into generated output** (`is-object`,
35
43
  `safe-accessor`, `validate-array`, `validate-record`) — intentionally
36
44
  dependency-free and minimal, not general-purpose validators.
37
45
 
38
46
  Notable subpaths: `/resolve-ref`, `/extract-refs`, `/schema-guards`,
39
47
  `/ref-to-name`, `/ref-to-filename`, `/upgrade-draft07-schema`,
40
- `/generate-type-definition`, `/is-object`. Install: `bun add @amritk/helpers`.
48
+ `/walk-ref-graph`, `/generate-type-definition`, `/is-object`. Install: `bun add @amritk/helpers`.
package/README.md CHANGED
@@ -42,9 +42,12 @@ bun add @amritk/helpers
42
42
  | Subpath | Exports | Purpose |
43
43
  |:---|:---|:---|
44
44
  | `@amritk/helpers/extract-refs` | `extractRefs` | Collect every `$ref` reachable from a schema. |
45
- | `@amritk/helpers/resolve-ref` | `resolveRef` | Resolve a JSON pointer `$ref` against a root schema. |
45
+ | `@amritk/helpers/resolve-ref` | `resolveRef` | Resolve a `$ref` — JSON Pointer, `$anchor` name, or URI — against a root schema. |
46
+ | `@amritk/helpers/build-anchor-map` | `buildAnchorMap` | Build a map of `$anchor` / `$dynamicAnchor` name → JSON Pointer. |
46
47
  | `@amritk/helpers/build-dynamic-ref-map` | `buildDynamicRefMap` | Build a map of `$dynamicAnchor` → resolved location. |
47
48
  | `@amritk/helpers/resolve-dynamic-refs` | `resolveDynamicRefs` | Replace `$dynamicRef` occurrences using the map above. |
49
+ | `@amritk/helpers/assert-id-scopes` | `assertIdScopes` | Reject a document whose `$id`-scoped fragment ref resolves to nothing in its own resource. |
50
+ | `@amritk/helpers/max-schema-depth` | `MAX_SCHEMA_DEPTH`, `assertSchemaDepth` | The nesting cap every recursive walker enforces. |
48
51
  | `@amritk/helpers/upgrade-draft07-schema` | `upgradeDraft07Schema`, `isDraft07Schema` | Upgrade a Draft-07 schema to 2020-12. |
49
52
  | `@amritk/helpers/ref-to-filename` | `refToFilename`, `toKebabCase` | Convert a `$ref` to a stable filename. |
50
53
  | `@amritk/helpers/ref-to-name` | `refToName` | Convert a `$ref` to a TypeScript identifier (PascalCase). |
@@ -0,0 +1,20 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ /**
3
+ * Fails a document whose `$id` scoping this package cannot honour.
4
+ *
5
+ * In 2020-12 an `$id` on a subschema starts a new resource, and a `#/...` ref
6
+ * inside it resolves against *that* resource rather than the document root.
7
+ * {@link normalizeRefScopes} implements that, so nearly every such document now
8
+ * generates correctly. What is left is the residue: a fragment ref inside an
9
+ * embedded resource that names nothing in the resource it belongs to. The spec
10
+ * calls that unresolvable, but the resolvers here navigate from the document
11
+ * root, so it would quietly pick up the *outer* definition of the same name — a
12
+ * different type, no warning, exit 0. A wrong type that compiles is the worst
13
+ * outcome available, so it is rejected up front instead.
14
+ *
15
+ * The check stays deliberately narrow: it only fires when the enclosing resource
16
+ * declares ref targets of its own (`$defs`, `definitions`, or an `$anchor`),
17
+ * which is exactly the ambiguous case. A decorative `$id` with nothing local to
18
+ * point at has only one possible reading, so it stays silent and keeps working.
19
+ */
20
+ export declare const assertIdScopes: (rootSchema: JSONSchema) => void;
@@ -0,0 +1,45 @@
1
+ import { buildResourceRegistry, DATA_KEYWORDS, escapePointerSegment } from "./build-resource-registry.js";
2
+ import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { resolveRef } from "./resolve-ref.js";
4
+ import { resolveScopedRef } from "./resolve-scoped-ref.js";
5
+ const declaresLocalTargets = (record) => typeof record["$defs"] === "object" || typeof record["definitions"] === "object" || typeof record["$anchor"] === "string";
6
+ const assertIdScopes = (rootSchema) => {
7
+ const registry = buildResourceRegistry(rootSchema);
8
+ if (registry === null)
9
+ return;
10
+ const walk = (node, pointer, enclosing, resource, depth) => {
11
+ assertSchemaDepth(depth, "assertIdScopes");
12
+ if (node === null || typeof node !== "object")
13
+ return;
14
+ if (Array.isArray(node)) {
15
+ for (let index = 0; index < node.length; index++) {
16
+ walk(node[index], `${pointer}/${index}`, enclosing, resource, depth + 1);
17
+ }
18
+ return;
19
+ }
20
+ const record = node;
21
+ const declared = registry.baseAt.get(pointer);
22
+ const base = declared ?? enclosing;
23
+ const scope = declared !== void 0 && pointer !== "" ? record : resource;
24
+ for (const key of ["$ref", "$dynamicRef"]) {
25
+ const ref = record[key];
26
+ if (typeof ref !== "string" || !ref.startsWith("#") || ref === "#")
27
+ continue;
28
+ if (scope === null || !declaresLocalTargets(scope))
29
+ continue;
30
+ const target = resolveScopedRef(registry, ref, base);
31
+ if (target !== void 0 && resolveRef(`#${target.pointer}`, rootSchema))
32
+ continue;
33
+ throw new Error(`The subschema with $id "${scope["$id"]}" declares its own definitions and contains the ref "${ref}", which names nothing inside it. $id base-URI scoping makes that ref unresolvable, but resolving it from the document root would silently select a different definition. Point the ref at a definition the embedded resource declares, hoist the resource into the root $defs, or drop the inner $id.`);
34
+ }
35
+ for (const key of Object.keys(record)) {
36
+ if (DATA_KEYWORDS.has(key))
37
+ continue;
38
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, scope, depth + 1);
39
+ }
40
+ };
41
+ walk(rootSchema, "", registry.rootBase, null, 0);
42
+ };
43
+ export {
44
+ assertIdScopes
45
+ };
@@ -0,0 +1,26 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ /**
3
+ * Maps every `$anchor` name declared in a document to the JSON Pointer of the
4
+ * subschema that declares it, so a plain-name ref (`$ref: "#named"`) can be
5
+ * resolved.
6
+ *
7
+ * `$anchor` is a core 2020-12 keyword, but the resolver only ever understood
8
+ * JSON Pointer fragments — so `#named` navigated the pointer `named`, found
9
+ * nothing, and the ref silently produced an unloadable `'./#named.ts'` import.
10
+ * `$dynamicAnchor` names are collected too: 2020-12 says a `$dynamicAnchor`
11
+ * also behaves as a plain `$anchor`, so a static `$ref` is allowed to target
12
+ * one (only `$dynamicRef` gets the late-binding treatment, which
13
+ * {@link buildDynamicRefMap} handles separately).
14
+ *
15
+ * The whole document is scanned — an anchor may sit anywhere — and the first
16
+ * occurrence in document order wins, matching how `buildDynamicRefMap` binds a
17
+ * name to a single document-global target. The root itself can declare an
18
+ * anchor; it maps to the pointer `#`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * // $defs.address carries `$anchor: "addr"`
23
+ * buildAnchorMap(rootSchema) // { addr: '#/$defs/address' }
24
+ * ```
25
+ */
26
+ export declare const buildAnchorMap: (rootSchema: JSONSchema) => Record<string, string>;
@@ -0,0 +1,35 @@
1
+ import { assertSchemaDepth } from "./max-schema-depth.js";
2
+ import { isSchemaObject } from "./schema-guards.js";
3
+ const escapeSegment = (segment) => segment.indexOf("~") !== -1 || segment.indexOf("/") !== -1 ? segment.replace(/~/g, "~0").replace(/\//g, "~1") : segment;
4
+ const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
5
+ const buildAnchorMap = (rootSchema) => {
6
+ const map = /* @__PURE__ */ Object.create(null);
7
+ if (!isSchemaObject(rootSchema))
8
+ return map;
9
+ const walk = (node, pointer, depth) => {
10
+ assertSchemaDepth(depth, "buildAnchorMap");
11
+ if (node === null || typeof node !== "object")
12
+ return;
13
+ if (Array.isArray(node)) {
14
+ for (let i = 0; i < node.length; i++)
15
+ walk(node[i], `${pointer}/${i}`, depth + 1);
16
+ return;
17
+ }
18
+ const record = node;
19
+ for (const keyword of ["$anchor", "$dynamicAnchor"]) {
20
+ const anchor = record[keyword];
21
+ if (typeof anchor === "string" && !Object.hasOwn(map, anchor))
22
+ map[anchor] = `#${pointer}`;
23
+ }
24
+ for (const key of Object.keys(record)) {
25
+ if (NON_SCHEMA_KEYWORDS.has(key))
26
+ continue;
27
+ walk(record[key], `${pointer}/${escapeSegment(key)}`, depth + 1);
28
+ }
29
+ };
30
+ walk(rootSchema, "", 0);
31
+ return map;
32
+ };
33
+ export {
34
+ buildAnchorMap
35
+ };
@@ -12,6 +12,14 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
12
12
  * the first occurrence in document order wins, matching how the resolvers bind
13
13
  * a name to a single document-global target.
14
14
  *
15
+ * The document root is included, mapping to the pointer `#`. That is the
16
+ * canonical recursive-tree idiom (`{ $id: '.../tree', $dynamicAnchor: 'node',
17
+ * items: { $dynamicRef: '#node' } }`), and leaving it out meant the ref had no
18
+ * target at all: the type generator fell back to the anchor's *name*, so
19
+ * `#node` became the type `Node` — never generated, never imported, and under
20
+ * the `DOM` lib silently bound to the DOM `Node` interface instead of failing.
21
+ * `walkRefGraph` turns the `#` pointer into the root's own generated file.
22
+ *
15
23
  * @example
16
24
  * // Given a schema with $defs.schema having $dynamicAnchor: "meta"
17
25
  * buildDynamicRefMap(rootSchema)
@@ -1,3 +1,4 @@
1
+ import { assertSchemaDepth } from "./max-schema-depth.js";
1
2
  import { isSchemaObject } from "./schema-guards.js";
2
3
  const escapeSegment = (segment) => segment.indexOf("~") !== -1 || segment.indexOf("/") !== -1 ? segment.replace(/~/g, "~0").replace(/\//g, "~1") : segment;
3
4
  const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
@@ -5,26 +6,27 @@ const buildDynamicRefMap = (rootSchema) => {
5
6
  const map = {};
6
7
  if (!isSchemaObject(rootSchema))
7
8
  return map;
8
- const walk = (node, pointer) => {
9
+ const walk = (node, pointer, depth) => {
10
+ assertSchemaDepth(depth, "buildDynamicRefMap");
9
11
  if (node === null || typeof node !== "object")
10
12
  return;
11
13
  if (Array.isArray(node)) {
12
14
  for (let i = 0; i < node.length; i++)
13
- walk(node[i], `${pointer}/${i}`);
15
+ walk(node[i], `${pointer}/${i}`, depth + 1);
14
16
  return;
15
17
  }
16
18
  const record = node;
17
19
  const anchor = record["$dynamicAnchor"];
18
- if (pointer !== "" && typeof anchor === "string" && !(`#${anchor}` in map)) {
20
+ if (typeof anchor === "string" && !(`#${anchor}` in map)) {
19
21
  map[`#${anchor}`] = `#${pointer}`;
20
22
  }
21
23
  for (const key of Object.keys(record)) {
22
24
  if (NON_SCHEMA_KEYWORDS.has(key))
23
25
  continue;
24
- walk(record[key], `${pointer}/${escapeSegment(key)}`);
26
+ walk(record[key], `${pointer}/${escapeSegment(key)}`, depth + 1);
25
27
  }
26
28
  };
27
- walk(rootSchema, "");
29
+ walk(rootSchema, "", 0);
28
30
  return map;
29
31
  };
30
32
  export {
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The `$id` base-URI machinery JSON Schema 2020-12 defines, read off a document
3
+ * once and expressed entirely in JSON Pointers.
4
+ *
5
+ * A subschema carrying `$id` is an *embedded resource*: its `$id` resolved
6
+ * against the base in scope becomes a new base URI, every `$ref` written inside
7
+ * it resolves against *that* base, and its `$anchor`s belong to it rather than
8
+ * to the document. Without this a `$ref` written as a relative URI (`"list"`),
9
+ * an absolute one (`"http://example.com/b/d.json"`), a URN, or an absolute path
10
+ * (`"/absref/foobar.json"`) has nothing to resolve against — even when the
11
+ * resource it names sits a few lines further down the same document. Worse, a
12
+ * plain `#/$defs/t` written *inside* a resource used to be read against the
13
+ * document root, so it quietly selected a different definition than its author
14
+ * wrote.
15
+ *
16
+ * Everything is keyed by JSON Pointer rather than by object identity on purpose:
17
+ * pointers are the currency the rest of this package already deals in
18
+ * (`resolveRef`, `refToName`, `refToFilename`, the generated import graph), so a
19
+ * consumer can turn a registry hit straight into a `$ref` string, a filename, or
20
+ * a type name without holding on to the document.
21
+ *
22
+ * The walk stays entirely in memory. A URI that matches no embedded resource is
23
+ * simply not found — fetching the document behind it is `@amritk/resolve-refs`'
24
+ * job.
25
+ */
26
+ /** A document's embedded resources and anchors, all located by JSON Pointer. */
27
+ export type ResourceRegistry = {
28
+ /** The document root's base URI — its own `$id` resolved, or {@link SYNTHETIC_BASE}. */
29
+ readonly rootBase: string;
30
+ /** Absolute URI (fragment stripped) → the pointer of the subschema that declared it. */
31
+ readonly resources: ReadonlyMap<string, string>;
32
+ /** `${base}#${name}` → pointer, for `$anchor` and `$dynamicAnchor` alike. */
33
+ readonly anchors: ReadonlyMap<string, string>;
34
+ /** `${base}#${name}` → pointer, for `$dynamicAnchor` only — what `$dynamicRef` binds to. */
35
+ readonly dynamicAnchors: ReadonlyMap<string, string>;
36
+ /**
37
+ * Pointer of every `$id`-bearing node → the absolute base URI it establishes.
38
+ * A second walk over the same document can rebuild the base in scope from this
39
+ * without re-parsing a single URL. Only `$id`-bearing nodes are recorded, so it
40
+ * stays tiny.
41
+ */
42
+ readonly baseAt: ReadonlyMap<string, string>;
43
+ };
44
+ /**
45
+ * The base a document with no `$id` of its own resolves against. It uses the
46
+ * reserved `.invalid` TLD so it can never collide with a real `$id`, and nothing
47
+ * ever fetches it — only URI strings are ever compared.
48
+ */
49
+ export declare const SYNTHETIC_BASE = "https://helpers.mjst.invalid/schema";
50
+ /**
51
+ * Keywords whose value is arbitrary *data* rather than a subschema. An `$id` or
52
+ * `$anchor` sitting inside an `enum` member is part of an instance the schema
53
+ * describes, not a declaration, so every walk over the `$id` graph stops at
54
+ * these.
55
+ */
56
+ export declare const DATA_KEYWORDS: Set<string>;
57
+ /** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
58
+ export declare const resolveUri: (ref: string, base: string) => string | undefined;
59
+ /**
60
+ * Escapes one object key for use as a JSON Pointer reference token.
61
+ *
62
+ * `~`/`/` are RFC 6901's own escapes. `%` is escaped on top of those because the
63
+ * pointer we build here is handed back as a `$ref` — a URI fragment — and
64
+ * `resolveRef` percent-decodes each token before matching it, so a definition
65
+ * literally named `a%2Fb` would otherwise be looked up as `a/b`.
66
+ */
67
+ export declare const escapePointerSegment: (segment: string) => string;
68
+ /**
69
+ * The base URI a subschema establishes through its `$id`, or the enclosing base
70
+ * when it declares none. A draft-07-style `$id: "#name"` resolves to a bare
71
+ * fragment and therefore establishes nothing, which the empty-string check
72
+ * catches.
73
+ */
74
+ export declare const baseAfterId: (node: Record<string, unknown>, enclosing: string) => string;
75
+ /**
76
+ * Walks a document once, registering every embedded resource and every anchor
77
+ * under the base URI it is scoped to. First declaration wins on a duplicate URI
78
+ * or anchor name, which is document order.
79
+ *
80
+ * Returns `null` when the document declares no `$id` anywhere — there is then
81
+ * exactly one base URI in play, so plain document-local pointer resolution
82
+ * already gives the spec's answer and every caller can skip the whole apparatus
83
+ * (and its per-node cost) on what is overwhelmingly the common document.
84
+ *
85
+ * @param root - The document to read. Anything that is not an object registers
86
+ * nothing.
87
+ */
88
+ export declare const buildResourceRegistry: (root: unknown) => ResourceRegistry | null;
@@ -0,0 +1,90 @@
1
+ import { assertSchemaDepth } from "./max-schema-depth.js";
2
+ const SYNTHETIC_BASE = "https://helpers.mjst.invalid/schema";
3
+ const DATA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
4
+ const resolveUri = (ref, base) => {
5
+ try {
6
+ return new URL(ref, base).href;
7
+ } catch {
8
+ return void 0;
9
+ }
10
+ };
11
+ const escapePointerSegment = (segment) => segment.indexOf("~") === -1 && segment.indexOf("/") === -1 && segment.indexOf("%") === -1 ? segment : segment.replace(/~/g, "~0").replace(/\//g, "~1").replace(/%/g, "%25");
12
+ const baseAfterId = (node, enclosing) => {
13
+ const id = node["$id"];
14
+ if (typeof id !== "string" || id === "")
15
+ return enclosing;
16
+ const resolved = resolveUri(id, enclosing);
17
+ if (resolved === void 0)
18
+ return enclosing;
19
+ const hash = resolved.indexOf("#");
20
+ const bare = hash === -1 ? resolved : resolved.slice(0, hash);
21
+ return bare === "" ? enclosing : bare;
22
+ };
23
+ const registries = /* @__PURE__ */ new WeakMap();
24
+ const buildResourceRegistry = (root) => {
25
+ if (root === null || typeof root !== "object")
26
+ return null;
27
+ const memoized = registries.get(root);
28
+ if (memoized !== void 0 || registries.has(root))
29
+ return memoized ?? null;
30
+ const resources = /* @__PURE__ */ new Map();
31
+ const anchors = /* @__PURE__ */ new Map();
32
+ const dynamicAnchors = /* @__PURE__ */ new Map();
33
+ const baseAt = /* @__PURE__ */ new Map();
34
+ let sawId = false;
35
+ const walk = (node, pointer, enclosing, depth) => {
36
+ assertSchemaDepth(depth, "buildResourceRegistry");
37
+ if (node === null || typeof node !== "object")
38
+ return;
39
+ if (Array.isArray(node)) {
40
+ for (let index = 0; index < node.length; index++)
41
+ walk(node[index], `${pointer}/${index}`, enclosing, depth + 1);
42
+ return;
43
+ }
44
+ const record = node;
45
+ const base = baseAfterId(record, enclosing);
46
+ if (base !== enclosing) {
47
+ sawId = true;
48
+ baseAt.set(pointer, base);
49
+ if (!resources.has(base))
50
+ resources.set(base, pointer);
51
+ }
52
+ const anchor = record["$anchor"];
53
+ if (typeof anchor === "string" && !anchors.has(`${base}#${anchor}`))
54
+ anchors.set(`${base}#${anchor}`, pointer);
55
+ const dynamicAnchor = record["$dynamicAnchor"];
56
+ if (typeof dynamicAnchor === "string") {
57
+ const key = `${base}#${dynamicAnchor}`;
58
+ if (!dynamicAnchors.has(key))
59
+ dynamicAnchors.set(key, pointer);
60
+ if (!anchors.has(key))
61
+ anchors.set(key, pointer);
62
+ }
63
+ for (const key of Object.keys(record)) {
64
+ if (DATA_KEYWORDS.has(key))
65
+ continue;
66
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, depth + 1);
67
+ }
68
+ };
69
+ walk(root, "", SYNTHETIC_BASE, 0);
70
+ if (!sawId) {
71
+ registries.set(root, null);
72
+ return null;
73
+ }
74
+ const rootBase = baseAt.get("") ?? SYNTHETIC_BASE;
75
+ if (!resources.has(rootBase))
76
+ resources.set(rootBase, "");
77
+ if (!resources.has(SYNTHETIC_BASE))
78
+ resources.set(SYNTHETIC_BASE, "");
79
+ const registry = { rootBase, resources, anchors, dynamicAnchors, baseAt };
80
+ registries.set(root, registry);
81
+ return registry;
82
+ };
83
+ export {
84
+ DATA_KEYWORDS,
85
+ SYNTHETIC_BASE,
86
+ baseAfterId,
87
+ buildResourceRegistry,
88
+ escapePointerSegment,
89
+ resolveUri
90
+ };
@@ -1 +1,28 @@
1
1
  export declare const escapeRegexPattern: (pattern: string) => string;
2
+ /**
3
+ * The flags a generated regex for `pattern` should carry: `'u'` where the
4
+ * pattern is a legal Unicode-mode regex, `''` where it is not.
5
+ *
6
+ * A 2020-12 `pattern` is meant to be read as Unicode — Ajv compiles with `u` by
7
+ * default, and so does `@amritk/runtime-validators` (`compilePattern` in
8
+ * `interpreter/interpret.ts`) — and without the flag `\p{L}` is misread as a
9
+ * literal `p` and `^.$` rejects a single astral character. The flag is not
10
+ * unconditional because `u` also outlaws escapes that are legal without it
11
+ * (`\-`, a bare `\p`), and a pattern using one would turn into a syntax error in
12
+ * the emitted regex literal. Compiling here is the same decision the interpreter
13
+ * makes at runtime, taken once at generation time instead.
14
+ */
15
+ export declare const regexFlagsFor: (pattern: string) => string;
16
+ /**
17
+ * A complete regex literal for a JSON Schema `pattern` — the escaped body
18
+ * between slashes, with the flags {@link regexFlagsFor} picks.
19
+ *
20
+ * Emit sites take this rather than interpolating `escapeRegexPattern` into their
21
+ * own `/…/`, so the flag decision is made in one place and cannot be forgotten
22
+ * at one of the dozen places a pattern reaches generated code.
23
+ *
24
+ * @example
25
+ * regexLiteral('\\p{L}+') // → '/\\p{L}+/u'
26
+ * @throws if `pattern` is not a valid regular expression.
27
+ */
28
+ export declare const regexLiteral: (pattern: string) => string;
@@ -9,6 +9,7 @@ const lineTerminatorEscapes = {
9
9
  // PARAGRAPH SEPARATOR
10
10
  };
11
11
  const escapeCache = /* @__PURE__ */ new Map();
12
+ const flagCache = /* @__PURE__ */ new Map();
12
13
  const ESCAPE_CACHE_LIMIT = 1e3;
13
14
  const escapeRegexPattern = (pattern) => {
14
15
  const cached = escapeCache.get(pattern);
@@ -37,6 +38,25 @@ const escapeRegexPattern = (pattern) => {
37
38
  escapeCache.set(pattern, escaped);
38
39
  return escaped;
39
40
  };
41
+ const regexFlagsFor = (pattern) => {
42
+ const cached = flagCache.get(pattern);
43
+ if (cached !== void 0)
44
+ return cached;
45
+ let flags = "";
46
+ try {
47
+ new RegExp(pattern, "u");
48
+ flags = "u";
49
+ } catch {
50
+ flags = "";
51
+ }
52
+ if (flagCache.size >= ESCAPE_CACHE_LIMIT)
53
+ flagCache.delete(flagCache.keys().next().value);
54
+ flagCache.set(pattern, flags);
55
+ return flags;
56
+ };
57
+ const regexLiteral = (pattern) => `/${escapeRegexPattern(pattern)}/${regexFlagsFor(pattern)}`;
40
58
  export {
41
- escapeRegexPattern
59
+ escapeRegexPattern,
60
+ regexFlagsFor,
61
+ regexLiteral
42
62
  };
@@ -1,3 +1,4 @@
1
+ import { assertSchemaDepth } from "./max-schema-depth.js";
1
2
  const isResolvableRef = (ref) => {
2
3
  if (ref === "#")
3
4
  return false;
@@ -9,13 +10,14 @@ const isResolvableRef = (ref) => {
9
10
  };
10
11
  const extractRefs = (schema) => {
11
12
  const refs = /* @__PURE__ */ new Set();
12
- const traverse = (obj) => {
13
+ const traverse = (obj, depth) => {
14
+ assertSchemaDepth(depth, "extractRefs");
13
15
  if (typeof obj !== "object" || obj === null) {
14
16
  return;
15
17
  }
16
18
  if (Array.isArray(obj)) {
17
19
  for (const item of obj) {
18
- traverse(item);
20
+ traverse(item, depth + 1);
19
21
  }
20
22
  return;
21
23
  }
@@ -24,10 +26,10 @@ const extractRefs = (schema) => {
24
26
  refs.add(record["$ref"]);
25
27
  }
26
28
  for (const key in record) {
27
- traverse(record[key]);
29
+ traverse(record[key], depth + 1);
28
30
  }
29
31
  };
30
- traverse(schema);
32
+ traverse(schema, 0);
31
33
  return refs;
32
34
  };
33
35
  export {
@@ -1,13 +1,20 @@
1
+ const NON_ASCII_IDENTIFIER_PART = /[\p{ID_Continue}$]/u;
2
+ const isIdentifierPart = (content, index) => {
3
+ const code = content.charCodeAt(index);
4
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57)
5
+ return true;
6
+ if (code === 95 || code === 36)
7
+ return true;
8
+ if (code < 128)
9
+ return false;
10
+ return NON_ASCII_IDENTIFIER_PART.test(String.fromCodePoint(content.codePointAt(index)));
11
+ };
1
12
  const exportNameAt = (content, at, prefix) => {
2
13
  if (!content.startsWith(prefix, at))
3
14
  return null;
4
15
  let end = at + prefix.length;
5
- while (end < content.length) {
6
- const code = content.charCodeAt(end);
7
- const isWord = code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
8
- if (!isWord)
9
- break;
10
- end++;
16
+ while (end < content.length && isIdentifierPart(content, end)) {
17
+ end += content.codePointAt(end) > 65535 ? 2 : 1;
11
18
  }
12
19
  return end > at + prefix.length ? content.slice(at + prefix.length, end) : null;
13
20
  };
@@ -336,10 +336,7 @@ const getUnbrandedType = (schema, options = {}) => {
336
336
  return refTypeName(schema.$ref, options);
337
337
  }
338
338
  if (schema.$dynamicRef) {
339
- if (schema.$dynamicRef === "#meta") {
340
- return `Schema${options.typeSuffix ?? ""}`;
341
- }
342
- return refToName(schema.$dynamicRef, options.typeSuffix);
339
+ return "unknown";
343
340
  }
344
341
  if (schema.const !== void 0) {
345
342
  return JSON.stringify(schema.const);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Folds documents the caller has already loaded into the document being
3
+ * generated, so a `$ref` that names another document resolves like any other.
4
+ *
5
+ * The generators are a single-document pipeline by construction: `$id` is applied
6
+ * once by {@link normalizeRefScopes}, every ref becomes a pointer from the
7
+ * document root, and the ref-graph walk, the filename and type-name derivation
8
+ * and the emitted import graph all work in that one currency. A ref to a
9
+ * *separate* resource had nowhere to land in that model — not because the URI
10
+ * could not be resolved, but because the bytes were somewhere else — so
11
+ * generation stopped.
12
+ *
13
+ * Grafting closes that gap without teaching any of the machinery a second
14
+ * addressing mode. Each registered document is embedded in the root's `$defs` as
15
+ * what it already is — a schema resource carrying its own base URI — and from
16
+ * that point on it *is* part of the document: the registry walk registers its
17
+ * `$id`, its anchors and its own embedded resources, `normalizeRefScopes`
18
+ * rewrites refs into it to plain pointers, and the walker gives it files and type
19
+ * names by the ordinary rules. Cross-document `$ref`, `$anchor` and
20
+ * `$dynamicAnchor` all start working at once, and nothing downstream had to
21
+ * change.
22
+ *
23
+ * This is the build-time counterpart of `@amritk/runtime-validators`'
24
+ * `ValidateOptions.schemas`, and it keeps the same promise: no I/O. The documents
25
+ * are handed over, never fetched — loading them is the caller's job (or
26
+ * `@amritk/resolve-refs`'). A URI nobody registered is still refused, loudly, at
27
+ * generation time.
28
+ *
29
+ * Registered documents that nothing references cost nothing in the output: the
30
+ * ref-graph walk only emits files for definitions it can actually reach, so a
31
+ * caller can register a whole directory and ship only what the schema uses.
32
+ */
33
+ /**
34
+ * A grafted document: the root to carry on with, and the `$defs` names the graft
35
+ * introduced.
36
+ *
37
+ * The names matter downstream because a registered document is *not* quite an
38
+ * authored one: a caller is meant to be able to over-register, so the ones
39
+ * nothing references have to be identifiable in order to be dropped again (see
40
+ * {@link pruneExternalSchemas}).
41
+ */
42
+ export type GraftedSchema = {
43
+ readonly document: Record<string, unknown>;
44
+ readonly names: ReadonlySet<string>;
45
+ };
46
+ /**
47
+ * Embeds each registered document into `root`'s `$defs`, returning a new root.
48
+ *
49
+ * The document keeps its own `$id` when it has one, and is given the retrieval
50
+ * URI as its `$id` when it does not — which is what makes a relative `$ref`
51
+ * *inside* a registered document resolve against the URI it was fetched from
52
+ * rather than against the root's base. When a document's `$id` disagrees with the
53
+ * URI it was registered under, both have to keep naming it, so a tiny alias
54
+ * resource (`{ $id: <retrieval URI>, $ref: <its own $id> }`) is embedded
55
+ * alongside it and refs to the retrieval URI land there.
56
+ *
57
+ * Every registered document is embedded, whether or not the schema mentions it —
58
+ * which of them are needed is not knowable until the base URIs have been applied
59
+ * and the refs are pointers. {@link pruneExternalSchemas} drops the rest once
60
+ * that is done.
61
+ *
62
+ * `root` is returned by identity when there is nothing to graft, so the
63
+ * overwhelmingly common no-registry call allocates nothing.
64
+ *
65
+ * @param root - The document being generated.
66
+ * @param schemas - Already-loaded documents, keyed by the absolute URI a `$ref`
67
+ * names them by.
68
+ * @returns The root document in which every registered URI is resolvable, and
69
+ * the `$defs` names the graft introduced.
70
+ * @throws When two registered URIs, or a registered URI and an existing `$defs`
71
+ * entry, want the same definition name — the name is what every emitted import
72
+ * is keyed on, so picking a winner would silently mistype one of them.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * graftExternalSchemas(
77
+ * { $ref: 'https://example.com/user.json' },
78
+ * { 'https://example.com/user.json': { type: 'object' } },
79
+ * ).document
80
+ * // → { $ref: 'https://example.com/user.json', $defs: { user: { $id: '…', type: 'object' } } }
81
+ * ```
82
+ */
83
+ export declare const graftExternalSchemas: (root: Record<string, unknown>, schemas: Readonly<Record<string, unknown>>) => GraftedSchema;