@atscript/typescript 0.1.110 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_plugin = require('./plugin-mzTvme4k.cjs');
3
- require('./json-schema-B3iAqkGQ.cjs');
2
+ const require_plugin = require('./plugin-oUSsb3Ri.cjs');
3
+ const require_unique_name = require('./unique-name-xWd9uO-k.cjs');
4
4
  let path = require("path");
5
5
  path = require_plugin.__toESM(path);
6
6
  let _atscript_core = require("@atscript/core");
@@ -34,6 +34,80 @@ let fs = require("fs");
34
34
  if (existing !== file.content) (0, fs.writeFileSync)(target, file.content);
35
35
  }
36
36
  }
37
+ /**
38
+ * Reference validator for parity tests: a subclass never takes the allocation-free pre-check
39
+ * (interpreted or compiled) nor the literal-union shortcut, so it always runs the full
40
+ * error-collecting walk.
41
+ */ var WalkValidator = class extends require_unique_name.Validator {};
42
+ /** A seeded random number generator (mulberry32) returning values in `[0, 1)`. */ function rng(seed) {
43
+ return () => {
44
+ seed = seed + 1831565813 | 0;
45
+ let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
46
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
47
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
48
+ };
49
+ }
50
+ /**
51
+ * A random schema of two modules (`d0.as`, `d1.as`, importing each other) dense in what makes
52
+ * merges large: unions inside intersections, intersections of types sharing prop names (so
53
+ * their props merge too), self and mutual references, arrays of intersections, and mutating /
54
+ * alias `annotate` blocks through them. Not every one is valid (a path may name no prop).
55
+ */ function denseSchema(seed) {
56
+ const r = rng(seed);
57
+ const pick = (list) => list[Math.floor(r() * list.length)];
58
+ const count = 3 + Math.floor(r() * 4);
59
+ const names = Array.from({ length: count }, (_, i) => `S${i}`);
60
+ const PROPS = [
61
+ "d",
62
+ "e",
63
+ "f"
64
+ ];
65
+ const prim = () => pick([
66
+ "string",
67
+ "number",
68
+ "boolean",
69
+ "string.email",
70
+ "null"
71
+ ]);
72
+ const wrap = (t) => /[&|]/.test(t) ? `(${t})` : t;
73
+ const many = (depth, op) => Array.from({ length: 2 + Math.floor(r() * 2) }, () => wrap(expr(depth + 1))).join(` ${op} `);
74
+ const obj = (depth) => {
75
+ return `{ ${[...new Set(Array.from({ length: 1 + Math.floor(r() * 2) }, () => pick(PROPS)))].map((p) => `${p}${r() < .3 ? "?" : ""}: ${expr(depth + 1)}`).join(", ")} }`;
76
+ };
77
+ function expr(depth) {
78
+ const k = r();
79
+ if (depth > 3 || k < .3) return r() < .8 ? pick(names) : prim();
80
+ if (k < .5) return obj(depth);
81
+ if (k < .7) return many(depth, "|");
82
+ if (k < .92) return many(depth, "&");
83
+ return `${wrap(expr(depth + 1))}[]`;
84
+ }
85
+ const files = [[], []];
86
+ const declared = [];
87
+ names.forEach((name, i) => {
88
+ const props = [...new Set(Array.from({ length: 1 + Math.floor(r() * 3) }, () => pick(PROPS)))];
89
+ declared.push(props);
90
+ const body = props.map((p) => ` ${p}${r() < .3 ? "?" : ""}: ${expr(0)}`).join("\n");
91
+ files[i % 2].push(`export interface ${name} {\n${body}\n}`);
92
+ });
93
+ for (let i = 0; i < 2; i++) files[i].push(`export type T${i} = ${many(1, "&")}`);
94
+ /** An `annotate` block of a random type: a prop it declares, or (sometimes) one below it. */ const annotate = (head, label) => {
95
+ const target = Math.floor(r() * count);
96
+ const path$2 = [pick(declared[target]), ...r() < .4 ? [pick(PROPS)] : []].join(".");
97
+ return `${head.replace("%", names[target])} {\n @meta.label "${label}"\n ${path$2}\n}`;
98
+ };
99
+ files[0].push(annotate("annotate %", "m"));
100
+ files[1].push(annotate("export annotate % as A1", "a"));
101
+ const out = {};
102
+ for (let i = 0; i < 2; i++) {
103
+ const imported = names.filter((_, j) => j % 2 !== i);
104
+ out[`d${i}.as`] = `import { ${imported.join(", ")} } from './d${1 - i}'\n\n${files[i].join("\n\n")}\n`;
105
+ }
106
+ return out;
107
+ }
37
108
 
