@amritk/helpers 0.15.4 → 0.16.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.
@@ -11,3 +11,15 @@
11
11
  * a schema was expected.
12
12
  */
13
13
  export declare const readKey: <T>(source: Readonly<Record<string, T>>, key: string) => T | undefined;
14
+ /**
15
+ * True when `source` declares `key` itself — the presence half of the same
16
+ * question {@link readKey} answers by value.
17
+ *
18
+ * A caller that only needs to know whether a keyword is *there* would otherwise
19
+ * write `'items' in schema`, and `in` walks the prototype chain: with
20
+ * `Object.prototype.items` set, every node in a document declares a keyword none
21
+ * of them wrote, and what the generators emit from that is a different validator
22
+ * — an inherited `items: false` capping every array at zero, an inherited `if`
23
+ * sending a walk into unbounded recursion.
24
+ */
25
+ export declare const declaresKey: (source: object, key: string) => boolean;
package/dist/read-key.js CHANGED
@@ -1,4 +1,6 @@
1
1
  const readKey = (source, key) => Object.hasOwn(source, key) ? source[key] : void 0;
2
+ const declaresKey = (source, key) => Object.hasOwn(source, key);
2
3
  export {
4
+ declaresKey,
3
5
  readKey
4
6
  };
@@ -1,3 +1,44 @@
1
+ /**
2
+ * Converts a filename-like string to a PascalCase TypeScript identifier,
3
+ * appending an optional suffix.
4
+ *
5
+ * Word boundaries are *any* run of characters that cannot appear in a JS
6
+ * identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
7
+ * becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
8
+ * A name that does not start with an identifier character (a leading digit, say)
9
+ * is prefixed with `_`.
10
+ *
11
+ * The `_` fallback for an empty result is a backstop only: `refToFilename`
12
+ * already normalizes a name that would reduce to nothing into a `ref-<hash>`
13
+ * form, so distinct refs stay distinct before they ever reach this function.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * kebabToPascal('server-variable') // 'ServerVariable'
18
+ * kebabToPascal('channel') // 'Channel'
19
+ * kebabToPascal('channel', 'Object') // 'ChannelObject'
20
+ * kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
21
+ * kebabToPascal('123abc') // '_123abc'
22
+ * kebabToPascal('中文') // '中文'
23
+ * ```
24
+ */
25
+ /**
26
+ * Splits `text` on characters TypeScript will not accept inside an identifier
27
+ * and joins the words in PascalCase, keeping the rest of each word so acronyms
28
+ * survive. Returns `''` when nothing usable is left, leaving the emptiness
29
+ * policy to the caller.
30
+ *
31
+ * Shared with {@link deriveRootTypeName} rather than reimplemented there: that
32
+ * copy split on `[^a-zA-Z0-9]+`, which is the ASCII-only class this module's
33
+ * `WORD_SEPARATOR` doc describes fixing. A document titled `中文` came back
34
+ * empty and was named `Document`, `Café Menu` came back as `CafMenu` with the
35
+ * `é` deleted from the middle of a word, and `Ünïcödé Doc` as `NCDDoc` — while
36
+ * a `$ref` to a definition of the same name was spelled correctly, so the root
37
+ * type and the refs into it disagreed.
38
+ */
39
+ export declare const toPascalWords: (text: string) => string;
40
+ /** True when `name` may begin a TypeScript identifier. */
41
+ export declare const isIdentifierStart: (name: string) => boolean;
1
42
  /**
2
43
  * Converts a JSON Schema $ref to a type name.
3
44
  * Derives the filename via `refToFilename` then converts to PascalCase,
@@ -1,22 +1,28 @@
1
1
  import { refToFilename } from "./ref-to-filename.js";
2
2
  const WORD_SEPARATOR = /[^\p{ID_Continue}]+|_+/u;
3
3
  const IDENTIFIER_START = /^[\p{ID_Start}_$]/u;
4
- const kebabToPascal = (kebab, suffix) => {
5
- const words = kebab.split(WORD_SEPARATOR);
4
+ const toPascalWords = (text) => {
6
5
  let pascalCase = "";
7
- for (const word of words) {
6
+ for (const word of text.split(WORD_SEPARATOR)) {
8
7
  if (word === void 0 || word === "")
9
8
  continue;
10
9
  const first = [...word][0];
11
10
  pascalCase += first.toUpperCase() + word.slice(first.length);
12
11
  }
12
+ return pascalCase;
13
+ };
14
+ const isIdentifierStart = (name) => IDENTIFIER_START.test(name);
15
+ const kebabToPascal = (kebab, suffix) => {
16
+ let pascalCase = toPascalWords(kebab);
13
17
  if (pascalCase === "")
14
18
  pascalCase = "_";
15
- else if (!IDENTIFIER_START.test(pascalCase))
19
+ else if (!isIdentifierStart(pascalCase))
16
20
  pascalCase = `_${pascalCase}`;
17
21
  return pascalCase + suffix;
18
22
  };
19
23
  const refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
20
24
  export {
21
- refToName
25
+ isIdentifierStart,
26
+ refToName,
27
+ toPascalWords
22
28
  };
@@ -1,11 +1,11 @@
1
- import { DATA_KEYWORDS, entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
1
+ import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
2
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
3
  import { readKey } from "./read-key.js";
4
4
  const resolveDynamicRefs = (schema, dynamicRefMap) => {
5
5
  if (typeof schema !== "object" || schema === null) {
6
6
  return schema;
7
7
  }
8
- if (!containsDynamicRef(schema, 0)) {
8
+ if (!containsDynamicRef(schema, 0, false)) {
9
9
  return schema;
10
10
  }
11
11
  const clone = JSON.parse(JSON.stringify(schema));
@@ -38,23 +38,23 @@ const resolveDynamicRefs = (schema, dynamicRefMap) => {
38
38
  walk(clone, 0);
39
39
  return clone;
40
40
  };
41
- const containsDynamicRef = (value, depth) => {
41
+ const containsDynamicRef = (value, depth, inSchemaMap) => {
42
42
  assertSchemaDepth(depth, "resolveDynamicRefs");
43
43
  if (typeof value !== "object" || value === null)
44
44
  return false;
45
45
  if (Array.isArray(value)) {
46
46
  for (const item of value)
47
- if (containsDynamicRef(item, depth + 1))
47
+ if (containsDynamicRef(item, depth + 1, inSchemaMap))
48
48
  return true;
49
49
  return false;
50
50
  }
51
51
  const record = value;
52
- if (typeof readKey(record, "$dynamicRef") === "string")
52
+ if (!inSchemaMap && typeof readKey(record, "$dynamicRef") === "string")
53
53
  return true;
54
54
  for (const key of Object.keys(record)) {
55
- if (DATA_KEYWORDS.has(key))
55
+ if (isDataPosition(key, inSchemaMap))
56
56
  continue;
57
- if (containsDynamicRef(record[key], depth + 1))
57
+ if (containsDynamicRef(record[key], depth + 1, entersSchemaMap(key, inSchemaMap)))
58
58
  return true;
59
59
  }
60
60
  return false;
@@ -14,7 +14,7 @@
14
14
  * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
15
15
  * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
16
16
  * safeAccessor("input", "constructor")
17
- * // '(input != null && Object.hasOwn(input, "constructor") ? input["constructor"] : undefined)'
17
+ * // '((input != null && Object.hasOwn(input, "constructor") ? input["constructor"] : undefined) as any)'
18
18
  */
