@amritk/helpers 0.10.2 → 0.11.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.
- package/dist/escape-regex-pattern.d.ts +0 -25
- package/dist/escape-regex-pattern.js +26 -9
- package/dist/generate-index-barrel.d.ts +7 -0
- package/dist/generate-index-barrel.js +59 -11
- package/dist/quote-js-string.d.ts +14 -0
- package/dist/quote-js-string.js +19 -0
- package/dist/validate-array.d.ts +12 -1
- package/dist/validate-array.js +25 -5
- package/dist/walk-ref-graph.d.ts +6 -1
- package/dist/walk-ref-graph.js +50 -2
- package/package.json +1 -1
- package/src/escape-regex-pattern.ts +29 -10
- package/src/generate-index-barrel.ts +64 -9
- package/src/quote-js-string.ts +20 -0
- package/src/validate-array.ts +23 -5
- package/src/walk-ref-graph.ts +58 -3
|
@@ -1,26 +1 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
|
|
3
|
-
* a generated regex literal (`/…/`), and validates that the pattern is a legal
|
|
4
|
-
* regex at generation time.
|
|
5
|
-
*
|
|
6
|
-
* A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
|
|
7
|
-
* regex literal — not a string literal — so backslashes are regex syntax and
|
|
8
|
-
* must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
|
|
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.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
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.
|
|
25
|
-
*/
|
|
26
1
|
export declare const escapeRegexPattern: (pattern: string) => string;
|
|
@@ -23,7 +23,24 @@
|
|
|
23
23
|
* escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
|
|
24
24
|
* @throws if `pattern` is not a valid regular expression.
|
|
25
25
|
*/
|
|
26
|
+
// Line terminators, keyed by code point, and the backslash escape each maps to.
|
|
27
|
+
// These are the four characters disallowed *raw* inside a regex literal.
|
|
28
|
+
const lineTerminatorEscapes = {
|
|
29
|
+
10: '\\n', // LF
|
|
30
|
+
13: '\\r', // CR
|
|
31
|
+
8232: '\\u2028', // LINE SEPARATOR
|
|
32
|
+
8233: '\\u2029', // PARAGRAPH SEPARATOR
|
|
33
|
+
};
|
|
34
|
+
// Memoized results: the same schema pattern is escaped once per parser, per
|
|
35
|
+
// validator, and per assertion context, on every generation — and the dominant
|
|
36
|
+
// cost is the validating `new RegExp` compile. Schemas carry a bounded set of
|
|
37
|
+
// patterns; the cap only guards a pathological long-lived process.
|
|
38
|
+
const escapeCache = new Map();
|
|
39
|
+
const ESCAPE_CACHE_LIMIT = 1000;
|
|
26
40
|
export const escapeRegexPattern = (pattern) => {
|
|
41
|
+
const cached = escapeCache.get(pattern);
|
|
42
|
+
if (cached !== undefined)
|
|
43
|
+
return cached;
|
|
27
44
|
// Validate at generation time — an invalid pattern must fail here, not emit
|
|
28
45
|
// a `/([/` literal that breaks the generated file.
|
|
29
46
|
try {
|
|
@@ -32,21 +49,13 @@ export const escapeRegexPattern = (pattern) => {
|
|
|
32
49
|
catch (error) {
|
|
33
50
|
throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
34
51
|
}
|
|
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
|
-
0x0a: '\\n', // LF
|
|
39
|
-
0x0d: '\\r', // CR
|
|
40
|
-
0x2028: '\\u2028', // LINE SEPARATOR
|
|
41
|
-
0x2029: '\\u2029', // PARAGRAPH SEPARATOR
|
|
42
|
-
};
|
|
43
52
|
// Match either an escape sequence (`\` + any char, kept verbatim) or a single
|
|
44
53
|
// character that would corrupt the literal (a bare `/` or a line terminator).
|
|
45
54
|
// The line terminators are written as `\u….` escapes so this source file is
|
|
46
55
|
// itself free of the raw characters it guards against. Consuming escape pairs
|
|
47
56
|
// first means the slash in `\/` is never seen as bare, so it is not
|
|
48
57
|
// double-escaped.
|
|
49
|
-
|
|
58
|
+
const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
|
|
50
59
|
if (match === '/')
|
|
51
60
|
return '\\/';
|
|
52
61
|
const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
|
|
@@ -55,4 +64,12 @@ export const escapeRegexPattern = (pattern) => {
|
|
|
55
64
|
// An escape pair like `\/` or `\d`: keep exactly as authored.
|
|
56
65
|
return match;
|
|
57
66
|
});
|
|
67
|
+
if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
|
|
68
|
+
// Evict the single oldest entry (Maps iterate in insertion order) instead
|
|
69
|
+
// of clearing wholesale — a corpus slightly over the limit keeps its hot
|
|
70
|
+
// set instead of collapsing to a 0% hit rate every pass.
|
|
71
|
+
escapeCache.delete(escapeCache.keys().next().value);
|
|
72
|
+
}
|
|
73
|
+
escapeCache.set(pattern, escaped);
|
|
74
|
+
return escaped;
|
|
58
75
|
};
|
|
@@ -11,6 +11,13 @@ export type GenerateIndexBarrelOptions = {
|
|
|
11
11
|
* Defaults to `false`.
|
|
12
12
|
*/
|
|
13
13
|
readonly typesOnly?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Extension used on every relative re-export specifier. `'js'` (default) is
|
|
16
|
+
* the standard TS NodeNext form (`./x.js` resolving to a sibling `x.ts`);
|
|
17
|
+
* `'ts'` emits the literal on-disk path so the output runs directly under
|
|
18
|
+
* Node's type stripping.
|
|
19
|
+
*/
|
|
20
|
+
readonly importExt?: 'js' | 'ts';
|
|
14
21
|
};
|
|
15
22
|
/**
|
|
16
23
|
* Builds the `index.ts` barrel that re-exports every generated module. This is
|
|
@@ -1,7 +1,57 @@
|
|
|
1
|
-
// Generated files declare their public surface with
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
// Generated files declare their public surface with `export type <Name>` /
|
|
2
|
+
// `export const <Name>` at line starts, so the names can be recovered from the
|
|
3
|
+
// source text without parsing it.
|
|
4
|
+
/** Reads the identifier following `prefix` when `content` starts with it at `at`. */
|
|
5
|
+
const exportNameAt = (content, at, prefix) => {
|
|
6
|
+
if (!content.startsWith(prefix, at))
|
|
7
|
+
return null;
|
|
8
|
+
let end = at + prefix.length;
|
|
9
|
+
while (end < content.length) {
|
|
10
|
+
const code = content.charCodeAt(end);
|
|
11
|
+
const isWord = (code >= 97 && code <= 122) || (code >= 65 && code <= 90) || (code >= 48 && code <= 57) || code === 95;
|
|
12
|
+
if (!isWord)
|
|
13
|
+
break;
|
|
14
|
+
end++;
|
|
15
|
+
}
|
|
16
|
+
return end > at + prefix.length ? content.slice(at + prefix.length, end) : null;
|
|
17
|
+
};
|
|
18
|
+
/** True for every JS LineTerminator code unit — the same set the old `/m` regexes anchored after. */
|
|
19
|
+
const isLineTerminator = (code) => code === 10 || code === 13 || code === 8232 || code === 8233;
|
|
20
|
+
/**
|
|
21
|
+
* Collects `export type` / `export const` names with a single line-start walk.
|
|
22
|
+
* A multiline-anchored regex scan (`/^export .../gm`) does the same job but
|
|
23
|
+
* showed up at several percent of total generation time in CPU profiles — the
|
|
24
|
+
* regex engine re-anchors at every line of every generated file on every build.
|
|
25
|
+
*/
|
|
26
|
+
const collectExportNames = (content, typeNames, constNames) => {
|
|
27
|
+
let lineStart = 0;
|
|
28
|
+
while (lineStart < content.length) {
|
|
29
|
+
// charCode prefilter: almost every line starts with whitespace, a brace, or
|
|
30
|
+
// a keyword other than `export` — one integer compare skips the substring
|
|
31
|
+
// comparison for all of them (101 === 'e').
|
|
32
|
+
if (content.charCodeAt(lineStart) === 101 && content.startsWith('export ', lineStart)) {
|
|
33
|
+
const typeName = exportNameAt(content, lineStart, 'export type ');
|
|
34
|
+
if (typeName !== null) {
|
|
35
|
+
typeNames.push(typeName);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const constName = exportNameAt(content, lineStart, 'export const ');
|
|
39
|
+
if (constName !== null)
|
|
40
|
+
constNames.push(constName);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Advance past the next line break of ANY JS flavor (LF, CR, CRLF,
|
|
44
|
+
// U+2028, U+2029) — matching the multiline regexes this walk replaced,
|
|
45
|
+
// which treated all of them as line starts.
|
|
46
|
+
let next = lineStart;
|
|
47
|
+
while (next < content.length && !isLineTerminator(content.charCodeAt(next)))
|
|
48
|
+
next++;
|
|
49
|
+
if (next >= content.length)
|
|
50
|
+
break;
|
|
51
|
+
// \r\n counts as one break.
|
|
52
|
+
lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
5
55
|
/**
|
|
6
56
|
* Builds the `index.ts` barrel that re-exports every generated module. This is
|
|
7
57
|
* the shared version of the near-identical barrel each generator used to build
|
|
@@ -17,6 +67,7 @@ const CONST_EXPORT_RE = /^export const (\w+)/gm;
|
|
|
17
67
|
*/
|
|
18
68
|
export const generateIndexBarrel = (files, options = {}) => {
|
|
19
69
|
const typesOnly = options.typesOnly ?? false;
|
|
70
|
+
const importExt = options.importExt ?? 'js';
|
|
20
71
|
const sortedFiles = files
|
|
21
72
|
.filter((file) => !file.filename.startsWith('_helpers/'))
|
|
22
73
|
.sort((a, b) => a.filename.localeCompare(b.filename));
|
|
@@ -25,19 +76,16 @@ export const generateIndexBarrel = (files, options = {}) => {
|
|
|
25
76
|
const moduleName = file.filename.replace(/\.ts$/, '');
|
|
26
77
|
const typeNames = [];
|
|
27
78
|
const constNames = [];
|
|
28
|
-
|
|
29
|
-
typeNames.push(match[1]);
|
|
30
|
-
for (const match of file.content.matchAll(CONST_EXPORT_RE))
|
|
31
|
-
constNames.push(match[1]);
|
|
79
|
+
collectExportNames(file.content, typeNames, constNames);
|
|
32
80
|
if (typeNames.length === 0 && constNames.length === 0)
|
|
33
81
|
continue;
|
|
34
|
-
//
|
|
82
|
+
// An explicit extension so the barrel resolves under Node ESM, not only Bun.
|
|
35
83
|
if (typesOnly) {
|
|
36
|
-
indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}
|
|
84
|
+
indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.${importExt}';\n`;
|
|
37
85
|
}
|
|
38
86
|
else {
|
|
39
87
|
const typeExports = typeNames.map((name) => `type ${name}`);
|
|
40
|
-
indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}
|
|
88
|
+
indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.${importExt}';\n`;
|
|
41
89
|
}
|
|
42
90
|
}
|
|
43
91
|
return indexContent;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits `text` as a double-quoted JS string literal for generated code.
|
|
3
|
+
*
|
|
4
|
+
* This is the one escape-or-quote decision for schema-controlled text
|
|
5
|
+
* (property names, patterns, enum values) embedded in generated source — a key
|
|
6
|
+
* like `it's` or a pattern with a quote or newline must never break out of the
|
|
7
|
+
* literal or inject code, so anything carrying such a character goes through
|
|
8
|
+
* `JSON.stringify`. The common all-plain string skips the full escaper: code
|
|
9
|
+
* generators emit one literal per assertion/message, and the stringify calls
|
|
10
|
+
* were a measurable slice of generation time. Centralized so the next
|
|
11
|
+
* generator wanting the fast path cannot get the security-sensitive regex
|
|
12
|
+
* subtly wrong.
|
|
13
|
+
*/
|
|
14
|
+
export declare const quoteJsString: (text: string) => string;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Characters that force the JSON.stringify escaping path below: quote,
|
|
2
|
+
// backslash, C0 controls, and the JS line separators. Anything else sits
|
|
3
|
+
// verbatim inside a double-quoted literal.
|
|
4
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: the C0 range is exactly the set that must never appear raw in a generated string literal
|
|
5
|
+
const NEEDS_ESCAPING = /["\\\u0000-\u001f\u2028\u2029]/;
|
|
6
|
+
/**
|
|
7
|
+
* Emits `text` as a double-quoted JS string literal for generated code.
|
|
8
|
+
*
|
|
9
|
+
* This is the one escape-or-quote decision for schema-controlled text
|
|
10
|
+
* (property names, patterns, enum values) embedded in generated source — a key
|
|
11
|
+
* like `it's` or a pattern with a quote or newline must never break out of the
|
|
12
|
+
* literal or inject code, so anything carrying such a character goes through
|
|
13
|
+
* `JSON.stringify`. The common all-plain string skips the full escaper: code
|
|
14
|
+
* generators emit one literal per assertion/message, and the stringify calls
|
|
15
|
+
* were a measurable slice of generation time. Centralized so the next
|
|
16
|
+
* generator wanting the fast path cannot get the security-sensitive regex
|
|
17
|
+
* subtly wrong.
|
|
18
|
+
*/
|
|
19
|
+
export const quoteJsString = (text) => (NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`);
|
package/dist/validate-array.d.ts
CHANGED
|
@@ -1,2 +1,13 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Parses the items of an array with a parser function.
|
|
3
|
+
*
|
|
4
|
+
* When every element parses to the very same reference — the parser found it
|
|
5
|
+
* already valid and handed it back, as the generated item sub-parsers do for
|
|
6
|
+
* clean values — the input array itself is returned and nothing is allocated.
|
|
7
|
+
* The result array is only materialized (lazily, on the first element the
|
|
8
|
+
* parser actually replaced) when something was coerced or stripped, so the
|
|
9
|
+
* common all-clean parse costs no allocation at all. Callers already share
|
|
10
|
+
* element references either way; sharing the container mirrors the generated
|
|
11
|
+
* fast paths, which return the input array by reference too.
|
|
12
|
+
*/
|
|
2
13
|
export declare const validateArray: (input: unknown, parser: (input: unknown) => unknown) => any[];
|
package/dist/validate-array.js
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Parses the items of an array with a parser function.
|
|
3
|
+
*
|
|
4
|
+
* When every element parses to the very same reference — the parser found it
|
|
5
|
+
* already valid and handed it back, as the generated item sub-parsers do for
|
|
6
|
+
* clean values — the input array itself is returned and nothing is allocated.
|
|
7
|
+
* The result array is only materialized (lazily, on the first element the
|
|
8
|
+
* parser actually replaced) when something was coerced or stripped, so the
|
|
9
|
+
* common all-clean parse costs no allocation at all. Callers already share
|
|
10
|
+
* element references either way; sharing the container mirrors the generated
|
|
11
|
+
* fast paths, which return the input array by reference too.
|
|
12
|
+
*/
|
|
2
13
|
export const validateArray = (input, parser) => {
|
|
3
14
|
if (!Array.isArray(input)) {
|
|
4
15
|
return [];
|
|
5
16
|
}
|
|
6
|
-
// Pre-allocate the result array for better performance than push()
|
|
7
17
|
const len = input.length;
|
|
8
|
-
|
|
18
|
+
let result = null;
|
|
9
19
|
for (let i = 0; i < len; i++) {
|
|
10
|
-
|
|
20
|
+
const parsed = parser(input[i]);
|
|
21
|
+
if (result !== null) {
|
|
22
|
+
result[i] = parsed;
|
|
23
|
+
}
|
|
24
|
+
else if (parsed !== input[i]) {
|
|
25
|
+
// First replaced element: materialize the copy and backfill the prefix.
|
|
26
|
+
result = new Array(len);
|
|
27
|
+
for (let j = 0; j < i; j++)
|
|
28
|
+
result[j] = input[j];
|
|
29
|
+
result[i] = parsed;
|
|
30
|
+
}
|
|
11
31
|
}
|
|
12
|
-
return result;
|
|
32
|
+
return result ?? input;
|
|
13
33
|
};
|
package/dist/walk-ref-graph.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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;
|
package/dist/walk-ref-graph.js
CHANGED
|
@@ -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:
|
|
130
|
+
ref: rootNodeRef,
|
|
83
131
|
typeName: rootTypeName,
|
|
84
132
|
filename: rootFilename,
|
|
85
|
-
schema: resolveDynamicRefs(
|
|
133
|
+
schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
|
|
86
134
|
rootSchema: upgraded,
|
|
87
135
|
isRoot: true,
|
|
88
136
|
});
|
package/package.json
CHANGED
|
@@ -23,7 +23,26 @@
|
|
|
23
23
|
* escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
|
|
24
24
|
* @throws if `pattern` is not a valid regular expression.
|
|
25
25
|
*/
|
|
26
|
+
// Line terminators, keyed by code point, and the backslash escape each maps to.
|
|
27
|
+
// These are the four characters disallowed *raw* inside a regex literal.
|
|
28
|
+
const lineTerminatorEscapes: Record<number, string> = {
|
|
29
|
+
10: '\\n', // LF
|
|
30
|
+
13: '\\r', // CR
|
|
31
|
+
8232: '\\u2028', // LINE SEPARATOR
|
|
32
|
+
8233: '\\u2029', // PARAGRAPH SEPARATOR
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Memoized results: the same schema pattern is escaped once per parser, per
|
|
36
|
+
// validator, and per assertion context, on every generation — and the dominant
|
|
37
|
+
// cost is the validating `new RegExp` compile. Schemas carry a bounded set of
|
|
38
|
+
// patterns; the cap only guards a pathological long-lived process.
|
|
39
|
+
const escapeCache = new Map<string, string>()
|
|
40
|
+
const ESCAPE_CACHE_LIMIT = 1000
|
|
41
|
+
|
|
26
42
|
export const escapeRegexPattern = (pattern: string): string => {
|
|
43
|
+
const cached = escapeCache.get(pattern)
|
|
44
|
+
if (cached !== undefined) return cached
|
|
45
|
+
|
|
27
46
|
// Validate at generation time — an invalid pattern must fail here, not emit
|
|
28
47
|
// a `/([/` literal that breaks the generated file.
|
|
29
48
|
try {
|
|
@@ -34,26 +53,26 @@ export const escapeRegexPattern = (pattern: string): string => {
|
|
|
34
53
|
)
|
|
35
54
|
}
|
|
36
55
|
|
|
37
|
-
// Line terminators, keyed by code point, and the backslash escape each maps to.
|
|
38
|
-
// These are the four characters disallowed *raw* inside a regex literal.
|
|
39
|
-
const lineTerminatorEscapes: Record<number, string> = {
|
|
40
|
-
0x0a: '\\n', // LF
|
|
41
|
-
0x0d: '\\r', // CR
|
|
42
|
-
0x2028: '\\u2028', // LINE SEPARATOR
|
|
43
|
-
0x2029: '\\u2029', // PARAGRAPH SEPARATOR
|
|
44
|
-
}
|
|
45
|
-
|
|
46
56
|
// Match either an escape sequence (`\` + any char, kept verbatim) or a single
|
|
47
57
|
// character that would corrupt the literal (a bare `/` or a line terminator).
|
|
48
58
|
// The line terminators are written as `\u….` escapes so this source file is
|
|
49
59
|
// itself free of the raw characters it guards against. Consuming escape pairs
|
|
50
60
|
// first means the slash in `\/` is never seen as bare, so it is not
|
|
51
61
|
// double-escaped.
|
|
52
|
-
|
|
62
|
+
const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
|
|
53
63
|
if (match === '/') return '\\/'
|
|
54
64
|
const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)]
|
|
55
65
|
if (terminatorEscape !== undefined && match.length === 1) return terminatorEscape
|
|
56
66
|
// An escape pair like `\/` or `\d`: keep exactly as authored.
|
|
57
67
|
return match
|
|
58
68
|
})
|
|
69
|
+
|
|
70
|
+
if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
|
|
71
|
+
// Evict the single oldest entry (Maps iterate in insertion order) instead
|
|
72
|
+
// of clearing wholesale — a corpus slightly over the limit keeps its hot
|
|
73
|
+
// set instead of collapsing to a 0% hit rate every pass.
|
|
74
|
+
escapeCache.delete(escapeCache.keys().next().value as string)
|
|
75
|
+
}
|
|
76
|
+
escapeCache.set(pattern, escaped)
|
|
77
|
+
return escaped
|
|
59
78
|
}
|
|
@@ -12,12 +12,67 @@ export type GenerateIndexBarrelOptions = {
|
|
|
12
12
|
* Defaults to `false`.
|
|
13
13
|
*/
|
|
14
14
|
readonly typesOnly?: boolean
|
|
15
|
+
/**
|
|
16
|
+
* Extension used on every relative re-export specifier. `'js'` (default) is
|
|
17
|
+
* the standard TS NodeNext form (`./x.js` resolving to a sibling `x.ts`);
|
|
18
|
+
* `'ts'` emits the literal on-disk path so the output runs directly under
|
|
19
|
+
* Node's type stripping.
|
|
20
|
+
*/
|
|
21
|
+
readonly importExt?: 'js' | 'ts'
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Generated files declare their public surface with `export type <Name>` /
|
|
25
|
+
// `export const <Name>` at line starts, so the names can be recovered from the
|
|
26
|
+
// source text without parsing it.
|
|
27
|
+
|
|
28
|
+
/** Reads the identifier following `prefix` when `content` starts with it at `at`. */
|
|
29
|
+
const exportNameAt = (content: string, at: number, prefix: string): string | null => {
|
|
30
|
+
if (!content.startsWith(prefix, at)) return null
|
|
31
|
+
let end = at + prefix.length
|
|
32
|
+
while (end < content.length) {
|
|
33
|
+
const code = content.charCodeAt(end)
|
|
34
|
+
const isWord =
|
|
35
|
+
(code >= 97 && code <= 122) || (code >= 65 && code <= 90) || (code >= 48 && code <= 57) || code === 95
|
|
36
|
+
if (!isWord) break
|
|
37
|
+
end++
|
|
38
|
+
}
|
|
39
|
+
return end > at + prefix.length ? content.slice(at + prefix.length, end) : null
|
|
15
40
|
}
|
|
16
41
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
42
|
+
/** True for every JS LineTerminator code unit — the same set the old `/m` regexes anchored after. */
|
|
43
|
+
const isLineTerminator = (code: number): boolean => code === 10 || code === 13 || code === 8232 || code === 8233
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Collects `export type` / `export const` names with a single line-start walk.
|
|
47
|
+
* A multiline-anchored regex scan (`/^export .../gm`) does the same job but
|
|
48
|
+
* showed up at several percent of total generation time in CPU profiles — the
|
|
49
|
+
* regex engine re-anchors at every line of every generated file on every build.
|
|
50
|
+
*/
|
|
51
|
+
const collectExportNames = (content: string, typeNames: string[], constNames: string[]): void => {
|
|
52
|
+
let lineStart = 0
|
|
53
|
+
while (lineStart < content.length) {
|
|
54
|
+
// charCode prefilter: almost every line starts with whitespace, a brace, or
|
|
55
|
+
// a keyword other than `export` — one integer compare skips the substring
|
|
56
|
+
// comparison for all of them (101 === 'e').
|
|
57
|
+
if (content.charCodeAt(lineStart) === 101 && content.startsWith('export ', lineStart)) {
|
|
58
|
+
const typeName = exportNameAt(content, lineStart, 'export type ')
|
|
59
|
+
if (typeName !== null) {
|
|
60
|
+
typeNames.push(typeName)
|
|
61
|
+
} else {
|
|
62
|
+
const constName = exportNameAt(content, lineStart, 'export const ')
|
|
63
|
+
if (constName !== null) constNames.push(constName)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Advance past the next line break of ANY JS flavor (LF, CR, CRLF,
|
|
67
|
+
// U+2028, U+2029) — matching the multiline regexes this walk replaced,
|
|
68
|
+
// which treated all of them as line starts.
|
|
69
|
+
let next = lineStart
|
|
70
|
+
while (next < content.length && !isLineTerminator(content.charCodeAt(next))) next++
|
|
71
|
+
if (next >= content.length) break
|
|
72
|
+
// \r\n counts as one break.
|
|
73
|
+
lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1
|
|
74
|
+
}
|
|
75
|
+
}
|
|
21
76
|
|
|
22
77
|
/**
|
|
23
78
|
* Builds the `index.ts` barrel that re-exports every generated module. This is
|
|
@@ -34,6 +89,7 @@ const CONST_EXPORT_RE = /^export const (\w+)/gm
|
|
|
34
89
|
*/
|
|
35
90
|
export const generateIndexBarrel = (files: IndexBarrelFile[], options: GenerateIndexBarrelOptions = {}): string => {
|
|
36
91
|
const typesOnly = options.typesOnly ?? false
|
|
92
|
+
const importExt = options.importExt ?? 'js'
|
|
37
93
|
|
|
38
94
|
const sortedFiles = files
|
|
39
95
|
.filter((file) => !file.filename.startsWith('_helpers/'))
|
|
@@ -45,17 +101,16 @@ export const generateIndexBarrel = (files: IndexBarrelFile[], options: GenerateI
|
|
|
45
101
|
const typeNames: string[] = []
|
|
46
102
|
const constNames: string[] = []
|
|
47
103
|
|
|
48
|
-
|
|
49
|
-
for (const match of file.content.matchAll(CONST_EXPORT_RE)) constNames.push(match[1] as string)
|
|
104
|
+
collectExportNames(file.content, typeNames, constNames)
|
|
50
105
|
|
|
51
106
|
if (typeNames.length === 0 && constNames.length === 0) continue
|
|
52
107
|
|
|
53
|
-
//
|
|
108
|
+
// An explicit extension so the barrel resolves under Node ESM, not only Bun.
|
|
54
109
|
if (typesOnly) {
|
|
55
|
-
indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}
|
|
110
|
+
indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.${importExt}';\n`
|
|
56
111
|
} else {
|
|
57
112
|
const typeExports = typeNames.map((name) => `type ${name}`)
|
|
58
|
-
indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}
|
|
113
|
+
indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.${importExt}';\n`
|
|
59
114
|
}
|
|
60
115
|
}
|
|
61
116
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Characters that force the JSON.stringify escaping path below: quote,
|
|
2
|
+
// backslash, C0 controls, and the JS line separators. Anything else sits
|
|
3
|
+
// verbatim inside a double-quoted literal.
|
|
4
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: the C0 range is exactly the set that must never appear raw in a generated string literal
|
|
5
|
+
const NEEDS_ESCAPING = /["\\\u0000-\u001f\u2028\u2029]/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Emits `text` as a double-quoted JS string literal for generated code.
|
|
9
|
+
*
|
|
10
|
+
* This is the one escape-or-quote decision for schema-controlled text
|
|
11
|
+
* (property names, patterns, enum values) embedded in generated source — a key
|
|
12
|
+
* like `it's` or a pattern with a quote or newline must never break out of the
|
|
13
|
+
* literal or inject code, so anything carrying such a character goes through
|
|
14
|
+
* `JSON.stringify`. The common all-plain string skips the full escaper: code
|
|
15
|
+
* generators emit one literal per assertion/message, and the stringify calls
|
|
16
|
+
* were a measurable slice of generation time. Centralized so the next
|
|
17
|
+
* generator wanting the fast path cannot get the security-sensitive regex
|
|
18
|
+
* subtly wrong.
|
|
19
|
+
*/
|
|
20
|
+
export const quoteJsString = (text: string): string => (NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`)
|
package/src/validate-array.ts
CHANGED
|
@@ -1,15 +1,33 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Parses the items of an array with a parser function.
|
|
3
|
+
*
|
|
4
|
+
* When every element parses to the very same reference — the parser found it
|
|
5
|
+
* already valid and handed it back, as the generated item sub-parsers do for
|
|
6
|
+
* clean values — the input array itself is returned and nothing is allocated.
|
|
7
|
+
* The result array is only materialized (lazily, on the first element the
|
|
8
|
+
* parser actually replaced) when something was coerced or stripped, so the
|
|
9
|
+
* common all-clean parse costs no allocation at all. Callers already share
|
|
10
|
+
* element references either way; sharing the container mirrors the generated
|
|
11
|
+
* fast paths, which return the input array by reference too.
|
|
12
|
+
*/
|
|
2
13
|
export const validateArray = (input: unknown, parser: (input: unknown) => unknown) => {
|
|
3
14
|
if (!Array.isArray(input)) {
|
|
4
15
|
return []
|
|
5
16
|
}
|
|
6
17
|
|
|
7
|
-
// Pre-allocate the result array for better performance than push()
|
|
8
18
|
const len = input.length
|
|
9
|
-
|
|
19
|
+
let result: unknown[] | null = null
|
|
10
20
|
for (let i = 0; i < len; i++) {
|
|
11
|
-
|
|
21
|
+
const parsed = parser(input[i])
|
|
22
|
+
if (result !== null) {
|
|
23
|
+
result[i] = parsed
|
|
24
|
+
} else if (parsed !== input[i]) {
|
|
25
|
+
// First replaced element: materialize the copy and backfill the prefix.
|
|
26
|
+
result = new Array(len)
|
|
27
|
+
for (let j = 0; j < i; j++) result[j] = input[j]
|
|
28
|
+
result[i] = parsed
|
|
29
|
+
}
|
|
12
30
|
}
|
|
13
31
|
|
|
14
|
-
return result
|
|
32
|
+
return result ?? input
|
|
15
33
|
}
|
package/src/walk-ref-graph.ts
CHANGED
|
@@ -16,7 +16,12 @@ import { upgradeDraft07Schema } from './upgrade-draft07-schema'
|
|
|
16
16
|
* being copy-pasted into every generator.
|
|
17
17
|
*/
|
|
18
18
|
export type RefNode = {
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* The `$ref` string this node was reached through, or `undefined` for the
|
|
21
|
+
* root schema. Exception: an alias root (a bare `$ref` document) whose
|
|
22
|
+
* derived filename collides with its target's carries the target's ref, so
|
|
23
|
+
* generators can exclude self-imports from the merged file.
|
|
24
|
+
*/
|
|
20
25
|
ref: string | undefined
|
|
21
26
|
/** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
|
|
22
27
|
typeName: string
|
|
@@ -57,6 +62,38 @@ type RootCache = {
|
|
|
57
62
|
|
|
58
63
|
const rootCaches = new WeakMap<object, RootCache>()
|
|
59
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Keywords that give a schema a shape of its own. A root carrying any of these
|
|
67
|
+
* next to its `$ref` is a real composition, not a pure alias, and keeps the
|
|
68
|
+
* default root handling.
|
|
69
|
+
*/
|
|
70
|
+
const SHAPE_KEYWORDS = [
|
|
71
|
+
'properties',
|
|
72
|
+
'type',
|
|
73
|
+
'oneOf',
|
|
74
|
+
'anyOf',
|
|
75
|
+
'allOf',
|
|
76
|
+
'patternProperties',
|
|
77
|
+
'additionalProperties',
|
|
78
|
+
'enum',
|
|
79
|
+
'const',
|
|
80
|
+
'items',
|
|
81
|
+
'prefixItems',
|
|
82
|
+
'required',
|
|
83
|
+
'if',
|
|
84
|
+
'then',
|
|
85
|
+
'else',
|
|
86
|
+
'not',
|
|
87
|
+
] as const
|
|
88
|
+
|
|
89
|
+
/** The `$ref` of a pure-alias root document (only `$ref` + metadata keys), or null. */
|
|
90
|
+
const getAliasRootRef = (schema: JSONSchema): string | null => {
|
|
91
|
+
if (typeof schema !== 'object' || schema === null) return null
|
|
92
|
+
const record = schema as Record<string, unknown>
|
|
93
|
+
if (typeof record['$ref'] !== 'string') return null
|
|
94
|
+
return SHAPE_KEYWORDS.some((key) => key in record) ? null : record['$ref']
|
|
95
|
+
}
|
|
96
|
+
|
|
60
97
|
const getRootCache = (rootSchema: JSONSchema): RootCache => {
|
|
61
98
|
// Only object roots can key a WeakMap. A boolean root has no refs to walk and
|
|
62
99
|
// the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
|
|
@@ -136,11 +173,29 @@ export const walkRefGraph = (
|
|
|
136
173
|
// the same name does not emit a duplicate file.
|
|
137
174
|
const rootFilename = rootTypeName.toLowerCase()
|
|
138
175
|
processedFilenames.add(rootFilename)
|
|
176
|
+
|
|
177
|
+
// An alias root (a document that is just `$ref: '#/$defs/x'`) whose derived
|
|
178
|
+
// filename equals its target's would reserve the filename for a wrapper that
|
|
179
|
+
// re-exports the target — and the target, mapping to the same file, would
|
|
180
|
+
// then never be generated, leaving a file that imports itself. Generate the
|
|
181
|
+
// *target's* schema under the root's name instead, carrying the ref so
|
|
182
|
+
// generators can exclude the self-import.
|
|
183
|
+
let rootNodeSchema = upgraded as JSONSchema
|
|
184
|
+
let rootNodeRef: string | undefined
|
|
185
|
+
const aliasRef = getAliasRootRef(upgraded as JSONSchema)
|
|
186
|
+
if (aliasRef && refToFilename(aliasRef) === rootFilename) {
|
|
187
|
+
const resolved = cachedResolveRef(cache, aliasRef)
|
|
188
|
+
if (resolved) {
|
|
189
|
+
rootNodeSchema = resolved as JSONSchema
|
|
190
|
+
rootNodeRef = aliasRef
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
139
194
|
visit({
|
|
140
|
-
ref:
|
|
195
|
+
ref: rootNodeRef,
|
|
141
196
|
typeName: rootTypeName,
|
|
142
197
|
filename: rootFilename,
|
|
143
|
-
schema: resolveDynamicRefs(
|
|
198
|
+
schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
|
|
144
199
|
rootSchema: upgraded,
|
|
145
200
|
isRoot: true,
|
|
146
201
|
})
|