38
109
  //#endregion
39
- exports.prepareFixtures = prepareFixtures;
110
+ exports.WalkValidator = WalkValidator;
111
+ exports.denseSchema = denseSchema;
112
+ exports.prepareFixtures = prepareFixtures;
113
+ exports.rng = rng;
@@ -33,7 +33,7 @@ interface TTsPluginOptions {
33
33
  * `validate()` then runs the type's compiled check instead of the interpreted pre-check
34
34
  * (results and errors are identical; only speed differs). The check binds to the live
35
35
  * type on first use and re-binds after mutations made through `annotate()`, the
36
- * metadata / props `Map` methods, the `defineAnnotatedType()` handle and `cloneRefProp()`.
36
+ * metadata / props `Map` methods and the `defineAnnotatedType()` handle.
37
37
  * Raw writes need `invalidateCompiledValidators()`: property writes (`node.optional = …`,
38
38
  * `type.items.push(…)`, …) and in-place edits of annotation values (mutating a constraint
39
39
  * object, pushing onto an `@expect.pattern` array directly) — the check keeps the values
@@ -44,13 +44,309 @@ interface TTsPluginOptions {
44
44
  * before.
45
45
  *
46
46
  * Adds code to every `.as.js`: meant for backend builds — leave it off for bundles
47
- * shipped to browsers (the code is CSP-safe: no `eval` / `new Function`). The
48
- * `'js:compiled'` / `'js:interpreted'` render formats force it on / off per render.
47
+ * shipped to browsers (the code is CSP-safe: no `eval` / `new Function`).
48
+ *
49
+ * Off (the default), only types annotated with `@emit.compiledValidator` get a compiled
50
+ * check. The `'js:compiled'` render format compiles every type; `'js:interpreted'`
51
+ * compiles none, ignoring `@emit.compiledValidator` (see {@link JS_INTERPRETED_FORMAT}).
49
52
  * *(default: `false`)*
50
53
  */
51
54
  compileValidators?: boolean;
52
55
  }
53
56
 
57
+ /** Type definition for union, intersection, or tuple types. */
58
+ interface TAtscriptTypeComplex<DataType = unknown> {
59
+ kind: 'union' | 'intersection' | 'tuple';
60
+ items: TAtscriptAnnotatedType[];
61
+ tags: Set<AtscriptPrimitiveTags>;
62
+ /** @internal phantom — carries the DataType at the type level, never set at runtime */
63
+ __dataType?: DataType;
64
+ }
65
+ /** Type definition for array types. */
66
+ interface TAtscriptTypeArray<DataType = unknown[]> {
67
+ kind: 'array';
68
+ of: TAtscriptAnnotatedType;
69
+ tags: Set<AtscriptPrimitiveTags>;
70
+ /** @internal phantom — carries the DataType at the type level, never set at runtime */
71
+ __dataType?: DataType;
72
+ }
73
+ /** Type definition for object types with named and pattern-matched properties. */
74
+ interface TAtscriptTypeObject<K extends string = string, DataType = Record<K, unknown>> {
75
+ kind: 'object';
76
+ props: Map<K, TAtscriptAnnotatedType>;
77
+ propsPatterns: Array<{
78
+ pattern: RegExp;
79
+ def: TAtscriptAnnotatedType;
80
+ }>;
81
+ tags: Set<AtscriptPrimitiveTags>;
82
+ /** @internal phantom — carries the DataType at the type level, never set at runtime */
83
+ __dataType?: DataType;
84
+ }
85
+ /** Type definition for primitive/literal types (string, number, boolean, null, etc.). */
86
+ interface TAtscriptTypeFinal<DataType = unknown> {
87
+ kind: '';
88
+ /**
89
+ * design type
90
+ */
91
+ designType: 'string' | 'number' | 'boolean' | 'undefined' | 'null' | 'object' | 'any' | 'never' | 'phantom' | 'decimal';
92
+ /**
93
+ * value for literals
94
+ */
95
+ value?: string | number | boolean;
96
+ tags: Set<AtscriptPrimitiveTags>;
97
+ /** @internal phantom — carries the DataType at the type level, never set at runtime */
98
+ __dataType?: DataType;
99
+ }
100
+ /**
101
+ * Extract DataType from a type def's phantom generic
102
+ */
103
+ type InferDataType<T> = T extends {
104
+ __dataType?: infer D;
105
+ } ? D : unknown;
106
+ /**
107
+ * Extract the DataType from a {@link TAtscriptAnnotatedType}.
108
+ *
109
+ * Resolves the phantom `__dataType` carried by the type definition.
110
+ * When `__dataType` is `unknown` (unset), falls back to the constructor
111
+ * instance type if `T` is also a class (i.e. a generated interface).
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * import type { TAtscriptDataType } from '@atscript/typescript/utils'
116
+ * import MyInterface from './my-interface.as'
117
+ *
118
+ * type Data = TAtscriptDataType<typeof MyInterface>
119
+ * ```
120
+ */
121
+ type TAtscriptDataType<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType> = T extends {
122
+ type: {
123
+ __dataType?: infer D;
124
+ };
125
+ } ? unknown extends D ? T extends new (...args: any[]) => infer I ? I : unknown : D : unknown;
126
+ /** Union of all possible type definition shapes. */
127
+ type TAtscriptTypeDef<DataType = unknown> = TAtscriptTypeComplex<DataType> | TAtscriptTypeFinal<DataType> | TAtscriptTypeArray<DataType> | TAtscriptTypeObject<string, DataType>;
128
+ /**
129
+ * Core annotated type — wraps a type definition with metadata and a validator factory.
130
+ *
131
+ * Generated `.as` files produce classes/namespaces that conform to this interface.
132
+ * The `DataType` phantom generic carries the TypeScript data shape for type-safe validation.
133
+ *
134
+ * @typeParam T - The underlying type definition (e.g. {@link TAtscriptTypeObject}).
135
+ * @typeParam DataType - The TypeScript type the validated data narrows to (auto-inferred from `T`).
136
+ */
137
+ interface TAtscriptAnnotatedType<T extends TAtscriptTypeDef = TAtscriptTypeDef, DataType = InferDataType<T>> {
138
+ __is_atscript_annotated_type: true;
139
+ type: T;
140
+ validator(opts?: Partial<TValidatorOptions>): Validator<this, DataType>;
141
+ metadata: TMetadataMap<AtscriptMetadata>;
142
+ optional?: boolean;
143
+ id?: string;
144
+ ref?: {
145
+ type: () => TAtscriptAnnotatedType;
146
+ field: string;
147
+ };
148
+ }
149
+ /**
150
+ * Atscript Metadata Map with typed setters/getters
151
+ */
152
+ interface TMetadataMap<O extends object> extends Map<keyof O, O[keyof O]> {
153
+ get<K extends keyof O>(key: K): O[K] | undefined;
154
+ get(key: string): unknown;
155
+ set<K extends keyof O>(key: K, value: O[K]): this;
156
+ has<K extends keyof O>(key: K): boolean;
157
+ has(key: string): boolean;
158
+ }
159
+
160
+ interface TError {
161
+ path: string;
162
+ message: string;
163
+ details?: TError[];
164
+ }
165
+ /**
166
+ * A plugin function that can intercept validation.
167
+ *
168
+ * Return `true` to accept the value, `false` to reject it,
169
+ * or `undefined` to fall through to the default validation.
170
+ */
171
+ type TValidatorPlugin = (ctx: TValidatorPluginContext, def: TAtscriptAnnotatedType, value: any) => boolean | undefined;
172
+ /** Options for configuring {@link Validator} behavior. */
173
+ interface TValidatorOptions {
174
+ partial: boolean | 'deep' | ((type: TAtscriptAnnotatedType<TAtscriptTypeObject>, path: string) => boolean);
175
+ replace?: (type: TAtscriptAnnotatedType, path: string) => TAtscriptAnnotatedType;
176
+ plugins: TValidatorPlugin[];
177
+ unknownProps: 'strip' | 'ignore' | 'error';
178
+ errorLimit: number;
179
+ skipList?: Set<string>;
180
+ }
181
+ /** Context exposed to {@link TValidatorPlugin} functions. */
182
+ interface TValidatorPluginContext {
183
+ opts: Validator<any>['opts'];
184
+ /**
185
+ * Validates `value` against `def` at the current path (errors go to the current level). With
186
+ * `unknownProps: 'strip'`, a call that returns `false` strips nothing: the keys it recorded are
187
+ * dropped, as for a rejected union branch, so trying alternatives (`a || b`) strips what the
188
+ * union `a | b` would.
189
+ */
190
+ validateAnnotatedType: Validator<any>['validateAnnotatedType'];
191
+ error: Validator<any>['error'];
192
+ path: Validator<any>['path'];
193
+ /**
194
+ * The type the validator was created for — the root of the walk, as passed to the
195
+ * constructor (before `replace`). The plugin's `def` argument is the node visited now.
196
+ */
197
+ readonly root: TAtscriptAnnotatedType;
198
+ context: unknown;
199
+ }
200
+ /**
201
+ * Validates values against an {@link TAtscriptAnnotatedType} definition.
202
+ *
203
+ * `DataType` is automatically inferred from the type definition's phantom generic,
204
+ * enabling the {@link validate} method to act as a type guard.
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * // From a generated interface class:
209
+ * const validator = new Validator(MyInterface)
210
+ * if (validator.validate(data, true)) {
211
+ * data // narrowed to MyInterface
212
+ * }
213
+ *
214
+ * // Or use the built-in factory:
215
+ * MyInterface.validator().validate(data)
216
+ * ```
217
+ *
218
+ * @typeParam T - The annotated type definition.
219
+ * @typeParam DataType - The TypeScript type that `validate` narrows to (auto-inferred).
220
+ */
221
+ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>> {
222
+ protected readonly def: T;
223
+ protected opts: TValidatorOptions;
224
+ protected hasPlugins: boolean;
225
+ protected hasReplace: boolean;
226
+ private replaceCache?;
227
+ constructor(def: T, opts?: Partial<TValidatorOptions>);
228
+ /** Validation errors collected during the last {@link validate} call. */
229
+ errors: TError[];
230
+ protected stackErrors: Array<TError[] | null>;
231
+ protected pathSegments: string[];
232
+ protected depth: number;
233
+ protected limitExceeded: boolean;
234
+ protected context: unknown;
235
+ /**
236
+ * The unions over objects this call decided inside union branches (value → outcomes). A union
237
+ * nested in its own branches, many branches each, is reached again with the same value and path
238
+ * from every branch of every union above it — (branches)^(depth) work. The memo is made once
239
+ * the call has wasted {@link WASTE_BEFORE_MEMO} union branches (failed after branches of nested
240
+ * unions over objects failed) since the outermost union, as in the pre-check — ordinary walks
241
+ * never make it. It decides each such union once, with the same result and the same error object
242
+ * (both depend only on these, the options and the input, which the walk never changes), and
243
+ * records the same strips again.
244
+ */
245
+ private unionMemo?;
246
+ /** Union branches being checked (`> 0`: inside a union branch). */
247
+ private unionDepth;
248
+ /** Failed branches of unions over objects inside union branches (see `unionMemo`). */
249
+ private nestedFailures;
250
+ /** Wasted union branches since the outermost union was entered (see `unionMemo`). */
251
+ private wasted;
252
+ /**
253
+ * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
254
+ * order the objects completed, then in key order. A rejected union branch, pattern property
255
+ * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
256
+ * call passes (`performStrips`).
257
+ */
258
+ private strips;
259
+ protected buildPath(): string;
260
+ protected push(name: string): void;
261
+ protected pop(saveErrors: boolean): TError[] | null | undefined;
262
+ protected clear(): void;
263
+ protected error(message: string, path?: string, details?: TError[]): TError;
264
+ /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */
265
+ private report;
266
+ protected throw(): void;
267
+ /**
268
+ * Validates a value against the type definition.
269
+ *
270
+ * Acts as a TypeScript type guard — when it returns `true`, the value
271
+ * is narrowed to `DataType`.
272
+ *
273
+ * @param value - The value to validate.
274
+ * @param safe - If `true`, returns `false` on failure instead of throwing.
275
+ * @returns `true` if the value matches the type definition.
276
+ * @throws {ValidatorError} When validation fails and `safe` is not `true`.
277
+ */
278
+ validate<TT = DataType>(value: any, safe?: boolean, context?: unknown): value is TT;
279
+ /**
280
+ * Plain `Validator` without plugins / `replace`: eligible for the allocation-free
281
+ * shortcuts. Subclasses may override the protected `validate*` hooks, so they
282
+ * always take the full walk. (A getter, not a constructor-set field: validators are
283
+ * often built per call, so construction stays as cheap as before.)
284
+ */
285
+ private get shortcuts();
286
+ /** Validates `value` against `def` (after `replace`, `optional` and the plugins). */
287
+ protected validateSafe(def: TAtscriptAnnotatedType, value: any): boolean;
288
+ /**
289
+ * What {@link validateSafe} decides of `def` (replaced) before its own validation: an
290
+ * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
291
+ */
292
+ private preCheck;
293
+ /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */
294
+ private pluginCtx?;
295
+ /**
296
+ * The plugins' view of this validator: its state read live; `validateAnnotatedType` drops the
297
+ * strips a failed call recorded (a failed validation at any level strips nothing).
298
+ */
299
+ private pluginContext;
300
+ /** `def` as the `replace` option replaces it at the current path (memoized per node). */
301
+ private replaced;
302
+ protected get path(): string;
303
+ /** The type this validator was created for (see {@link TValidatorPluginContext.root}). */
304
+ protected get root(): T;
305
+ protected validateAnnotatedType(def: TAtscriptAnnotatedType, value: any): boolean;
306
+ protected validateUnion(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
307
+ /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */
308
+ private wasteBranch;
309
+ /** The outcome this call recorded for union `def` over `value` at `path` (see `unionMemo`). */
310
+ private decided;
311
+ /**
312
+ * Records the outcome of union `def` over `value` at `path`, entered with `kept` strips (the
313
+ * ones after them are its own).
314
+ */
315
+ private decide;
316
+ /**
317
+ * Constraints annotated on the union itself (`@expect.min 0` on `number | null`)
318
+ * apply to the non-null value that matched `branch`, on top of the branch's own.
319
+ * A literal branch (an enum value) is exempt: its value is fixed.
320
+ */
321
+ protected validateUnionConstraints(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, branch: TAtscriptAnnotatedType, value: any): boolean;
322
+ /** Every member must pass, each on its own (JSON Schema `allOf`). */
323
+ protected validateIntersection(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
324
+ /**
325
+ * An unknown key (`unknownProps`): 'error' reports it, 'strip' adds it to the keys to strip
326
+ * (returned; recorded in `strips` once the object passed).
327
+ */
328
+ private unknownKey;
329
+ /** The `skipList` keys of the object at the current path. */
330
+ private skipListHere;
331
+ protected validateTuple(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
332
+ protected validateArray(def: TAtscriptAnnotatedType<TAtscriptTypeArray>, value: any): boolean;
333
+ /** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */
334
+ protected validateArrayConstraints(meta: TMetadataMap<AtscriptMetadata>, value: any[], of?: TAtscriptAnnotatedType): boolean;
335
+ protected validateObject(def: TAtscriptAnnotatedType<TAtscriptTypeObject>, value: any): boolean;
336
+ protected validatePrimitive(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: any): boolean;
337
+ protected validateString(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: string): boolean;
338
+ /** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */
339
+ protected validateStringConstraints(meta: TMetadataMap<AtscriptMetadata>, value: string): boolean;
340
+ protected validateNumber(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: number): boolean;
341
+ /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */
342
+ protected validateNumberConstraints(meta: TMetadataMap<AtscriptMetadata>, value: number): boolean;
343
+ /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */
344
+ private numberBoundFailed;
345
+ protected validateBoolean(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: boolean): boolean;
346
+ /** `@meta.required` check for a boolean value (must be `true`). */
347
+ protected validateBooleanConstraints(meta: TMetadataMap<AtscriptMetadata>, value: boolean): boolean;
348
+ }
349
+
54
350
  interface PrepareFixturesOptions {
55
351
  /** Absolute directory containing the `.as` fixture files. */
56
352
  rootDir: string;
@@ -74,6 +370,22 @@ interface PrepareFixturesOptions {
74
370
  * don't touch mtimes of up-to-date artifacts.
75
371
  */
76
372
  declare function prepareFixtures(options: PrepareFixturesOptions): Promise<void>;
373
+ /**
374
+ * Reference validator for parity tests: a subclass never takes the allocation-free pre-check
375
+ * (interpreted or compiled) nor the literal-union shortcut, so it always runs the full
376
+ * error-collecting walk.
377
+ */
378
+ declare class WalkValidator extends Validator {
379
+ }
380
+ /** A seeded random number generator (mulberry32) returning values in `[0, 1)`. */
381
+ declare function rng(seed: number): () => number;
382
+ /**
383
+ * A random schema of two modules (`d0.as`, `d1.as`, importing each other) dense in what makes
384
+ * merges large: unions inside intersections, intersections of types sharing prop names (so
385
+ * their props merge too), self and mutual references, arrays of intersections, and mutating /
386
+ * alias `annotate` blocks through them. Not every one is valid (a path may name no prop).
387
+ */
388
+ declare function denseSchema(seed: number): Record<string, string>;
77
389
 
78
- export { prepareFixtures };
390
+ export { WalkValidator, denseSchema, prepareFixtures, rng };
79
391
  export type { PrepareFixturesOptions };
@@ -1,5 +1,5 @@
1
- import { r as tsPlugin } from "./plugin-DpzE8aJr.mjs";
2
- import "./json-schema-BG1SEcjI.mjs";
1
+ import { r as tsPlugin } from "./plugin-DhesoKce.mjs";
2
+ import { E as Validator } from "./unique-name-hg1CyPIs.mjs";
3
3
  import path from "path";
4
4
  import { build } from "@atscript/core";
5
5
  import { readFileSync, writeFileSync } from "fs";
@@ -32,6 +32,77 @@ import { readFileSync, writeFileSync } from "fs";
32
32
  if (existing !== file.content) writeFileSync(target, file.content);
33
33
  }
34
34
  }
35
+ /**
36
+ * Reference validator for parity tests: a subclass never takes the allocation-free pre-check
37
+ * (interpreted or compiled) nor the literal-union shortcut, so it always runs the full
38
+ * error-collecting walk.
39
+ */ var WalkValidator = class extends Validator {};
40
+ /** A seeded random number generator (mulberry32) returning values in `[0, 1)`. */ function rng(seed) {
41
+ return () => {
42
+ seed = seed + 1831565813 | 0;
43
+ let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
44
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
45
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
46
+ };
47
+ }
48
+ /**
49
+ * A random schema of two modules (`d0.as`, `d1.as`, importing each other) dense in what makes
50
+ * merges large: unions inside intersections, intersections of types sharing prop names (so
51
+ * their props merge too), self and mutual references, arrays of intersections, and mutating /
52
+ * alias `annotate` blocks through them. Not every one is valid (a path may name no prop).
53
+ */ function denseSchema(seed) {
54
+ const r = rng(seed);
55
+ const pick = (list) => list[Math.floor(r() * list.length)];
56
+ const count = 3 + Math.floor(r() * 4);
57
+ const names = Array.from({ length: count }, (_, i) => `S${i}`);
58
+ const PROPS = [
59
+ "d",
60
+ "e",
61
+ "f"
62
+ ];
63
+ const prim = () => pick([
64
+ "string",
65
+ "number",
66
+ "boolean",
67
+ "string.email",
68
+ "null"
69
+ ]);
70
+ const wrap = (t) => /[&|]/.test(t) ? `(${t})` : t;
71
+ const many = (depth, op) => Array.from({ length: 2 + Math.floor(r() * 2) }, () => wrap(expr(depth + 1))).join(` ${op} `);
72
+ const obj = (depth) => {
73
+ return `{ ${[...new Set(Array.from({ length: 1 + Math.floor(r() * 2) }, () => pick(PROPS)))].map((p) => `${p}${r() < .3 ? "?" : ""}: ${expr(depth + 1)}`).join(", ")} }`;
74
+ };
75
+ function expr(depth) {
76
+ const k = r();
77
+ if (depth > 3 || k < .3) return r() < .8 ? pick(names) : prim();
78
+ if (k < .5) return obj(depth);
79
+ if (k < .7) return many(depth, "|");
80
+ if (k < .92) return many(depth, "&");
81
+ return `${wrap(expr(depth + 1))}[]`;
82
+ }
83
+ const files = [[], []];
84
+ const declared = [];
85
+ names.forEach((name, i) => {
86
+ const props = [...new Set(Array.from({ length: 1 + Math.floor(r() * 3) }, () => pick(PROPS)))];
87
+ declared.push(props);
88
+ const body = props.map((p) => ` ${p}${r() < .3 ? "?" : ""}: ${expr(0)}`).join("\n");
89
+ files[i % 2].push(`export interface ${name} {\n${body}\n}`);
90
+ });
91
+ for (let i = 0; i < 2; i++) files[i].push(`export type T${i} = ${many(1, "&")}`);
92
+ /** An `annotate` block of a random type: a prop it declares, or (sometimes) one below it. */ const annotate = (head, label) => {
93
+ const target = Math.floor(r() * count);
94
+ const path = [pick(declared[target]), ...r() < .4 ? [pick(PROPS)] : []].join(".");
95
+ return `${head.replace("%", names[target])} {\n @meta.label "${label}"\n ${path}\n}`;
96
+ };
97
+ files[0].push(annotate("annotate %", "m"));
98
+ files[1].push(annotate("export annotate % as A1", "a"));
99
+ const out = {};
100
+ for (let i = 0; i < 2; i++) {
101
+ const imported = names.filter((_, j) => j % 2 !== i);
102
+ out[`d${i}.as`] = `import { ${imported.join(", ")} } from './d${1 - i}'\n\n${files[i].join("\n\n")}\n`;
103
+ }
104
+ return out;
105
+ }
35
106
 
36
107
  //#endregion
37
- export { prepareFixtures };
108
+ export { WalkValidator, denseSchema, prepareFixtures, rng };