@amritk/helpers 0.10.1 → 0.10.3

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 (38) hide show
  1. package/dist/escape-regex-pattern.d.ts +15 -5
  2. package/dist/escape-regex-pattern.js +48 -10
  3. package/dist/generate-index-barrel.js +3 -2
  4. package/dist/generate-type-definition.js +44 -48
  5. package/dist/multiple-of-check.d.ts +4 -0
  6. package/dist/multiple-of-check.js +30 -0
  7. package/dist/parse-documentation.js +6 -2
  8. package/dist/ref-to-name.js +17 -2
  9. package/dist/resolve-dynamic-refs.js +24 -0
  10. package/dist/safe-accessor.d.ts +3 -3
  11. package/dist/safe-accessor.js +10 -6
  12. package/dist/validate-record.js +11 -1
  13. package/dist/walk-ref-graph.d.ts +6 -1
  14. package/dist/walk-ref-graph.js +54 -4
  15. package/package.json +4 -2
  16. package/src/build-dynamic-ref-map.ts +42 -0
  17. package/src/derive-root-type-name.ts +42 -0
  18. package/src/escape-regex-pattern.ts +59 -0
  19. package/src/extract-dynamic-anchor-defs.ts +33 -0
  20. package/src/extract-refs.ts +73 -0
  21. package/src/generate-index-barrel.ts +63 -0
  22. package/src/generate-type-definition.ts +599 -0
  23. package/src/has-ref.ts +10 -0
  24. package/src/is-object.ts +15 -0
  25. package/src/mjst-extension.ts +81 -0
  26. package/src/multiple-of-check.ts +32 -0
  27. package/src/parse-documentation.ts +177 -0
  28. package/src/ref-to-filename.ts +116 -0
  29. package/src/ref-to-name.ts +54 -0
  30. package/src/resolve-dynamic-refs.ts +74 -0
  31. package/src/resolve-ref.ts +82 -0
  32. package/src/safe-accessor.ts +53 -0
  33. package/src/schema-guards.ts +195 -0
  34. package/src/unknown-key-check.ts +68 -0
  35. package/src/upgrade-draft07-schema.ts +179 -0
  36. package/src/validate-array.ts +15 -0
  37. package/src/validate-record.ts +28 -0
  38. package/src/walk-ref-graph.ts +241 -0
@@ -1,16 +1,26 @@
1
1
  /**
2
2
  * Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
3
- * a generated regex literal (`/…/`).
3
+ * a generated regex literal (`/…/`), and validates that the pattern is a legal
4
+ * regex at generation time.
4
5
  *
5
6
  * A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
6
7
  * regex literal — not a string literal — so backslashes are regex syntax and
7
8
  * must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
8
- * digit" to "a literal backslash followed by d"). The only character that would
9
- * corrupt the surrounding literal is an *unescaped* `/`, which would close it
10
- * early. So we escape bare slashes to `\/` while leaving every existing escape
11
- * sequence (including an already-escaped `\/`) untouched.
9
+ * digit" to "a literal backslash followed by d"). Two things would otherwise
10
+ * corrupt the surrounding literal:
11
+ * - an *unescaped* `/`, which would close the literal early; and
12
+ * - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
13
+ * inside a regex literal and would split the emitted `/…/` across lines (a
14
+ * syntax error). Each is rewritten to its backslash escape, which matches
15
+ * the identical character, so the regex's meaning is unchanged.
16
+ *
17
+ * Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
18
+ * `/([/…` and produce output that does not parse. We compile the pattern with
19
+ * `new RegExp` here and throw a clear generator-time error instead, so a bad
20
+ * schema fails loudly during generation rather than emitting broken code.
12
21
  *
13
22
  * @example
14
23
  * escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
24
+ * @throws if `pattern` is not a valid regular expression.
15
25
  */
16
26
  export declare const escapeRegexPattern: (pattern: string) => string;