19
19
  export declare const safeAccessor: (variable: string, key: string) => string;
20
20
  /**
@@ -4,7 +4,7 @@ const safeAccessor = (variable, key) => {
4
4
  if (PROTOTYPE_MEMBERS.has(key)) {
5
5
  const base = variable.endsWith("?") ? variable.slice(0, -1) : variable;
6
6
  const literal2 = JSON.stringify(key);
7
- return `(${base} != null && Object.hasOwn(${base}, ${literal2}) ? ${base}[${literal2}] : undefined)`;
7
+ return `((${base} != null && Object.hasOwn(${base}, ${literal2}) ? ${base}[${literal2}] : undefined) as any)`;
8
8
  }
9
9
  if (JS_IDENTIFIER.test(key)) {
10
10
  return `${variable}.${key}`;
@@ -3,7 +3,7 @@ const minLengthPassExpr = (valueExpr, min) => {
3
3
  if (min <= 0)
4
4
  return "true";
5
5
  if (min === 1)
6
- return `${valueExpr}.length >= 1`;
6
+ return `(${valueExpr}.length >= 1)`;
7
7
  return `(${valueExpr}.length >= ${min} && (${valueExpr}.length >= ${min * 2} || ${codePoints(valueExpr)} >= ${min}))`;
8
8
  };
9
9
  const maxLengthPassExpr = (valueExpr, max) => `(${valueExpr}.length <= ${max} || ${codePoints(valueExpr)} <= ${max})`;
@@ -11,7 +11,7 @@ const minLengthFailExpr = (valueExpr, min) => {
11
11
  if (min <= 0)
12
12
  return "false";
13
13
  if (min === 1)
14
- return `${valueExpr}.length < 1`;
14
+ return `(${valueExpr}.length < 1)`;
15
15
  return `(${valueExpr}.length < ${min} || (${valueExpr}.length < ${min * 2} && ${codePoints(valueExpr)} < ${min}))`;
16
16
  };
17
17
  const maxLengthFailExpr = (valueExpr, max) => `(${valueExpr}.length > ${max} && ${codePoints(valueExpr)} > ${max})`;
@@ -18,12 +18,15 @@ export type UnknownKeyCheck = {
18
18
  * Builds the boolean expression that is true when `keyVar` is NOT one of the
19
19
  * known keys — an inline chain of `!==` comparisons, a `Set.has` miss, or the
20
20
  * constant `true` when there are no known keys (every key is undeclared).
21
+ *
22
+ * Self-parenthesized, so it drops into a `&&` / `||` chain or under a `!`
23
+ * as one term.
21
24
  */
