@alexify/metaschema 2.0.0 → 3.1.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
@@ -0,0 +1,254 @@
1
+ // Two schemas as one (`merge`), by unification: a field in both takes the
2
+ // constraints of both (the length and the bounds that satisfy both, the
3
+ // values both enums hold, the validate functions of both), a field in one
4
+ // comes as it is, and what no value can satisfy (two types, two patterns,
5
+ // bounds with nothing in common, two defaults) is ERR_MERGE_CONFLICT with
6
+ // the field. CUE composes definitions this way, instead of inheritance.
7
+ const { hasBrand, define } = require('../util.js');
8
+ const { Schema } = require('../schema.js');
9
+ const { isStruct } = require('../struct.js');
10
+ const { isThenable } = require('../issues.js');
11
+ const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
+ const { same, capitalize, definitionOf, structDefinitionOf, atSchema } = require('./data.js');
13
+
14
+ // The keys a field definition settles by a rule of its own; every other key
15
+ // (an annotation, an option of a custom type) comes from the first schema.
16
+ const BOOLEANS = new Set(['unique', 'index', 'primary', 'deprecated']);
17
+
18
+ // A conflict carries the path of the field it is at; `merge` locates it in
19
+ // the schema on the way out, as a struct does with a definition error.
20
+ const conflict = (reason, path = '') => {
21
+ const error = new SchemaDefinitionError('ERR_MERGE_CONFLICT', reason);
22
+ error.field = path;
23
+ return error;
24
+ };
25
+
26
+ // Both validate functions, as one that returns what both returned (an
27
+ // array of returns is one the check reads), awaited when either is async.
28
+ const compose = (first, second) =>
29
+ function validate(value, path) {
30
+ const a = first.call(this, value, path);
31
+ const b = second.call(this, value, path);
32
+ if (isThenable(a) || isThenable(b)) return Promise.all([a, b]);
33
+ return [a, b];
34
+ };
35
+
36
+ const lower = (a, b) => (a === undefined ? b : b === undefined ? a : a > b ? a : b);
37
+
38
+ const upper = (a, b) => (a === undefined ? b : b === undefined ? a : a < b ? a : b);
39
+
40
+ // The length both rules allow: the greater of the minimums, the lesser of
41
+ // the maximums.
42
+ const mergeLength = (a, b, path) => {
43
+ const min = lower(a.min, b.min);
44
+ const max = upper(a.max, b.max);
45
+ if (min !== undefined && max !== undefined && min > max) {
46
+ throw conflict('The lengths have nothing in common', path);
47
+ }
48
+ const length = {};
49
+ if (min !== undefined) length.min = min;
50
+ if (max !== undefined) length.max = max;
51
+ return length;
52
+ };
53
+
54
+ const mergeEnum = (a, b, path) => {
55
+ const values = [];
56
+ for (const value of a) {
57
+ for (const other of b) {
58
+ if (same(value, other)) {
59
+ values.push(value);
60
+ break;
61
+ }
62
+ }
63
+ }
64
+ if (values.length === 0) throw conflict('The enums have no value in common', path);
65
+ return values;
66
+ };
67
+
68
+ const mergeList = (a, b, path) => {
69
+ if (a.length !== b.length) throw conflict('The elements differ in number', path);
70
+ const list = [];
71
+ for (let index = 0; index < a.length; index += 1) {
72
+ list.push(mergeFields(a[index], b[index], `${path}[${index}]`));
73
+ }
74
+ return list;
75
+ };
76
+
77
+ // One key of two definitions of a field: a value the other side lacks
78
+ // stands (null is allowed only where both allow it), the same value stands,
79
+ // two values settle by the rule of the key.
80
+ const mergeKey = (key, a, b, path) => {
81
+ if (key === 'nullable') return a === true && b === true ? true : undefined;
82
+ if (a === undefined) return b;
83
+ if (b === undefined) return a;
84
+ if (same(a, b)) return a;
85
+ switch (key) {
86
+ case 'required':
87
+ return a || b;
88
+ case 'length':
89
+ return mergeLength(a, b, path);
90
+ case 'min':
91
+ return a > b ? a : b;
92
+ case 'max':
93
+ return a < b ? a : b;
94
+ case 'enum':
95
+ return mergeEnum(a, b, path);
96
+ case 'validate':
97
+ return compose(a, b);
98
+ case 'aliases':
99
+ return Array.from(new Set(a.concat(b)));
100
+ case 'schema':
101
+ if (typeof a.type === 'string' || typeof b.type === 'string') {
102
+ throw conflict('A struct in one schema and a schema of one type in the other', path);
103
+ }
104
+ return mergeStruct(a, b, path);
105
+ case 'value':
106
+ if (Array.isArray(a) !== Array.isArray(b)) {
107
+ throw conflict('A tuple in one schema and not in the other', path);
108
+ }
109
+ return Array.isArray(a) ? mergeList(a, b, path) : mergeFields(a, b, `${path}[]`);
110
+ case 'pattern':
111
+ case 'default':
112
+ case 'parse':
113
+ case 'serialize':
114
+ case 'union':
115
+ case 'discriminator':
116
+ case 'key':
117
+ case 'one':
118
+ case 'many':
119
+ case 'embed':
120
+ throw conflict(`The ${key} differs between the schemas`, path);
121
+ default:
122
+ return BOOLEANS.has(key) ? a || b : a;
123
+ }
124
+ };
125
+
126
+ // The types a field may have in the two schemas as one: the same, or any
127
+ // (unknown) and a type, or integer and number, which is integer.
128
+ const mergeType = (a, b, path) => {
129
+ if (a === b) return a;
130
+ if (a === 'any' || a === 'unknown') return b;
131
+ if (b === 'any' || b === 'unknown') return a;
132
+ if ((a === 'integer' && b === 'number') || (a === 'number' && b === 'integer')) return 'integer';
133
+ throw conflict(`The type is ${a} in one schema and ${b} in the other`, path);
134
+ };
135
+
136
+ // Two definitions of one field as one; a string or a built field is its
137
+ // definition first. Bounds that leave nothing between them are a conflict,
138
+ // as two lengths are.
139
+ const mergeFields = (x, y, path) => {
140
+ const a = typeof x === 'string' ? { type: x } : x;
141
+ const b = typeof y === 'string' ? { type: y } : y;
142
+ const type = mergeType(a.type, b.type, path);
143
+ // The side whose type the result has sets the keys of its type.
144
+ const [first, second] = type === b.type && type !== a.type ? [b, a] : [a, b];
145
+ const def = { type };
146
+ const keys = new Set(Object.keys(first));
147
+ for (const key of Object.keys(second)) keys.add(key);
148
+ for (const key of keys) {
149
+ if (key === 'type') continue;
150
+ const value = mergeKey(key, first[key], second[key], path);
151
+ if (value !== undefined) define(def, key, value);
152
+ }
153
+ if (def.min !== undefined && def.max !== undefined && def.min > def.max) {
154
+ throw conflict('The bounds have nothing in common', path);
155
+ }
156
+ return def;
157
+ };
158
+
159
+ const isFunction = (value) => typeof value === 'function';
160
+
161
+ const at = (path, key) => (path === '' ? key : `${path}.${key}`);
162
+
163
+ // The fields of two structs as one: the fields of the first in their order,
164
+ // then the ones only the second has. An alias of a field that is a field of
165
+ // the other schema, or an alias of two fields, is a key the struct cannot
166
+ // read twice.
167
+ const mergeStruct = (a, b, path) => {
168
+ const fields = {};
169
+ const keys = new Set(Object.keys(a));
170
+ for (const key of Object.keys(b)) keys.add(key);
171
+ const taken = new Set(keys);
172
+ for (const key of keys) {
173
+ const x = Object.hasOwn(a, key) ? a[key] : undefined;
174
+ const y = Object.hasOwn(b, key) ? b[key] : undefined;
175
+ const where = at(path, key);
176
+ let def = x === undefined ? y : x;
177
+ if (x !== undefined && y !== undefined) {
178
+ if (isFunction(x) || isFunction(y)) {
179
+ if (key === 'validate' && isFunction(x) && isFunction(y)) def = compose(x, y);
180
+ else if (x !== y) throw conflict('The function differs between the schemas', where);
181
+ } else def = mergeFields(x, y, where);
182
+ }
183
+ define(fields, key, def);
184
+ for (const alias of def.aliases ?? []) {
185
+ if (taken.has(alias)) {
186
+ throw conflict(`The alias "${alias}" is a field or an alias already`, where);
187
+ }
188
+ taken.add(alias);
189
+ }
190
+ }
191
+ return fields;
192
+ };
193
+
194
+ // The schema both schemas describe. The kind and its metadata are the first
195
+ // schema's (`options.metadata` says otherwise), the name too unless
196
+ // `options.name`; the indexes are the ones of either (the same under one
197
+ // key), the functions of the schema itself compose as a field's do.
198
+ const merge = (a, b, options = {}) => {
199
+ if (!hasBrand(a, 'Schema') || !hasBrand(b, 'Schema')) {
200
+ throw invalidTarget('Two Schemas are expected');
201
+ }
202
+ if (options === null || typeof options !== 'object') {
203
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Merge options must be an object');
204
+ }
205
+ const { name = a.name, metadata = {} } = options;
206
+ const namespaces = Array.from(new Set([...a.namespaces, ...b.namespaces]));
207
+ const structA = isStruct(a.fields);
208
+ const structB = isStruct(b.fields);
209
+ try {
210
+ if (!structA || !structB) {
211
+ if (structA !== structB) throw conflict('A struct and a schema of one type cannot be merged');
212
+ return new Schema(
213
+ name,
214
+ mergeFields(definitionOf(a.fields), definitionOf(b.fields), ''),
215
+ namespaces,
216
+ );
217
+ }
218
+ const { kind, scope, store, allow, unknown, custom } = a;
219
+ const meta = { scope, store, allow, unknown, ...custom, ...metadata };
220
+ const { kind: given = kind, ...rest } = meta;
221
+ const definition = { [capitalize(given)]: rest };
222
+ const fields = mergeStruct(structDefinitionOf(a.fields), structDefinitionOf(b.fields), '');
223
+ for (const key of Object.keys(fields)) define(definition, key, fields[key]);
224
+ for (const source of [a, b]) {
225
+ for (const key in source.indexes) {
226
+ const index = source.indexes[key];
227
+ if (index.many !== undefined) continue;
228
+ if (Object.hasOwn(definition, key) && !same(definition[key], index)) {
229
+ throw conflict('The index differs between the schemas', key);
230
+ }
231
+ define(definition, key, index);
232
+ }
233
+ }
234
+ for (const key in a.options) {
235
+ const x = a.options[key];
236
+ const y = b.options[key];
237
+ if (x === null && y === null) continue;
238
+ if (x === null || y === null || x === y) definition[key] = x === null ? y : x;
239
+ else if (key === 'validate') definition[key] = compose(x, y);
240
+ else throw conflict('The functions of the schemas differ', key);
241
+ }
242
+ return new Schema(name, definition, namespaces);
243
+ } catch (error) {
244
+ if (error instanceof SchemaDefinitionError && error.code === 'ERR_MERGE_CONFLICT') {
245
+ const { field } = error;
246
+ error.field = '';
247
+ if (field) error.locate(name, field);
248
+ else atSchema(error, name);
249
+ }
250
+ throw error;
251
+ }
252
+ };
253
+
254
+ module.exports = { merge };
@@ -0,0 +1,322 @@
1
+ // A string for a pattern (`sample`): the source of a regular expression read
2
+ // into nodes once per RegExp, and a string drawn from the nodes with the
3
+ // random source of the sample. The subset is what a validation pattern is
4
+ // made of: alternatives, groups, classes, escapes and quantifiers; what
5
+ // generates no string (a lookaround, a back reference, a word boundary) is
6
+ // ERR_SAMPLE_PATTERN. Nothing here reads a schema: `sample.js` hands over
7
+ // the RegExp and the random source, and the letters of the locale are read
8
+ // at draw time, so the nodes serve every locale.
9
+ const { SchemaDefinitionError } = require('../errors.js');
10
+
11
+ const invalid = (reason) => new SchemaDefinitionError('ERR_SAMPLE_PATTERN', reason);
12
+
13
+ // A whole number in [0, max], and an element of a list, from the random
14
+ // source of a sample.
15
+ const int = (state, max) => Math.floor(state.random() * (max + 1));
16
+
17
+ const pick = (state, list) => list[int(state, list.length - 1)];
18
+
19
+ const unsupported = (what, source) => invalid(`Pattern /${source}/ cannot be sampled: ${what}`);
20
+
21
+ const code = (char) => char.codePointAt(0);
22
+
23
+ const range = (from, to) => [code(from), code(to)];
24
+
25
+ // How many times a quantifier may repeat, and how deep groups may nest: the
26
+ // bounds of what a draw allocates and of what the parser recurses into.
27
+ const MAX_REPEAT = 10_000;
28
+ const MAX_GROUPS = 64;
29
+
30
+ const CLASSES = Object.assign(Object.create(null), {
31
+ d: [range('0', '9')],
32
+ w: [range('0', '9'), range('A', 'Z'), range('a', 'z'), range('_', '_')],
33
+ s: [range(' ', ' ')],
34
+ });
35
+
36
+ // The Unicode property escapes a validation pattern uses; the letters are
37
+ // those of the locale, read when the string is drawn.
38
+ const PROPERTIES = Object.assign(Object.create(null), {
39
+ L: 'letters',
40
+ Letter: 'letters',
41
+ Lu: [range('A', 'Z')],
42
+ Ll: [range('a', 'z')],
43
+ N: [range('0', '9')],
44
+ Nd: [range('0', '9')],
45
+ });
46
+
47
+ const LETTER = /^[A-Za-z]$/;
48
+
49
+ const classNode = (set, negate, letters) => ({ set, negate, letters });
50
+
51
+ // The nodes of a pattern: { alt }, { seq }, { set, negate, letters } for a
52
+ // class (`letters`: the letters of the locale are in it), { text }, and
53
+ // { node, min, max } for a repetition.
54
+ class PatternParser {
55
+ constructor(source) {
56
+ this.source = source;
57
+ this.at = 0;
58
+ this.groups = 0;
59
+ }
60
+
61
+ fail(what) {
62
+ return unsupported(what, this.source);
63
+ }
64
+
65
+ peek() {
66
+ return this.source[this.at];
67
+ }
68
+
69
+ next() {
70
+ const char = this.source[this.at];
71
+ this.at += 1;
72
+ return char;
73
+ }
74
+
75
+ parse() {
76
+ const node = this.alternatives();
77
+ if (this.at < this.source.length) throw this.fail(`unexpected "${this.peek()}"`);
78
+ return node;
79
+ }
80
+
81
+ alternatives() {
82
+ const alt = [this.sequence()];
83
+ while (this.peek() === '|') {
84
+ this.next();
85
+ alt.push(this.sequence());
86
+ }
87
+ return alt.length === 1 ? alt[0] : { alt };
88
+ }
89
+
90
+ sequence() {
91
+ const seq = [];
92
+ while (this.at < this.source.length && this.peek() !== '|' && this.peek() !== ')') {
93
+ const atom = this.atom();
94
+ if (atom !== null) seq.push(this.quantified(atom));
95
+ }
96
+ return { seq };
97
+ }
98
+
99
+ // An atom, or null for an anchor, which generates nothing.
100
+ atom() {
101
+ const char = this.next();
102
+ if (char === '^' || char === '$') return null;
103
+ if (char === '(') return this.group();
104
+ if (char === '[') return this.set();
105
+ if (char === '.') return classNode([], false, true);
106
+ if (char === '\\') return this.escape(false);
107
+ if (char === '*' || char === '+' || char === '?') throw this.fail(`nothing to repeat`);
108
+ return { text: char };
109
+ }
110
+
111
+ group() {
112
+ this.groups += 1;
113
+ if (this.groups > MAX_GROUPS) throw this.fail(`groups nested deeper than ${MAX_GROUPS}`);
114
+ if (this.peek() === '?') {
115
+ this.next();
116
+ const kind = this.next();
117
+ if (kind === ':') {
118
+ // A non-capturing group.
119
+ } else if (kind === '<' && this.peek() !== '=' && this.peek() !== '!') {
120
+ while (this.next() !== '>') if (this.at >= this.source.length) throw this.fail('a name');
121
+ } else throw this.fail('a lookaround');
122
+ }
123
+ const node = this.alternatives();
124
+ if (this.next() !== ')') throw this.fail('an unclosed group');
125
+ this.groups -= 1;
126
+ return node;
127
+ }
128
+
129
+ // A class escape (\d, \w, \s, \p{..}) as ranges, the negated ones as
130
+ // what they are not among the letters and digits, or one character.
131
+ escape(inSet) {
132
+ const char = this.next();
133
+ if (char === undefined) throw this.fail('a trailing backslash');
134
+ const lower = char.toLowerCase();
135
+ if (CLASSES[lower] !== undefined) return classNode(CLASSES[lower], char !== lower, false);
136
+ if (lower === 'p') {
137
+ if (this.next() !== '{') throw this.fail('a property escape');
138
+ let name = '';
139
+ while (this.peek() !== '}') {
140
+ if (this.at >= this.source.length) throw this.fail('a property escape');
141
+ name += this.next();
142
+ }
143
+ this.next();
144
+ const property = PROPERTIES[name.replace(/^(General_Category|gc)=/, '')];
145
+ if (property === undefined) throw this.fail(`the property "${name}"`);
146
+ const letters = property === 'letters';
147
+ return classNode(letters ? [] : property, char !== lower, letters);
148
+ }
149
+ if (char === 'b' && !inSet) throw this.fail('a word boundary');
150
+ if (char === 'B' || char === 'k' || (char >= '1' && char <= '9')) {
151
+ throw this.fail('a back reference');
152
+ }
153
+ const named = { t: '\t', n: '\n', r: '\r', f: '\f', v: '\v', 0: '\0', b: '\b' };
154
+ if (named[char] !== undefined) return { text: named[char] };
155
+ if (char === 'x' || char === 'u') return { text: this.codePoint(char) };
156
+ if (char === 'c') {
157
+ const letter = this.next();
158
+ if (!LETTER.test(letter)) throw this.fail('a control escape');
159
+ return { text: String.fromCharCode(letter.charCodeAt(0) % 32) };
160
+ }
161
+ return { text: char };
162
+ }
163
+
164
+ codePoint(kind) {
165
+ let hex = '';
166
+ if (kind === 'u' && this.peek() === '{') {
167
+ this.next();
168
+ while (this.peek() !== '}') {
169
+ if (this.at >= this.source.length) throw this.fail('a code point escape');
170
+ hex += this.next();
171
+ }
172
+ this.next();
173
+ } else {
174
+ for (let index = 0; index < (kind === 'x' ? 2 : 4); index += 1) hex += this.next();
175
+ }
176
+ const point = Number.parseInt(hex, 16);
177
+ if (Number.isNaN(point)) throw this.fail(`the escape \\${kind}${hex}`);
178
+ return String.fromCodePoint(point);
179
+ }
180
+
181
+ // A character class: ranges, single characters and class escapes.
182
+ set() {
183
+ const negate = this.peek() === '^';
184
+ if (negate) this.next();
185
+ const set = [];
186
+ let letters = false;
187
+ while (this.peek() !== ']') {
188
+ if (this.at >= this.source.length) throw this.fail('an unclosed class');
189
+ let char = this.next();
190
+ if (char === '\\') {
191
+ const escaped = this.escape(true);
192
+ if (escaped.set !== undefined) {
193
+ if (escaped.negate) throw this.fail('a negated class escape inside a class');
194
+ if (escaped.letters) letters = true;
195
+ for (const pair of escaped.set) set.push(pair);
196
+ continue;
197
+ }
198
+ char = escaped.text;
199
+ }
200
+ if (
201
+ this.peek() === '-' &&
202
+ this.source[this.at + 1] !== ']' &&
203
+ this.at + 1 < this.source.length
204
+ ) {
205
+ this.next();
206
+ let to = this.next();
207
+ if (to === '\\') to = this.escape(true).text;
208
+ set.push([code(char), code(to)]);
209
+ } else set.push([code(char), code(char)]);
210
+ }
211
+ this.next();
212
+ return classNode(set, negate, letters);
213
+ }
214
+
215
+ // The quantifier after an atom; a lazy one generates the same.
216
+ quantified(node) {
217
+ const char = this.peek();
218
+ let min = 1;
219
+ let max = 1;
220
+ if (char === '*') {
221
+ min = 0;
222
+ max = Infinity;
223
+ } else if (char === '+') max = Infinity;
224
+ else if (char === '?') min = 0;
225
+ else if (char === '{') {
226
+ const close = this.source.indexOf('}', this.at);
227
+ const match = /^\{(\d+)(,(\d*))?\}$/.exec(this.source.slice(this.at, close + 1));
228
+ if (match === null) return node;
229
+ min = Number(match[1]);
230
+ max = match[2] === undefined ? min : match[3] === '' ? Infinity : Number(match[3]);
231
+ if (min > MAX_REPEAT || (max !== Infinity && max > MAX_REPEAT)) {
232
+ throw this.fail(`a repetition over ${MAX_REPEAT}`);
233
+ }
234
+ this.at = close;
235
+ } else return node;
236
+ this.next();
237
+ if (this.peek() === '?') this.next();
238
+ return { node, min, max };
239
+ }
240
+ }
241
+
242
+ // The fewest code points a string of the node has: a lower bound of its
243
+ // length however the length rule counts (a surrogate pair in the source is
244
+ // two text nodes and one code point).
245
+ const minLengthOf = (node) => {
246
+ if (node.text !== undefined) return /^[\uDC00-\uDFFF]$/.test(node.text) ? 0 : 1;
247
+ if (node.set !== undefined) return 1;
248
+ if (node.alt !== undefined) {
249
+ let least = Infinity;
250
+ for (const branch of node.alt) least = Math.min(least, minLengthOf(branch));
251
+ return least;
252
+ }
253
+ if (node.seq !== undefined) {
254
+ let total = 0;
255
+ for (const part of node.seq) total += minLengthOf(part);
256
+ return total;
257
+ }
258
+ return node.min * minLengthOf(node.node);
259
+ };
260
+
261
+ const PATTERNS = new WeakMap();
262
+
263
+ // The nodes of a RegExp and the minimal length of its strings, once per
264
+ // RegExp: the nodes carry nothing of a locale or a seed.
265
+ const patternOf = (pattern) => {
266
+ let entry = PATTERNS.get(pattern);
267
+ if (entry === undefined) {
268
+ const node = new PatternParser(pattern.source).parse();
269
+ entry = { node, minLength: minLengthOf(node) };
270
+ PATTERNS.set(pattern, entry);
271
+ }
272
+ return entry;
273
+ };
274
+
275
+ // The pool a negated class draws from: the letters and digits that are not
276
+ // in it; a class that excludes the letters excludes every letter of the
277
+ // pool, since \P{L} matches no letter in any locale.
278
+ const POOL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_- ';
279
+
280
+ const inSet = (set, point) => {
281
+ for (const pair of set) if (point >= pair[0] && point <= pair[1]) return true;
282
+ return false;
283
+ };
284
+
285
+ // A character of a class: one of its ranges, or a letter of the locale
286
+ // where the class holds them.
287
+ const fromSet = (state, node) => {
288
+ if (node.negate) {
289
+ const out = [];
290
+ for (const char of POOL) {
291
+ if (!inSet(node.set, code(char)) && !(node.letters && LETTER.test(char))) out.push(char);
292
+ }
293
+ if (out.length === 0) throw invalid('A class excludes every character');
294
+ return pick(state, out);
295
+ }
296
+ const choices = node.set.length + (node.letters ? 1 : 0);
297
+ if (choices === 0) throw invalid('A class allows no character');
298
+ const index = int(state, choices - 1);
299
+ if (index === node.set.length) return pick(state, state.letters);
300
+ const pair = node.set[index];
301
+ return String.fromCodePoint(pair[0] + int(state, pair[1] - pair[0]));
302
+ };
303
+
304
+ // `extra` is how many repetitions an unbounded quantifier may add: the
305
+ // length the field asks for, when it does, else a few.
306
+ const fromPattern = (state, node, extra) => {
307
+ if (node.text !== undefined) return node.text;
308
+ if (node.set !== undefined) return fromSet(state, node);
309
+ if (node.alt !== undefined) return fromPattern(state, pick(state, node.alt), extra);
310
+ if (node.seq !== undefined) {
311
+ let text = '';
312
+ for (const part of node.seq) text += fromPattern(state, part, extra);
313
+ return text;
314
+ }
315
+ const max = node.max === Infinity ? node.min + extra : node.max;
316
+ const count = node.min + int(state, max - node.min);
317
+ let text = '';
318
+ for (let index = 0; index < count; index += 1) text += fromPattern(state, node.node, extra);
319
+ return text;
320
+ };
321
+
322
+ module.exports = { int, pick, patternOf, fromPattern };