@@ -1,20 +1,58 @@
1
1
  /**
2
2
  * Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
3
- * a generated regex literal (`/…/`).
3
+ * a generated regex literal (`/…/`), and validates that the pattern is a legal
4
+ * regex at generation time.
4
5
  *
5
6
  * A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
6
7
  * regex literal — not a string literal — so backslashes are regex syntax and
7
8
  * must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
8
- * digit" to "a literal backslash followed by d"). The only character that would
9
- * corrupt the surrounding literal is an *unescaped* `/`, which would close it
10
- * early. So we escape bare slashes to `\/` while leaving every existing escape
11
- * sequence (including an already-escaped `\/`) untouched.
9
+ * digit" to "a literal backslash followed by d"). Two things would otherwise
10
+ * corrupt the surrounding literal:
11
+ * - an *unescaped* `/`, which would close the literal early; and
12
+ * - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
13
+ * inside a regex literal and would split the emitted `/…/` across lines (a
14
+ * syntax error). Each is rewritten to its backslash escape, which matches
15
+ * the identical character, so the regex's meaning is unchanged.
16
+ *
17
+ * Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
18
+ * `/([/…` and produce output that does not parse. We compile the pattern with
19
+ * `new RegExp` here and throw a clear generator-time error instead, so a bad
20
+ * schema fails loudly during generation rather than emitting broken code.
12
21
  *
13
22
  * @example
14
23
  * escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
24
+ * @throws if `pattern` is not a valid regular expression.
15
25
  */
16
- export const escapeRegexPattern = (pattern) =>
17
- // Match either an escape sequence (`\` + any char, kept verbatim) or a bare
18
- // `/` (escaped). Consuming escape pairs first means the slash in `\/` is never
19
- // seen as bare, so it is not double-escaped.
20
- pattern.replace(/\\[\s\S]|\//g, (match) => (match === '/' ? '\\/' : match));
26
+ export const escapeRegexPattern = (pattern) => {
27
+ // Validate at generation time — an invalid pattern must fail here, not emit
28
+ // a `/([/` literal that breaks the generated file.
29
+ try {
30
+ new RegExp(pattern);
31
+ }
32
+ catch (error) {
33
+ throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
34
+ }
35
+ // Line terminators, keyed by code point, and the backslash escape each maps to.
36
+ // These are the four characters disallowed *raw* inside a regex literal.
37
+ const lineTerminatorEscapes = {
38
+ 10: '\\n', // LF
39
+ 13: '\\r', // CR
40
+ 8232: '\\u2028', // LINE SEPARATOR
41
+ 8233: '\\u2029', // PARAGRAPH SEPARATOR
42
+ };
43
+ // Match either an escape sequence (`\` + any char, kept verbatim) or a single
44
+ // character that would corrupt the literal (a bare `/` or a line terminator).
45
+ // The line terminators are written as `\u….` escapes so this source file is
46
+ // itself free of the raw characters it guards against. Consuming escape pairs
47
+ // first means the slash in `\/` is never seen as bare, so it is not
48
+ // double-escaped.
49
+ return pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
50
+ if (match === '/')
51
+ return '\\/';
52
+ const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
53
+ if (terminatorEscape !== undefined && match.length === 1)
54
+ return terminatorEscape;
55
+ // An escape pair like `\/` or `\d`: keep exactly as authored.
56
+ return match;
57
+ });
58
+ };
@@ -31,12 +31,13 @@ export const generateIndexBarrel = (files, options = {}) => {
31
31
  constNames.push(match[1]);
32
32
  if (typeNames.length === 0 && constNames.length === 0)
33
33
  continue;
34
+ // `.js` extension so the barrel resolves under Node ESM, not only Bun.
34
35
  if (typesOnly) {
35
- indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}';\n`;
36
+ indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.js';\n`;
36
37
  }
37
38
  else {
38
39
  const typeExports = typeNames.map((name) => `type ${name}`);
39
- indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}';\n`;
40
+ indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.js';\n`;
40
41
  }
41
42
  }
42
43
  return indexContent;
@@ -116,6 +116,35 @@ const getTypeScriptType = (schema, options = {}) => {
116
116
  };
