tslaws 1.1.0 → 1.2.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/coverage.js CHANGED
@@ -7,13 +7,16 @@
7
7
  import { parseGithubConfig } from "./github.js";
8
8
  import { parseSecurityConfig } from "./security/deps/config.js";
9
9
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
10
- import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';
10
+ import { dirname, extname, isAbsolute, join, posix, relative, resolve } from 'node:path';
11
11
  import ts from 'typescript';
12
12
  import { parseE2eConfig } from "./e2e.js";
13
13
  import { globMatcher } from "./globs.js";
14
14
  import { customLawFile } from "./lawFiles.js";
15
+ import { pluginExtensionNeeded } from "./pluginHooks.js";
16
+ import { transformPluginFile } from "./pluginHost.js";
15
17
  import { certifyProblem } from "./certificates.js";
16
18
  import { importMetaEnvOf, parseEnvConfig } from "./runtimeEnv.js";
19
+ import { resolveRelativeJs } from "./symbolic.js";
17
20
  import { solversProblem } from "./solvers.js";
18
21
  const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
19
22
  const configKeys = [
@@ -24,6 +27,7 @@ const configKeys = [
24
27
  'certify',
25
28
  'compilerOptions',
26
29
  'tsconfig',
30
+ 'browser',
27
31
  'e2e',
28
32
  'bundlerPlugins',
29
33
  'sandboxReads',
@@ -93,6 +97,37 @@ function checkFile(raw, source) {
93
97
  (!Array.isArray(laws) ||
94
98
  laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
95
99
  fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
100
+ if (object.browser !== undefined) {
101
+ if (!isPlain(object.browser))
102
+ return fail('"browser" must be an object');
103
+ const b = object.browser;
104
+ const allowed = ['isolation', 'headless', 'viewport', 'colorScheme', 'inBrowser', 'traceOnFailure'];
105
+ for (const key of Object.keys(b))
106
+ if (!allowed.includes(key))
107
+ fail(`"browser.${key}" is not supported; supported options are ${allowed.join(', ')}`);
108
+ if (b.isolation !== undefined && b.isolation !== 'page' && b.isolation !== 'iframe')
109
+ fail('"browser.isolation" must be "page" or "iframe"');
110
+ if (b.headless !== undefined && typeof b.headless !== 'boolean')
111
+ fail('"browser.headless" must be true or false');
112
+ if (b.inBrowser !== undefined && typeof b.inBrowser !== 'boolean')
113
+ fail('"browser.inBrowser" must be true or false');
114
+ if (b.traceOnFailure !== undefined && typeof b.traceOnFailure !== 'boolean')
115
+ fail('"browser.traceOnFailure" must be true or false');
116
+ if (b.colorScheme !== undefined &&
117
+ b.colorScheme !== 'light' &&
118
+ b.colorScheme !== 'dark' &&
119
+ b.colorScheme !== 'no-preference')
120
+ fail('"browser.colorScheme" must be "light", "dark" or "no-preference"');
121
+ if (b.viewport !== undefined) {
122
+ if (!isPlain(b.viewport))
123
+ return fail('"browser.viewport" must be { width, height } with positive numbers');
124
+ if (typeof b.viewport.width !== 'number' ||
125
+ typeof b.viewport.height !== 'number' ||
126
+ b.viewport.width < 1 ||
127
+ b.viewport.height < 1)
128
+ fail('"browser.viewport" must be { width, height } with positive numbers');
129
+ }
130
+ }
96
131
  if (object.security !== undefined)
97
132
  parseSecurityConfig(object.security);
98
133
  return object;
@@ -263,11 +298,40 @@ function loadMerged(file, cwd, root, chain, loaded) {
263
298
  delete base.standalone;
264
299
  return deepMerge(base, own);
265
300
  }
301
+ const configCache = new Map();
266
302
  /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
267
303
  export function readConfig(cwd) {
304
+ const key = resolve(cwd);
268
305
  const path = join(cwd, 'tslaws.json');
269
- if (!existsSync(path))
270
- return {};
306
+ const cached = configCache.get(key);
307
+ if (cached !== undefined) {
308
+ if (cached.files.length === 0) {
309
+ if (!existsSync(path))
310
+ return cached.config;
311
+ }
312
+ else {
313
+ let valid = true;
314
+ for (const [file, prev] of cached.files) {
315
+ try {
316
+ if (readFileSync(file, 'utf8') !== prev) {
317
+ valid = false;
318
+ break;
319
+ }
320
+ }
321
+ catch {
322
+ valid = false;
323
+ break;
324
+ }
325
+ }
326
+ if (valid)
327
+ return cached.config;
328
+ }
329
+ }
330
+ if (!existsSync(path)) {
331
+ const empty = {};
332
+ configCache.set(key, { files: [], config: empty });
333
+ return empty;
334
+ }
271
335
  const loaded = [];
272
336
  const merged = loadMerged(path, cwd, extendsRoot(cwd), [], loaded);
273
337
  let config;
@@ -282,6 +346,15 @@ export function readConfig(cwd) {
282
346
  const files = loaded.map((file) => relative(cwd, file).replaceAll('\\', '/')).join(', ');
283
347
  throw new Error(`${error.message} (merged from ${files})`);
284
348
  }
349
+ try {
350
+ const files = loaded.map((file) => [file, readFileSync(file, 'utf8')]);
351
+ if (configCache.size > 512)
352
+ configCache.clear();
353
+ configCache.set(key, { files, config });
354
+ }
355
+ catch {
356
+ // Skip caching if a file vanished mid-read.
357
+ }
285
358
  return config;
286
359
  }
287
360
  /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
@@ -340,15 +413,73 @@ function relativeRequire(expression) {
340
413
  return call.arguments[0].text;
341
414
  return undefined;
342
415
  }
343
- function parseModule(jsFile, modules) {
416
+ function resolveImport(jsFile, specifier, pluginCtx) {
417
+ const resolved = resolveRelativeJs(jsFile, specifier);
418
+ try {
419
+ if (existsSync(resolved) && statSync(resolved).isFile())
420
+ return resolved;
421
+ }
422
+ catch {
423
+ // Fall through to plugin resolution.
424
+ }
425
+ if (pluginCtx !== undefined && pluginCtx.plugins.length > 0) {
426
+ const base = resolve(dirname(jsFile), specifier);
427
+ const rel = relative(pluginCtx.outDir, base);
428
+ if (!rel.startsWith('..') && !isAbsolute(rel)) {
429
+ const src = resolve(pluginCtx.cwd, rel);
430
+ try {
431
+ if (pluginExtensionNeeded(extname(src)) && existsSync(src) && statSync(src).isFile())
432
+ return base;
433
+ }
434
+ catch {
435
+ // Ignore unreadable paths.
436
+ }
437
+ }
438
+ }
439
+ return resolved;
440
+ }
441
+ function exportedTargetName(left) {
442
+ if (!ts.isPropertyAccessExpression(left) || !ts.isIdentifier(left.expression))
443
+ return undefined;
444
+ if (left.expression.text === 'exports')
445
+ return left.name.text;
446
+ if (left.expression.text === 'module' && left.name.text === 'exports')
447
+ return 'default';
448
+ return undefined;
449
+ }
450
+ function parseModule(jsFile, modules, pluginCtx) {
344
451
  const known = modules.get(jsFile);
345
452
  if (known !== undefined)
346
453
  return known;
347
- if (!existsSync(jsFile))
454
+ let text;
455
+ if (existsSync(jsFile) && statSync(jsFile).isFile()) {
456
+ text = readFileSync(jsFile, 'utf8');
457
+ }
458
+ else if (pluginCtx !== undefined && pluginCtx.plugins.length > 0 && pluginExtensionNeeded(extname(jsFile))) {
459
+ const rel = relative(pluginCtx.outDir, jsFile);
460
+ if (rel.startsWith('..') || isAbsolute(rel))
461
+ return undefined;
462
+ const src = resolve(pluginCtx.cwd, rel);
463
+ if (!existsSync(src) || !statSync(src).isFile())
464
+ return undefined;
465
+ try {
466
+ text = transformPluginFile(src, pluginCtx.cwd, pluginCtx.plugins, 'cjs');
467
+ }
468
+ catch {
469
+ return undefined;
470
+ }
471
+ }
472
+ else {
348
473
  return undefined;
349
- const text = readFileSync(jsFile, 'utf8');
474
+ }
350
475
  const source = ts.createSourceFile(jsFile, text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
351
- const module = { nodes: new Map(), imports: new Map() };
476
+ const module = {
477
+ nodes: new Map(),
478
+ imports: new Map(),
479
+ reexports: new Map(),
480
+ localExports: new Map(),
481
+ stars: [],
482
+ };
352
483
  modules.set(jsFile, module);
353
484
  const exempt = (statement) => (ts.getLeadingCommentRanges(text, statement.getFullStart()) ?? []).some((r) => text.slice(r.pos, r.end).includes('@tslaws-exempt'));
354
485
  for (const statement of source.statements) {
@@ -366,8 +497,98 @@ function parseModule(jsFile, modules) {
366
497
  const specifier = relativeRequire(init);
367
498
  if (specifier === undefined)
368
499
  continue;
369
- const base = resolve(dirname(jsFile), specifier);
370
- module.imports.set(declaration.name.text, /\.[cm]?js$/.test(base) ? base : `${base}.js`);
500
+ module.imports.set(declaration.name.text, resolveImport(jsFile, specifier, pluginCtx));
501
+ }
502
+ }
503
+ }
504
+ const recordGetter = (exportedName, returned) => {
505
+ if (returned === undefined)
506
+ return;
507
+ if (ts.isPropertyAccessExpression(returned) && ts.isIdentifier(returned.expression)) {
508
+ const target = module.imports.get(returned.expression.text);
509
+ if (target !== undefined)
510
+ module.reexports.set(exportedName, { file: target, name: returned.name.text });
511
+ }
512
+ else if (ts.isIdentifier(returned) && exportedName !== returned.text) {
513
+ module.localExports.set(exportedName, returned.text);
514
+ }
515
+ };
516
+ for (const statement of source.statements) {
517
+ if (!ts.isExpressionStatement(statement))
518
+ continue;
519
+ if (ts.isBinaryExpression(statement.expression) &&
520
+ statement.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
521
+ const name = exportedTargetName(statement.expression.left);
522
+ if (name !== undefined) {
523
+ const rhs = statement.expression.right;
524
+ if (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs) || ts.isClassExpression(rhs))
525
+ module.nodes.set(name, { name, body: rhs, exempt: exempt(statement) });
526
+ else
527
+ recordGetter(name, rhs);
528
+ }
529
+ continue;
530
+ }
531
+ if (!ts.isCallExpression(statement.expression))
532
+ continue;
533
+ const call = statement.expression;
534
+ const callee = call.expression;
535
+ const calleeName = ts.isIdentifier(callee)
536
+ ? callee.text
537
+ : ts.isPropertyAccessExpression(callee)
538
+ ? callee.name.text
539
+ : '';
540
+ if (calleeName === '__exportStar' && call.arguments.length >= 1) {
541
+ const specifier = relativeRequire(call.arguments[0]);
542
+ if (specifier !== undefined)
543
+ module.stars.push(resolveImport(jsFile, specifier, pluginCtx));
544
+ }
545
+ else if (calleeName === '__reExport' && call.arguments.length >= 2) {
546
+ const specifier = relativeRequire(call.arguments[1]);
547
+ if (specifier !== undefined)
548
+ module.stars.push(resolveImport(jsFile, specifier, pluginCtx));
549
+ }
550
+ else if (calleeName === '__export' &&
551
+ call.arguments.length === 2 &&
552
+ ts.isObjectLiteralExpression(call.arguments[1])) {
553
+ for (const prop of call.arguments[1].properties) {
554
+ if (!ts.isPropertyAssignment(prop))
555
+ continue;
556
+ const exportedName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : undefined;
557
+ if (exportedName === undefined)
558
+ continue;
559
+ const getter = prop.initializer;
560
+ if (!ts.isArrowFunction(getter) && !ts.isFunctionExpression(getter))
561
+ continue;
562
+ const returned = ts.isBlock(getter.body)
563
+ ? getter.body.statements.length === 1 && ts.isReturnStatement(getter.body.statements[0])
564
+ ? getter.body.statements[0].expression
565
+ : undefined
566
+ : getter.body;
567
+ recordGetter(exportedName, returned);
568
+ }
569
+ }
570
+ else if (ts.isPropertyAccessExpression(callee) &&
571
+ ts.isIdentifier(callee.expression) &&
572
+ callee.expression.text === 'Object' &&
573
+ callee.name.text === 'defineProperty' &&
574
+ call.arguments.length === 3 &&
575
+ ts.isIdentifier(call.arguments[0]) &&
576
+ call.arguments[0].text === 'exports' &&
577
+ ts.isStringLiteral(call.arguments[1]) &&
578
+ ts.isObjectLiteralExpression(call.arguments[2])) {
579
+ const exportedName = call.arguments[1].text;
580
+ const getter = call.arguments[2].properties.find((p) => ts.isPropertyAssignment(p) &&
581
+ ts.isIdentifier(p.name) &&
582
+ p.name.text === 'get' &&
583
+ (ts.isFunctionExpression(p.initializer) || ts.isArrowFunction(p.initializer)));
584
+ if (getter !== undefined) {
585
+ const fn = getter.initializer;
586
+ const returned = ts.isBlock(fn.body)
587
+ ? fn.body.statements.length === 1 && ts.isReturnStatement(fn.body.statements[0])
588
+ ? fn.body.statements[0].expression
589
+ : undefined
590
+ : fn.body;
591
+ recordGetter(exportedName, returned);
371
592
  }
372
593
  }
373
594
  }
@@ -405,6 +626,8 @@ const sourceOf = (outDir, cwd, js) => {
405
626
  return candidates.find((c) => existsSync(join(cwd, c))) ?? candidates[0];
406
627
  };
407
628
  export function analyzeCoverage(input) {
629
+ const plugins = (readConfig(input.cwd).bundlerPlugins ?? []).map((p) => resolve(input.cwd, p));
630
+ const pluginCtx = plugins.length > 0 ? { cwd: input.cwd, outDir: input.outDir, plugins } : undefined;
408
631
  const modules = new Map();
409
632
  const key = (js, name) => `${js}::${name}`;
410
633
  const edges = (js, node) => {
@@ -416,7 +639,7 @@ export function analyzeCoverage(input) {
416
639
  if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression)) {
417
640
  const target = module.imports.get(n.expression.text);
418
641
  if (target !== undefined) {
419
- parseModule(target, modules);
642
+ parseModule(target, modules, pluginCtx);
420
643
  out.push(key(target, n.name.text));
421
644
  }
422
645
  }
@@ -430,7 +653,7 @@ export function analyzeCoverage(input) {
430
653
  const queue = [];
431
654
  const lawJs = input.lawFiles.map((f) => jsOf(input.outDir, f));
432
655
  for (const js of lawJs) {
433
- const module = parseModule(js, modules);
656
+ const module = parseModule(js, modules, pluginCtx);
434
657
  if (module === undefined)
435
658
  continue;
436
659
  for (const node of module.nodes.values())
@@ -442,12 +665,35 @@ export function analyzeCoverage(input) {
442
665
  continue;
443
666
  reached.add(current);
444
667
  const [js, name] = current.split('::');
445
- const module = parseModule(js, modules);
446
- const node = module?.nodes.get(name);
668
+ const module = parseModule(js, modules, pluginCtx);
669
+ if (module === undefined)
670
+ continue;
671
+ const node = module.nodes.get(name);
447
672
  if (node !== undefined)
448
673
  for (const next of edges(js, node))
449
674
  if (!reached.has(next))
450
675
  queue.push(next);
676
+ const local = module.localExports.get(name);
677
+ if (local !== undefined) {
678
+ const localNode = module.nodes.get(local);
679
+ if (localNode !== undefined)
680
+ for (const next of edges(js, localNode))
681
+ if (!reached.has(next))
682
+ queue.push(next);
683
+ }
684
+ const reexport = module.reexports.get(name);
685
+ if (reexport !== undefined) {
686
+ parseModule(reexport.file, modules, pluginCtx);
687
+ const next = key(reexport.file, reexport.name);
688
+ if (!reached.has(next))
689
+ queue.push(next);
690
+ }
691
+ for (const star of module.stars) {
692
+ parseModule(star, modules, pluginCtx);
693
+ const next = key(star, name);
694
+ if (!reached.has(next))
695
+ queue.push(next);
696
+ }
451
697
  }
452
698
  // The modules in scope: the cover globs, or every project module the laws import.
453
699
  const scope = new Set();
@@ -455,13 +701,18 @@ export function analyzeCoverage(input) {
455
701
  for (const f of input.coverFiles)
456
702
  scope.add(jsOf(input.outDir, f));
457
703
  else {
704
+ const visited = new Set();
458
705
  const visit = (js) => {
459
- const module = parseModule(js, modules);
706
+ if (visited.has(js))
707
+ return;
708
+ visited.add(js);
709
+ const module = parseModule(js, modules, pluginCtx);
460
710
  if (module === undefined)
461
711
  return;
462
- for (const target of module.imports.values()) {
463
- if (!scope.has(target) && !lawJs.includes(target)) {
464
- scope.add(target);
712
+ for (const target of [...module.imports.values(), ...module.stars]) {
713
+ if (!lawJs.includes(target)) {
714
+ if (!pluginExtensionNeeded(extname(target)))
715
+ scope.add(target);
465
716
  visit(target);
466
717
  }
467
718
  }
@@ -472,7 +723,7 @@ export function analyzeCoverage(input) {
472
723
  const uncovered = [];
473
724
  const exempt = [];
474
725
  for (const js of scope) {
475
- const module = parseModule(js, modules);
726
+ const module = parseModule(js, modules, pluginCtx);
476
727
  if (module === undefined)
477
728
  continue;
478
729
  const file = sourceOf(input.outDir, input.cwd, js);
package/dist/derived.d.ts CHANGED
@@ -4,5 +4,7 @@ import type { ManifestLaw } from './types.ts';
4
4
  export interface DerivedStore {
5
5
  law(law: ManifestLaw, compute: () => LawTypes): LawTypes;
6
6
  coverage(compute: () => CoverageReport): CoverageReport;
7
+ /** Writes any new entries to disk once, instead of rewriting derived.json on every law. */
8
+ flush(): void;
7
9
  }
8
10
  export declare function derivedStore(cwd: string, key: string | undefined): DerivedStore;
package/dist/derived.js CHANGED
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { arbitraryOf } from "./plan.js";
6
6
  export function derivedStore(cwd, key) {
7
7
  if (key === undefined)
8
- return { law: (_law, compute) => compute(), coverage: (compute) => compute() };
8
+ return { law: (_law, compute) => compute(), coverage: (compute) => compute(), flush: () => undefined };
9
9
  const path = join(cwd, '.tslaws', 'derived.json');
10
10
  let stored = { key, laws: {} };
11
11
  try {
@@ -16,7 +16,11 @@ export function derivedStore(cwd, key) {
16
16
  catch {
17
17
  // Nothing kept yet.
18
18
  }
19
- const save = () => {
19
+ let dirty = false;
20
+ const flush = () => {
21
+ if (!dirty)
22
+ return;
23
+ dirty = false;
20
24
  try {
21
25
  mkdirSync(join(cwd, '.tslaws'), { recursive: true });
22
26
  writeFileSync(path, JSON.stringify(stored));
@@ -37,7 +41,7 @@ export function derivedStore(cwd, key) {
37
41
  };
38
42
  const types = compute();
39
43
  stored.laws[id] = { plans: types.plans, shapes: types.shapes.map((shape) => shape ?? null) };
40
- save();
44
+ dirty = true;
41
45
  return types;
42
46
  },
43
47
  coverage(compute) {
@@ -45,8 +49,9 @@ export function derivedStore(cwd, key) {
45
49
  return stored.coverage;
46
50
  const report = compute();
47
51
  stored.coverage = report;
48
- save();
52
+ dirty = true;
49
53
  return report;
50
54
  },
55
+ flush,
51
56
  };
52
57
  }
@@ -2,6 +2,10 @@ import type * as fc from 'fast-check';
2
2
  import ts from 'typescript';
3
3
  import { type Plan } from './plan.ts';
4
4
  export { toWire, UnsupportedType, wireKey } from './plan.ts';
5
+ /** Extracts `[min, max]` literal bounds from `intRange<Lo, Hi>`. */
6
+ export declare function readIntRangeBounds(checker: ts.TypeChecker, type: ts.Type): [number, number] | undefined;
7
+ /** Extracts the element type `T` from `nonEmpty<T>`. */
8
+ export declare function readNonEmptyElement(checker: ts.TypeChecker, type: ts.Type): ts.Type | undefined;
5
9
  export declare class GeneratorFactory {
6
10
  private readonly checker;
7
11
  private readonly active;
@@ -10,7 +14,7 @@ export declare class GeneratorFactory {
10
14
  of(type: ts.Type): fc.Arbitrary<unknown>;
11
15
  plan(type: ts.Type, depth?: number): Plan;
12
16
  private structural;
13
- /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
17
+ /** A type with a registered generator or built-in refinement type (`int`, `nat`, `posInt`, `nonZeroInt`, `intRange`, `uint8`/`16`/`32`, `int32`, `nonEmpty`, `nonEmptyString`, `asciiString`, `finite`). */
14
18
  private registered;
15
19
  private union;
16
20
  private template;
@@ -3,6 +3,37 @@ import { arbitraryRegistry } from "./api.js";
3
3
  import { registerSecurityGenerators, securityTypeNames } from "./security/generators.js";
4
4
  import { arbitraryOf, UnsupportedType } from "./plan.js";
5
5
  export { toWire, UnsupportedType, wireKey } from "./plan.js";
6
+ /** Extracts `[min, max]` literal bounds from `intRange<Lo, Hi>`. */
7
+ export function readIntRangeBounds(checker, type) {
8
+ const args = type.aliasTypeArguments;
9
+ if (args !== undefined && args.length === 2 && args[0].isNumberLiteral() && args[1].isNumberLiteral()) {
10
+ const lo = args[0].value;
11
+ const hi = args[1].value;
12
+ if (Number.isSafeInteger(lo) && Number.isSafeInteger(hi) && lo <= hi)
13
+ return [lo, hi];
14
+ }
15
+ const minProp = type.getProperty('__tslawsMin');
16
+ const maxProp = type.getProperty('__tslawsMax');
17
+ if (minProp === undefined || maxProp === undefined)
18
+ return undefined;
19
+ const minType = checker.getTypeOfSymbol(minProp);
20
+ const maxType = checker.getTypeOfSymbol(maxProp);
21
+ if (minType.isNumberLiteral() && maxType.isNumberLiteral() && minType.value <= maxType.value)
22
+ return [minType.value, maxType.value];
23
+ return undefined;
24
+ }
25
+ /** Extracts the element type `T` from `nonEmpty<T>`. */
26
+ export function readNonEmptyElement(checker, type) {
27
+ if (type.aliasTypeArguments !== undefined && type.aliasTypeArguments.length === 1)
28
+ return type.aliasTypeArguments[0];
29
+ if (type.flags & ts.TypeFlags.Intersection) {
30
+ for (const part of type.types) {
31
+ if (checker.isArrayType(part))
32
+ return checker.getTypeArguments(part)[0];
33
+ }
34
+ }
35
+ return undefined;
36
+ }
6
37
  /** Whether a type is declared in tslaws' own security module, not by a project that reuses the name. */
7
38
  function declaredBySecurity(symbol) {
8
39
  return (symbol.declarations ?? []).some((d) => /\/tslaws\/(dist|src)\/security\//.test(d.getSourceFile().fileName));
@@ -70,19 +101,34 @@ export class GeneratorFactory {
70
101
  return { k: 'object' };
71
102
  throw new UnsupportedType(`no generator for type ${this.checker.typeToString(type)}`);
72
103
  }
73
- /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
104
+ /** A type with a registered generator or built-in refinement type (`int`, `nat`, `posInt`, `nonZeroInt`, `intRange`, `uint8`/`16`/`32`, `int32`, `nonEmpty`, `nonEmptyString`, `asciiString`, `finite`). */
74
105
  registered(type, depth) {
75
106
  const symbol = type.aliasSymbol ?? type.getSymbol();
76
- if (symbol === undefined)
107
+ const name = symbol?.getName();
108
+ // Parameterized & aliased range refinement types (`intRange<Lo, Hi>`, `uint8`, `uint16`, `uint32`, `int32`, or user aliases).
109
+ const bounds = readIntRangeBounds(this.checker, type);
110
+ if (bounds !== undefined)
111
+ return { k: 'intRange', min: bounds[0], max: bounds[1] };
112
+ if (name === 'nonEmpty') {
113
+ const elem = readNonEmptyElement(this.checker, type);
114
+ if (elem !== undefined)
115
+ return { k: 'nonEmpty', of: this.plan(elem, depth + 1) };
116
+ }
117
+ if (symbol === undefined || name === undefined)
77
118
  return undefined;
78
- const name = symbol.getName();
79
119
  // The payload types of tslaws/security have their generators even when the law has not been loaded yet.
80
120
  const security = securityTypeNames.has(name) && declaredBySecurity(symbol);
81
121
  if (security && !arbitraryRegistry().has(name))
82
122
  registerSecurityGenerators();
83
123
  if (!arbitraryRegistry().has(name))
84
124
  return undefined;
85
- if (name === 'int')
125
+ if (name === 'int' ||
126
+ name === 'nat' ||
127
+ name === 'posInt' ||
128
+ name === 'nonZeroInt' ||
129
+ name === 'asciiString' ||
130
+ name === 'nonEmptyString' ||
131
+ name === 'finite')
86
132
  return { k: 'named', name };
87
133
  const tag = security ? { security: true } : {};
88
134
  // What to generate if the registration is not there where the plan is used (a worker has only the built-in ones).
package/dist/lawHost.d.ts CHANGED
@@ -26,6 +26,8 @@ export type HostRequest = {
26
26
  plans: Plan[];
27
27
  options: CheckOptions;
28
28
  env: ImportMetaEnv;
29
+ /** Identifies the build; unchanged keys reuse already-loaded compiled modules instead of evicting require.cache per law. */
30
+ buildKey?: string;
29
31
  } | {
30
32
  type: 'holds';
31
33
  token: string;
package/dist/lawHost.js CHANGED
@@ -16,6 +16,7 @@ const guard = new Guard();
16
16
  let secret;
17
17
  const transformed = new Map();
18
18
  const loaded = new Map();
19
+ const loadedBuildKeys = new Map();
19
20
  let guarded = false;
20
21
  // The channel is the only way out. Keep it, and take it from the code that runs here so it cannot answer for the host.
21
22
  // `process.send` calls `this._send`, which lockDown hides, so the inner function is kept as well.
@@ -114,28 +115,40 @@ function lookup(kind, file) {
114
115
  throw new Error(prepared.error);
115
116
  return prepared.code;
116
117
  }
117
- function load(outDir, law, env, fresh) {
118
+ function load(outDir, law, env, fresh, buildKey) {
118
119
  const key = `${outDir}\0${law.file}\0${law.symbol ?? law.name}`;
120
+ const sameBuild = buildKey !== undefined && loadedBuildKeys.get(outDir) === buildKey;
119
121
  const known = loaded.get(key);
120
- if (!fresh && known !== undefined)
122
+ if ((!fresh || sameBuild) && known !== undefined) {
123
+ setImportMetaEnv(env);
121
124
  return known;
125
+ }
122
126
  setImportMetaEnv(env);
123
- installLoaderHooks();
124
- useTransforms({
125
- source: (file) => lookup('ts', file),
126
- plugin: (file, _cwd, _plugins, format) => lookup(format, file),
127
- });
128
- installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
129
- // Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
130
- loadResolver();
131
- // From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
132
- if (!guarded) {
133
- guarded = true;
134
- installGuard(guard);
135
- lockDown();
127
+ if (!sameBuild) {
128
+ installLoaderHooks();
129
+ useTransforms({
130
+ source: (file) => lookup('ts', file),
131
+ plugin: (file, _cwd, _plugins, format) => lookup(format, file),
132
+ });
133
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
134
+ // Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
135
+ loadResolver();
136
+ // From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
137
+ if (!guarded) {
138
+ guarded = true;
139
+ installGuard(guard);
140
+ lockDown();
141
+ }
142
+ // The process outlives a check, and the code may have been recompiled since the last one.
143
+ evictLoaded(require.cache, outDir);
144
+ for (const k of loaded.keys())
145
+ if (k.startsWith(`${outDir}\0`))
146
+ loaded.delete(k);
147
+ if (buildKey !== undefined)
148
+ loadedBuildKeys.set(outDir, buildKey);
149
+ else
150
+ loadedBuildKeys.delete(outDir);
136
151
  }
137
- // The process outlives a check, and the code may have been recompiled since the last one.
138
- evictLoaded(require.cache, outDir);
139
152
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
140
153
  if (typeof fn !== 'function')
141
154
  throw new Error('compiled module does not export the law');
@@ -169,7 +182,7 @@ process.on('message', async (request) => {
169
182
  const { id } = request;
170
183
  let fn;
171
184
  try {
172
- fn = load(request.outDir, request.law, request.env, request.type === 'run');
185
+ fn = load(request.outDir, request.law, request.env, request.type === 'run', request.type === 'run' ? request.buildKey : undefined);
173
186
  }
174
187
  catch (error) {
175
188
  send({ id, error: message(error), phase: 'load' });
@@ -0,0 +1,11 @@
1
+ /** Resolves the native `z3` binary path if installed and enabled, else undefined. */
2
+ export declare function nativeZ3Path(env?: NodeJS.ProcessEnv): string | undefined;
3
+ /** Fingerprint of the active Z3 backend for proof cache keys. */
4
+ export declare function z3Fingerprint(env?: NodeJS.ProcessEnv): string;
5
+ /** Terminates idle native Z3 processes (e.g. after a solver crash). */
6
+ export declare function closeNativeZ3(): void;
7
+ /** Runs one SMT-LIB query against a pooled native Z3 process; rejects with `Unsupported` on timeout. */
8
+ export declare function solveNative(binary: string, query: string, values: string, timeoutMs: number, onTimeout: () => Error): Promise<{
9
+ out: string;
10
+ vals: string;
11
+ }>;