22
25
  readonly isUnknown: (keyVar: string) => string;
23
26
  /**
24
27
  * The complement of {@link isUnknown}: true when `keyVar` IS a known key — an
25
28
  * inline chain of `===` comparisons, a `Set.has` hit, or the constant `false`
26
- * when there are no known keys.
29
+ * when there are no known keys. Self-parenthesized, like {@link isUnknown}.
27
30
  */
28
31
  readonly isKnown: (keyVar: string) => string;
29
32
  };
@@ -37,10 +40,18 @@ export type UnknownKeyCheck = {
37
40
  * TypeBox compile to. Above `inlineLimit` the chain grows long enough that the
38
41
  * `Set`'s O(1) lookup wins, so a `Set` named `setName` is hoisted instead.
39
42
  *
43
+ * Both expressions are parenthesized whichever form they take. Only the inline
44
+ * chains need it, but they are the ones that need it *invisibly*: `isKnown`
45
+ * returns `a || b` inline and an atomic `set.has(k)` above the limit, so a
46
+ * caller writing `x && check.isKnown(k)` got `(x && a) || b` for a 16-key object
47
+ * and correct code for a 17-key one — a precedence bug that appears and
48
+ * disappears with a performance threshold. Parenthesizing both makes the two
49
+ * forms interchangeable, which is what a caller already assumes they are.
50
+ *
40
51
  * @example
41
52
  * const check = unknownKeyCheck(['id', 'name'], '_knownKeys0')
42
53
  * check.declarations // []
43
- * check.isUnknown('_k') // '_k !== "id" && _k !== "name"'
44
- * check.isKnown('_k') // '_k === "id" || _k === "name"'
54
+ * check.isUnknown('_k') // '(_k !== "id" && _k !== "name")'
55
+ * check.isKnown('_k') // '(_k === "id" || _k === "name")'
45
56
  */
46
57
  export declare const unknownKeyCheck: (knownKeys: readonly string[], setName: string, inlineLimit?: number) => UnknownKeyCheck;
@@ -6,8 +6,8 @@ const unknownKeyCheck = (knownKeys, setName, inlineLimit = INLINE_KEY_LIMIT) =>
6
6
  if (knownKeys.length <= inlineLimit) {
7
7
  return {
8
8
  declarations: [],
9
- isUnknown: (keyVar) => knownKeys.map((key) => `${keyVar} !== ${JSON.stringify(key)}`).join(" && "),
10
- isKnown: (keyVar) => knownKeys.map((key) => `${keyVar} === ${JSON.stringify(key)}`).join(" || ")
9
+ isUnknown: (keyVar) => `(${knownKeys.map((key) => `${keyVar} !== ${JSON.stringify(key)}`).join(" && ")})`,
10
+ isKnown: (keyVar) => `(${knownKeys.map((key) => `${keyVar} === ${JSON.stringify(key)}`).join(" || ")})`
11
11
  };
12
12
  }
13
13
  return {
@@ -1,8 +1,12 @@
1
1
  import { assignKey } from "./assign-key.js";
2
2
  import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
3
3
  import { assertSchemaDepth } from "./max-schema-depth.js";
4
+ import { readKey } from "./read-key.js";
4
5
  import { refToFilename, toKebabCase } from "./ref-to-filename.js";
5
- const isDraft07Schema = (schema) => typeof schema["$schema"] === "string" && schema["$schema"].includes("draft-07");
6
+ const isDraft07Schema = (schema) => {
7
+ const declared = readKey(schema, "$schema");
8
+ return typeof declared === "string" && declared.includes("draft-07");
9
+ };
6
10
  const rewriteRefs = (obj, refMap, selfRef, depth = 0, inSchemaMap = false) => {
7
11
  assertSchemaDepth(depth, "upgradeDraft07Schema");
8
12
  if (typeof obj !== "object" || obj === null)
@@ -36,7 +40,7 @@ const hoistNestedDefs = (defs) => {
36
40
  continue;
37
41
  }
38
42
  const parentObj = parentSchema;
39
- const nestedDefs = parentObj["$defs"];
43
+ const nestedDefs = readKey(parentObj, "$defs");
40
44
  if (!nestedDefs || typeof nestedDefs !== "object") {
41
45
  assignKey(hoisted, parentName, parentSchema);
42
46
  continue;
@@ -4,6 +4,7 @@ import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
4
4
  import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
5
5
  import { extractRefs } from "./extract-refs.js";
6
6
  import { graftExternalSchemas } from "./graft-external-schemas.js";
7
+ import { assertSchemaDepth } from "./max-schema-depth.js";
7
8
  import { normalizeRefScopes } from "./normalize-ref-scopes.js";
8
9
  import { pruneExternalSchemas } from "./prune-external-schemas.js";
9
10
  import { readKey } from "./read-key.js";
@@ -44,11 +45,12 @@ const getAliasRootRef = (schema) => {
44
45
  return SHAPE_KEYWORDS.some((key) => Object.hasOwn(record, key)) ? null : ref;
45
46
  };
46
47
  const DEFINITION_MAP_KEYS = ["$defs", "definitions"];
47
- const expandBooleanDefinitions = (value, inSchemaMap = false) => {
48
+ const expandBooleanDefinitions = (value, depth, inSchemaMap = false) => {
49
+ assertSchemaDepth(depth, "walkRefGraph");
48
50
  if (typeof value !== "object" || value === null)
49
51
  return value;
50
52
  if (Array.isArray(value)) {
51
- const mapped = value.map((item) => expandBooleanDefinitions(item, inSchemaMap));
53
+ const mapped = value.map((item) => expandBooleanDefinitions(item, depth + 1, inSchemaMap));
52
54
  return mapped.some((item, index) => item !== value[index]) ? mapped : value;
53
55
  }
54
56
  const record = value;
@@ -59,21 +61,22 @@ const expandBooleanDefinitions = (value, inSchemaMap = false) => {
59
61
  for (const key of Object.keys(record)) {
60
62
  if (isDataPosition(key, inSchemaMap))
61
63
  continue;
62
- const next = !inSchemaMap && DEFINITION_MAP_KEYS.includes(key) ? expandDefinitionMap(record[key]) : expandBooleanDefinitions(record[key], entersSchemaMap(key, inSchemaMap));
64
+ const next = !inSchemaMap && DEFINITION_MAP_KEYS.includes(key) ? expandDefinitionMap(record[key], depth + 1) : expandBooleanDefinitions(record[key], depth + 1, entersSchemaMap(key, inSchemaMap));
63
65
  if (next !== record[key])
64
66
  changed = true;
65
67
  assignKey(result, key, next);
66
68
  }
67
69
  return changed ? result : value;
68
70
  };
69
- const expandDefinitionMap = (definitions) => {
71
+ const expandDefinitionMap = (definitions, depth) => {
72
+ assertSchemaDepth(depth, "walkRefGraph");
70
73
  if (typeof definitions !== "object" || definitions === null || Array.isArray(definitions))
71
74
  return definitions;
72
75
  const record = definitions;
73
76
  let changed = false;
74
77
  const result = {};
75
78
  for (const [name, definition] of Object.entries(record)) {
76
- const next = definition === true ? {} : definition === false ? { not: {} } : expandBooleanDefinitions(definition);
79
+ const next = definition === true ? {} : definition === false ? { not: {} } : expandBooleanDefinitions(definition, depth + 1);
77
80
  if (next !== definition)
78
81
  changed = true;
79
82
  assignKey(result, name, next);
@@ -97,7 +100,7 @@ const getRootCache = (rootSchema, schemas) => {
97
100
  return cached;
98
101
  const grafted = registry === void 0 ? void 0 : graftExternalSchemas(rootSchema, registry);
99
102
  const combined = grafted?.document ?? rootSchema;
100
- const expanded = expandBooleanDefinitions(upgradeDraft07Schema(combined));
103
+ const expanded = expandBooleanDefinitions(upgradeDraft07Schema(combined), 0);
101
104
  assertIdScopes(expanded);
102
105
  const normalized = normalizeRefScopes(expanded);
103
106
  const upgraded = grafted === void 0 ? normalized : pruneExternalSchemas(normalized, grafted.names);
@@ -117,11 +120,12 @@ const getRootCache = (rootSchema, schemas) => {
117
120
  }
118
121
  return cache;
119
122
  };
120
- const referencesRoot = (value, inSchemaMap = false) => {
123
+ const referencesRoot = (value, depth, inSchemaMap = false) => {
124
+ assertSchemaDepth(depth, "walkRefGraph");
121
125
  if (typeof value !== "object" || value === null)
122
126
  return false;
123
127
  if (Array.isArray(value))
124
- return value.some((item) => referencesRoot(item, inSchemaMap));
128
+ return value.some((item) => referencesRoot(item, depth + 1, inSchemaMap));
125
129
  const record = value;
126
130
  if (!inSchemaMap) {
127
131
  const ref = readKey(record, "$ref");
@@ -131,42 +135,45 @@ const referencesRoot = (value, inSchemaMap = false) => {
131
135
  for (const key of Object.keys(record)) {
132
136
  if (isDataPosition(key, inSchemaMap))
133
137
  continue;
134
- if (referencesRoot(record[key], entersSchemaMap(key, inSchemaMap)))
138
+ if (referencesRoot(record[key], depth + 1, entersSchemaMap(key, inSchemaMap)))
135
139
  return true;
136
140
  }
137
141
  return false;
138
142
  };
139
- const copyValue = (value) => {
143
+ const copyValue = (value, depth) => {
144
+ assertSchemaDepth(depth, "walkRefGraph");
140
145
  if (typeof value !== "object" || value === null)
141
146
  return value;
142
147
  if (Array.isArray(value))
143
- return value.map(copyValue);
148
+ return value.map((item) => copyValue(item, depth + 1));
144
149
  const out = {};
145
- for (const [key, sub] of Object.entries(value))
146
- assignKey(out, key, copyValue(sub));
150
+ for (const [key, sub] of Object.entries(value)) {
151
+ assignKey(out, key, copyValue(sub, depth + 1));
152
+ }
147
153
  return out;
148
154
  };
149
- const rewriteRootRefs = (value, rootSelfRef, inSchemaMap = false) => {
155
+ const rewriteRootRefs = (value, rootSelfRef, depth, inSchemaMap = false) => {
156
+ assertSchemaDepth(depth, "walkRefGraph");
150
157
  if (typeof value !== "object" || value === null)
151
158
  return value;
152
159
  if (Array.isArray(value))
153
- return value.map((item) => rewriteRootRefs(item, rootSelfRef, inSchemaMap));
160
+ return value.map((item) => rewriteRootRefs(item, rootSelfRef, depth + 1, inSchemaMap));
154
161
  const out = {};
155
162
  const record = value;
156
163
  for (const key of Object.keys(record)) {
157
164
  if (isDataPosition(key, inSchemaMap)) {
158
- assignKey(out, key, copyValue(record[key]));
165
+ assignKey(out, key, copyValue(record[key], depth + 1));
159
166
  continue;
160
167
  }
161
- assignKey(out, key, !inSchemaMap && key === "$ref" && (record[key] === ROOT_POINTER || record[key] === "#/") ? rootSelfRef : rewriteRootRefs(record[key], rootSelfRef, entersSchemaMap(key, inSchemaMap)));
168
+ assignKey(out, key, !inSchemaMap && key === "$ref" && (record[key] === ROOT_POINTER || record[key] === "#/") ? rootSelfRef : rewriteRootRefs(record[key], rootSelfRef, depth + 1, entersSchemaMap(key, inSchemaMap)));
162
169
  }
163
170
  return out;
164
171
  };
165
- const rootAnchoredCache = (base, rootFilename, rootSelfRef) => {
172
+ const rootAnchoredCache = (base, rootFilename, rootSelfRef, selfReferenced) => {
166
173
  const cached = base.rootAnchored.get(rootFilename);
167
174
  if (cached)
168
175
  return cached;
169
- const rewritten = referencesRoot(base.upgraded) ? rewriteRootRefs(base.upgraded, rootSelfRef) : base.upgraded;
176
+ const rewritten = selfReferenced ? rewriteRootRefs(base.upgraded, rootSelfRef, 0) : base.upgraded;
170
177
  const { $defs, ...rootBody } = rewritten;
171
178
  const defs = typeof $defs === "object" && $defs !== null ? $defs : {};
172
179
  if (Object.hasOwn(defs, rootFilename)) {
@@ -185,20 +192,26 @@ const rootAnchoredCache = (base, rootFilename, rootSelfRef) => {
185
192
  base.rootAnchored.set(rootFilename, derived);
186
193
  return derived;
187
194
  };
188
- const dynamicPointerRefs = (value, into = /* @__PURE__ */ new Set()) => {
195
+ const dynamicPointerRefs = (value, depth, into = /* @__PURE__ */ new Set(), inSchemaMap = false) => {
196
+ assertSchemaDepth(depth, "walkRefGraph");
189
197
  if (typeof value !== "object" || value === null)
190
198
  return into;
191
199
  if (Array.isArray(value)) {
192
200
  for (const item of value)
193
- dynamicPointerRefs(item, into);
201
+ dynamicPointerRefs(item, depth + 1, into, inSchemaMap);
194
202
  return into;
195
203
  }
196
204
  const record = value;
197
- const ref = readKey(record, "$dynamicRef");
198
- if (typeof ref === "string" && ref.startsWith("#/"))
199
- into.add(ref);
200
- for (const key of Object.keys(record))
201
- dynamicPointerRefs(record[key], into);
205
+ if (!inSchemaMap) {
206
+ const ref = readKey(record, "$dynamicRef");
207
+ if (typeof ref === "string" && ref.startsWith("#/"))
208
+ into.add(ref);
209
+ }
210
+ for (const key of Object.keys(record)) {
211
+ if (isDataPosition(key, inSchemaMap))
212
+ continue;
213
+ dynamicPointerRefs(record[key], depth + 1, into, entersSchemaMap(key, inSchemaMap));
214
+ }
202
215
  return into;
203
216
  };
204
217
  const cachedResolveRef = (cache, ref) => {
@@ -224,12 +237,12 @@ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
224
237
  const rootFilename = rootTypeName.toLowerCase();
225
238
  const rootSelfRef = `#/$defs/${rootFilename}`;
226
239
  const rootIsAnchored = Object.values(baseCache.dynamicRefMap).includes(ROOT_POINTER);
227
- const rootIsSelfReferenced = referencesRoot(baseCache.upgraded);
240
+ const rootIsSelfReferenced = referencesRoot(baseCache.upgraded, 0);
228
241
  const needsRootAlias = rootIsAnchored || rootIsSelfReferenced;
229
242
  if (needsRootAlias && refToName(rootSelfRef, typeSuffix) !== rootTypeName) {
230
243
  throw new Error(`The root schema is referenced by ${rootIsAnchored ? "a $dynamicAnchor" : 'a $ref to "#"'}, which is generated as the root's own file \u2014 but the root type name "${rootTypeName}" does not survive the round trip through ref naming (refs to it would be named "${refToName(rootSelfRef, typeSuffix)}"). Use a single-word root type name with no type suffix, or move the recursion onto a $defs entry.`);
231
244
  }
232
- const cache = needsRootAlias ? rootAnchoredCache(baseCache, rootFilename, rootSelfRef) : baseCache;
245
+ const cache = needsRootAlias ? rootAnchoredCache(baseCache, rootFilename, rootSelfRef, rootIsSelfReferenced) : baseCache;
233
246
  const { upgraded, dynamicRefMap } = cache;
234
247
  const processedRefs = /* @__PURE__ */ new Set();
235
248
  const filenameOwners = /* @__PURE__ */ new Map();
@@ -265,7 +278,7 @@ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
265
278
  const queue = [
266
279
  ...cachedExtractRefs(cache, upgraded),
267
280
  ...Object.values(dynamicRefMap),
268
- ...[...dynamicPointerRefs(upgraded)].filter((ref) => cachedResolveRef(cache, ref) !== void 0)
281
+ ...[...dynamicPointerRefs(upgraded, 0)].filter((ref) => cachedResolveRef(cache, ref) !== void 0)
269
282
  ];
270
283
  for (let head = 0; head < queue.length; head++) {
271
284
  const ref = queue[head];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.15.4",
3
+ "version": "0.16.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,