117
117
  /** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
118
118
  const recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
119
+ /**
120
+ * Builds the `Record<…>` type for a schema's `patternProperties`. Every pattern's
121
+ * value type is unioned (deduplicated) rather than only the first being used, so
122
+ * `{ '^a': string-schema, '^b': number-schema }` becomes `Record<string, string |
123
+ * number>` instead of silently dropping the second pattern. The template-literal
124
+ * `` `x-${string}` `` key is kept only when the sole pattern is the `^x-` vendor
125
+ * convention. Returns `undefined` when there are no usable patterns.
126
+ */
127
+ const patternPropertiesRecordType = (patternProperties, options) => {
128
+ const entries = Object.entries(patternProperties);
129
+ if (entries.length === 0)
130
+ return undefined;
131
+ const seen = new Set();
132
+ const valueTypes = [];
133
+ for (const [, value] of entries) {
134
+ const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
135
+ if (!seen.has(valueType)) {
136
+ seen.add(valueType);
137
+ valueTypes.push(valueType);
138
+ }
139
+ }
140
+ if (valueTypes.length === 0)
141
+ return undefined;
142
+ const valueType = valueTypes.join(' | ');
143
+ // The `^x-` vendor-extension convention maps to a template-literal key, but only
144
+ // when it is the single pattern (a union of key patterns can't be expressed).
145
+ const keyType = entries.length === 1 && entries[0]?.[0] === '^x-' ? '`x-${string}`' : 'string';
146
+ return recordType(keyType, valueType, options);
147
+ };
119
148
  /**
120
149
  * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
121
150
  * Recursively handles nested objects and arrays.
@@ -172,14 +201,6 @@ const getUnbrandedType = (schema, options = {}) => {
172
201
  }
173
202
  return enumUnion;
174
203
  }
175
- // Handle multi-value enum - union of literal types
176
- if (schema.enum && schema.enum.length > 1) {
177
- let multiEnumUnion = JSON.stringify(schema.enum[0]);
178
- for (let i = 1; i < schema.enum.length; i++) {
179
- multiEnumUnion += ' | ' + JSON.stringify(schema.enum[i]);
180
- }
181
- return multiEnumUnion;
182
- }
183
204
  // Handle union types (oneOf, anyOf) - check this before returning unknown
184
205
  if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
185
206
  // schema.oneOf[0] is safe: we guard with .length > 0 above
@@ -224,19 +245,9 @@ const getUnbrandedType = (schema, options = {}) => {
224
245
  return recordType('string', getTypeScriptType(schema.additionalProperties, options), options);
225
246
  }
226
247
  if (schema.patternProperties && typeof schema.patternProperties === 'object') {
227
- const firstEntry = Object.entries(schema.patternProperties)[0];
228
- if (firstEntry) {
229
- const [pattern, value] = firstEntry;
230
- if (value !== undefined) {
231
- const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
232
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
233
- // that maps naturally to the TypeScript template literal `x-${string}`
234
- if (pattern === '^x-') {
235
- return recordType('`x-${string}`', valueType, options);
236
- }
237
- return recordType('string', valueType, options);
238
- }
239
- }
248
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
249
+ if (record !== undefined)
250
+ return record;
240
251
  }
241
252
  if (schema.default !== undefined) {
242
253
  if (typeof schema.default === 'string') {
@@ -302,6 +313,9 @@ const getUnbrandedType = (schema, options = {}) => {
302
313
  case 'object':
303
314
  if (schema.properties) {
304
315
  const readonlyPrefix = options.readonly ? 'readonly ' : '';
316
+ // Build the required-key set once instead of an O(required) `includes`
317
+ // per property (O(properties × required) for a wide object).
318
+ const requiredSet = new Set(Array.isArray(schema.required) ? schema.required : []);
305
319
  const hasDescriptions = Object.values(schema.properties).some((p) => isSchemaObject(p) && (typeof p.description === 'string' || typeof p.$comment === 'string'));
306
320
  if (hasDescriptions) {
307
321
  let properties = '';
@@ -309,7 +323,7 @@ const getUnbrandedType = (schema, options = {}) => {
309
323
  for (const key in schema.properties) {
310
324
  // schema.properties[key] is safe: key comes from iterating schema.properties
311
325
  const propSchema = schema.properties[key];
312
- const isRequired = schema.required?.includes(key) ?? false;
326
+ const isRequired = requiredSet.has(key);
313
327
  const optional = isRequired ? '' : '?';
314
328
  const propType = getTypeScriptType(propSchema, options);
315
329
  const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === 'string'
@@ -342,7 +356,7 @@ const getUnbrandedType = (schema, options = {}) => {
342
356
  for (const key in schema.properties) {
343
357
  // schema.properties[key] is safe: key comes from iterating schema.properties
344
358
  const propSchema = schema.properties[key];
345
- const isRequired = schema.required?.includes(key) ?? false;
359
+ const isRequired = requiredSet.has(key);
346
360
  const optional = isRequired ? '' : '?';
347
361
  const propType = getTypeScriptType(propSchema, options);
348
362
  if (!first)
@@ -359,17 +373,9 @@ const getUnbrandedType = (schema, options = {}) => {
359
373
  }
360
374
  // Handle patternProperties as a Record type
361
375
  if (schema.patternProperties && typeof schema.patternProperties === 'object') {
362
- const firstEntry = Object.entries(schema.patternProperties)[0];
363
- if (firstEntry) {
364
- const [pattern, patternVal] = firstEntry;
365
- if (patternVal) {
366
- const valueType = getTypeScriptType(patternVal, options);
367
- if (pattern === '^x-') {
368
- return recordType('`x-${string}`', valueType, options);
369
- }
370
- return recordType('string', valueType, options);
371
- }
372
- }
376
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
377
+ if (record !== undefined)
378
+ return record;
373
379
  }
374
380
  return 'object';
375
381
  // Default to unknown
@@ -417,23 +423,12 @@ export const generateTypeDefinition = (schema, typeName, options = {}) => {
417
423
  Object.keys(normalizedSchema.patternProperties).length > 0;
418
424
  // Handle objects with only patternProperties (no fixed properties)
419
425
  if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
420
- const firstEntry = Object.entries(normalizedSchema.patternProperties)[0];
421
- const firstPattern = firstEntry?.[0];
422
- const firstPatternProperty = firstEntry?.[1];
423
- if (firstPatternProperty === undefined) {
424
- return `export type ${typeName} = Record<string, unknown>;`;
425
- }
426
- const patternPropType = typeof firstPatternProperty === 'boolean'
427
- ? getBooleanSubSchemaType(firstPatternProperty)
428
- : getTypeScriptType(firstPatternProperty, options);
429
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
430
- // that maps naturally to the TypeScript template literal `x-${string}`
431
- const keyType = firstPattern === '^x-' ? '`x-${string}`' : 'string';
426
+ const record = patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? 'Record<string, unknown>';
432
427
  let result = '';
433
428
  if (jsDocTitle && jsDocDescription) {
434
429
  result += buildJsDocBlock(jsDocTitle, jsDocDescription);
435
430
  }
436
- result += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`;
431
+ result += `export type ${typeName} = ${record};`;
437
432
  return result;
438
433
  }
439
434
  // Handle objects with only additionalProperties (no fixed properties)
@@ -447,12 +442,13 @@ export const generateTypeDefinition = (schema, typeName, options = {}) => {
447
442
  return result;
448
443
  }
449
444
  const schemaProps = normalizedSchema.properties ?? {};
445
+ const requiredSet = new Set(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : []);
450
446
  let properties = '';
451
447
  let isFirstProp = true;
452
448
  for (const key in schemaProps) {
453
449
  // schemaProps[key] is safe: key comes from iterating schemaProps
454
450
  const propSchema = schemaProps[key];
455
- const isRequired = normalizedSchema.required?.includes(key) ?? false;
451
+ const isRequired = requiredSet.has(key);
456
452
  const optional = isRequired ? '' : '?';
457
453
  const propType = getTypeScriptType(propSchema, options);
458
454
  const quotedKey = readonlyPrefix + safeKey(key);
@@ -0,0 +1,4 @@
1
+ /** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
2
+ export declare const multipleOfPassExpr: (valueExpr: string, divisor: number) => string;
3
+ /** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
4
+ export declare const multipleOfFailExpr: (valueExpr: string, divisor: number) => string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
3
+ * interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
4
+ *
5
+ * The naive `x % m === 0` is float-wrong: IEEE-754 makes `0.3 % 0.1` evaluate to
6
+ * `0.0999…`, so `0.3` would spuriously fail `multipleOf: 0.1`. The interpreter
7
+ * instead divides and compares the quotient to its nearest integer within a
8
+ * tolerance that *scales with the quotient's magnitude* — a fixed epsilon falsely
9
+ * rejects large values (e.g. `1234567.89` against `multipleOf: 0.01`) whose
10
+ * representation error in the quotient already exceeds it. Keeping the emitted
11
+ * check identical to the interpreter's keeps generated validators/parsers and the
12
+ * interpreter from disagreeing on the same document.
13
+ *
14
+ * `valueExpr` is inlined three times, so it must be a side-effect-free expression
15
+ * (a property read or a cached variable — which is all the generators ever pass).
16
+ */
17
+ const quotientTolerance = (valueExpr, divisor) => {
18
+ const q = `${valueExpr} / ${divisor}`;
19
+ return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
20
+ };
21
+ /** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
22
+ export const multipleOfPassExpr = (valueExpr, divisor) => {
23
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
24
+ return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
25
+ };
26
+ /** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
27
+ export const multipleOfFailExpr = (valueExpr, divisor) => {
28
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
29
+ return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
30
+ };
@@ -29,9 +29,13 @@ export const parseDocumentation = (markdownDocumentation, commentUrl, fallbackCo
29
29
  const headingHashes = headingLevelMatch?.[1] ?? '####';
30
30
  const subHeadingHashes = headingHashes + '#';
31
31
  // Find the section in the markdown
32
- // Match the section heading and capture everything until the next same-level heading or end of file
32
+ // Match the section heading and capture everything until the next same-level heading or end of file.
33
+ // `sectionTitle` comes from the URL fragment, so escape any regex metacharacters
34
+ // before interpolating — otherwise a fragment containing `+`, `(`, etc. throws a
35
+ // SyntaxError that the outer catch then mislabels as a fetch failure.
33
36
  const escapedHashes = headingHashes.replace(/#/g, '\\#');
34
- const sectionRegex = new RegExp(`${escapedHashes}\\s+${sectionTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, 'i');
37
+ const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
+ const sectionRegex = new RegExp(`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, 'i');
35
39
  const sectionMatch = markdown.match(sectionRegex);
36
40
  if (!sectionMatch) {
37
41
  return null;
@@ -1,20 +1,35 @@
1
1
  import { refToFilename } from './ref-to-filename.js';
2
2
  /**
3
- * Converts a kebab-case filename to PascalCase, appending an optional suffix.
3
+ * Converts a filename-like string to a PascalCase TypeScript identifier,
4
+ * appending an optional suffix.
5
+ *
6
+ * Word boundaries are *any* run of characters that cannot appear in a JS
7
+ * identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
8
+ * becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
9
+ * A leading digit is prefixed with `_`, and an otherwise-empty result falls back
10
+ * to `_`, so the output is always a usable identifier.
4
11
  *
5
12
  * @example
6
13
  * ```ts
7
14
  * kebabToPascal('server-variable') // 'ServerVariable'
8
15
  * kebabToPascal('channel') // 'Channel'
9
16
  * kebabToPascal('channel', 'Object') // 'ChannelObject'
17
+ * kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
18
+ * kebabToPascal('123abc') // '_123abc'
10
19
  * ```
11
20
  */
12
21
  const kebabToPascal = (kebab, suffix) => {
13
- const words = kebab.split('-');
22
+ const words = kebab.split(/[^A-Za-z0-9]+/);
14
23
  let pascalCase = '';
15
24
  for (const word of words) {
25
+ if (word === '')
26
+ continue;
16
27
  pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
17
28
  }
29
+ if (pascalCase === '')
30
+ pascalCase = '_';
31
+ else if (/^[0-9]/.test(pascalCase))
32
+ pascalCase = `_${pascalCase}`;
18
33
  return pascalCase + suffix;
19
34
  };
20
35
  /**
@@ -18,6 +18,12 @@ export const resolveDynamicRefs = (schema, dynamicRefMap) => {
18
18
  if (Object.keys(dynamicRefMap).length === 0) {
19
19
  return schema;
20
20
  }
21
+ // Cheap read-only pre-scan: most subschemas carry no `$dynamicRef`, so returning
22
+ // the original untouched avoids a full deep clone (and its allocation) on every
23
+ // node of every generator's walk when the document as a whole *does* use them.
24
+ if (!containsDynamicRef(schema)) {
25
+ return schema;
26
+ }
21
27
  const clone = JSON.parse(JSON.stringify(schema));
22
28
  const walk = (obj) => {
23
29
  if (typeof obj !== 'object' || obj === null) {
@@ -43,3 +49,21 @@ export const resolveDynamicRefs = (schema, dynamicRefMap) => {
43
49
  walk(clone);
44
50
  return clone;
45
51
  };
52
+ /** True if `value` contains a `$dynamicRef` string anywhere in its subtree. */
53
+ const containsDynamicRef = (value) => {
54
+ if (typeof value !== 'object' || value === null)
55
+ return false;
56
+ if (Array.isArray(value)) {
57
+ for (const item of value)
58
+ if (containsDynamicRef(item))
59
+ return true;
60
+ return false;
61
+ }
62
+ const record = value;
63
+ if (typeof record['$dynamicRef'] === 'string')
64
+ return true;
65
+ for (const key in record)
66
+ if (containsDynamicRef(record[key]))
67
+ return true;
68
+ return false;
69
+ };
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * @example
11
11
  * safeAccessor("input", "name") // "input.name"
12
- * safeAccessor("input?", "x-linkedin") // "input?.['x-linkedin']"
13
- * safeAccessor("input", "x-linkedin") // "input['x-linkedin']"
12
+ * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
13
+ * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
14
14
  */
15
15
  export declare const safeAccessor: (variable: string, key: string) => string;
16
16
  /**
@@ -19,6 +19,6 @@ export declare const safeAccessor: (variable: string, key: string) => string;
19
19
  *
20
20
  * @example
21
21
  * safeKey("name") // "name"
22
- * safeKey("x-linkedin") // "'x-linkedin'"
22
+ * safeKey("x-linkedin") // '"x-linkedin"'
23
23
  */
24
24
  export declare const safeKey: (key: string) => string;
@@ -15,18 +15,21 @@ const JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
15
15
  *
16
16
  * @example
17
17
  * safeAccessor("input", "name") // "input.name"
18
- * safeAccessor("input?", "x-linkedin") // "input?.['x-linkedin']"
19
- * safeAccessor("input", "x-linkedin") // "input['x-linkedin']"
18
+ * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
19
+ * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
20
20
  */
21
21
  export const safeAccessor = (variable, key) => {
22
22
  if (JS_IDENTIFIER.test(key)) {
23
23
  return `${variable}.${key}`;
24
24
  }
25
+ // Bracket keys are schema-controlled, so escape via JSON.stringify — a key like
26
+ // `it's` or `a']; evil(); //` would otherwise break or hijack the generated code.
27
+ const literal = JSON.stringify(key);
25
28
  // Handle optional chaining: "input?" -> "input?.['key']"
26
29
  if (variable.endsWith('?')) {
27
- return `${variable}.['${key}']`;
30
+ return `${variable}.[${literal}]`;
28
31
  }
29
- return `${variable}['${key}']`;
32
+ return `${variable}[${literal}]`;
30
33
  };
31
34
  /**
32
35
  * Generates a safe property key for use in object literals.
@@ -34,11 +37,12 @@ export const safeAccessor = (variable, key) => {
34
37
  *
35
38
  * @example
36
39
  * safeKey("name") // "name"
37
- * safeKey("x-linkedin") // "'x-linkedin'"
40
+ * safeKey("x-linkedin") // '"x-linkedin"'
38
41
  */
39
42
  export const safeKey = (key) => {
40
43
  if (JS_IDENTIFIER.test(key)) {
41
44
  return key;
42
45
  }
43
- return `'${key}'`;
46
+ // Schema-controlled keys must be escaped; a bare-quoted `it's` produces broken TS.
47
+ return JSON.stringify(key);
44
48
  };
@@ -10,7 +10,17 @@ export const validateRecord = (input, parser) => {
10
10
  const record = input;
11
11
  const result = {};
12
12
  for (const key in record) {
13
- result[key] = parser(record[key]);
13
+ const value = parser(record[key]);
14
+ // A plain assignment of `__proto__` invokes the prototype setter and
15
+ // corrupts `result`'s prototype (a prototype-pollution vector for untrusted
16
+ // input). Define it as an own data property instead so it round-trips as a
17
+ // normal key, matching every other property.
18
+ if (key === '__proto__') {
19
+ Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true });
20
+ }
21
+ else {
22
+ result[key] = value;
23
+ }
14
24
  }
15
25
  return result;
16
26
  };
@@ -6,7 +6,12 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
6
6
  * being copy-pasted into every generator.
7
7
  */
8
8
  export type RefNode = {
9
- /** The `$ref` string this node was reached through, or `undefined` for the root schema. */
9
+ /**
10
+ * The `$ref` string this node was reached through, or `undefined` for the
11
+ * root schema. Exception: an alias root (a bare `$ref` document) whose
12
+ * derived filename collides with its target's carries the target's ref, so
13
+ * generators can exclude self-imports from the merged file.
14
+ */
10
15
  ref: string | undefined;
11
16
  /** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
12
17
  typeName: string;
@@ -7,6 +7,38 @@ import { resolveDynamicRefs } from './resolve-dynamic-refs.js';
7
7
  import { resolveRef } from './resolve-ref.js';
8
8
  import { upgradeDraft07Schema } from './upgrade-draft07-schema.js';
9
9
  const rootCaches = new WeakMap();
10
+ /**
11
+ * Keywords that give a schema a shape of its own. A root carrying any of these
12
+ * next to its `$ref` is a real composition, not a pure alias, and keeps the
13
+ * default root handling.
14
+ */
15
+ const SHAPE_KEYWORDS = [
16
+ 'properties',
17
+ 'type',
18
+ 'oneOf',
19
+ 'anyOf',
20
+ 'allOf',
21
+ 'patternProperties',
22
+ 'additionalProperties',
23
+ 'enum',
24
+ 'const',
25
+ 'items',
26
+ 'prefixItems',
27
+ 'required',
28
+ 'if',
29
+ 'then',
30
+ 'else',
31
+ 'not',
32
+ ];
33
+ /** The `$ref` of a pure-alias root document (only `$ref` + metadata keys), or null. */
34
+ const getAliasRootRef = (schema) => {
35
+ if (typeof schema !== 'object' || schema === null)
36
+ return null;
37
+ const record = schema;
38
+ if (typeof record['$ref'] !== 'string')
39
+ return null;
40
+ return SHAPE_KEYWORDS.some((key) => key in record) ? null : record['$ref'];
41
+ };
10
42
  const getRootCache = (rootSchema) => {
11
43
  // Only object roots can key a WeakMap. A boolean root has no refs to walk and
12
44
  // the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
@@ -78,11 +110,27 @@ export const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
78
110
  // the same name does not emit a duplicate file.
79
111
  const rootFilename = rootTypeName.toLowerCase();
80
112
  processedFilenames.add(rootFilename);
113
+ // An alias root (a document that is just `$ref: '#/$defs/x'`) whose derived
114
+ // filename equals its target's would reserve the filename for a wrapper that
115
+ // re-exports the target — and the target, mapping to the same file, would
116
+ // then never be generated, leaving a file that imports itself. Generate the
117
+ // *target's* schema under the root's name instead, carrying the ref so
118
+ // generators can exclude the self-import.
119
+ let rootNodeSchema = upgraded;
120
+ let rootNodeRef;
121
+ const aliasRef = getAliasRootRef(upgraded);
122
+ if (aliasRef && refToFilename(aliasRef) === rootFilename) {
123
+ const resolved = cachedResolveRef(cache, aliasRef);
124
+ if (resolved) {
125
+ rootNodeSchema = resolved;
126
+ rootNodeRef = aliasRef;
127
+ }
128
+ }
81
129
  visit({
82
- ref: undefined,
130
+ ref: rootNodeRef,
83
131
  typeName: rootTypeName,
84
132
  filename: rootFilename,
85
- schema: resolveDynamicRefs(upgraded, dynamicRefMap),
133
+ schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
86
134
  rootSchema: upgraded,
87
135
  isRoot: true,
88
136
  });
@@ -90,8 +138,10 @@ export const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
90
138
  ...cachedExtractRefs(cache, upgraded),
91
139
  ...extractDynamicAnchorDefs(upgraded),
92
140
  ];
93
- while (queue.length > 0) {
94
- const ref = queue.shift();
141
+ // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
142
+ // makes draining a large ref graph quadratic.
143
+ for (let head = 0; head < queue.length; head++) {
144
+ const ref = queue[head];
95
145
  if (!ref || processedRefs.has(ref))
96
146
  continue;
97
147
  processedRefs.add(ref);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,7 +20,9 @@
20
20
  "url": "https://github.com/amritk/mjst/issues"
21
21
  },
22
22
  "files": [
23
- "dist"
23
+ "dist",
24
+ "src/**/*.ts",
25
+ "!src/**/*.test.ts"
24
26
  ],
25
27
  "publishConfig": {
26
28
  "access": "public"