tslaws 1.0.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.
Files changed (51) hide show
  1. package/README.md +183 -187
  2. package/dist/api.d.ts +86 -0
  3. package/dist/api.js +78 -0
  4. package/dist/badge.d.ts +111 -0
  5. package/dist/badge.js +288 -0
  6. package/dist/browser.d.ts +5 -2
  7. package/dist/browser.js +403 -173
  8. package/dist/browserApi.d.ts +305 -0
  9. package/dist/browserApi.js +456 -0
  10. package/dist/browserServer.d.ts +13 -0
  11. package/dist/browserServer.js +406 -0
  12. package/dist/certificates.js +50 -28
  13. package/dist/chc.d.ts +13 -1
  14. package/dist/chc.js +40 -8
  15. package/dist/check.js +64 -36
  16. package/dist/cli.d.ts +16 -0
  17. package/dist/cli.js +78 -1
  18. package/dist/compile.js +46 -5
  19. package/dist/coverage.d.ts +17 -0
  20. package/dist/coverage.js +297 -24
  21. package/dist/derived.d.ts +2 -0
  22. package/dist/derived.js +9 -4
  23. package/dist/generators.d.ts +5 -1
  24. package/dist/generators.js +50 -4
  25. package/dist/githubCli.js +88 -15
  26. package/dist/isolate.d.ts +5 -0
  27. package/dist/isolate.js +1 -1
  28. package/dist/lawHost.d.ts +2 -0
  29. package/dist/lawHost.js +32 -21
  30. package/dist/lawRuntime.d.ts +6 -0
  31. package/dist/lawRuntime.js +86 -7
  32. package/dist/nativeZ3.d.ts +11 -0
  33. package/dist/nativeZ3.js +162 -0
  34. package/dist/plan.d.ts +7 -0
  35. package/dist/plan.js +11 -0
  36. package/dist/pluginHooks.d.ts +4 -0
  37. package/dist/pluginHooks.js +13 -4
  38. package/dist/proofCache.d.ts +24 -0
  39. package/dist/proofCache.js +135 -0
  40. package/dist/property.d.ts +2 -2
  41. package/dist/property.js +33 -8
  42. package/dist/propertyWorker.js +14 -8
  43. package/dist/sandbox.d.ts +1 -1
  44. package/dist/sandbox.js +48 -8
  45. package/dist/seal.js +47 -8
  46. package/dist/smt.d.ts +16 -2
  47. package/dist/smt.js +241 -31
  48. package/dist/symbolic.d.ts +38 -3
  49. package/dist/symbolic.js +504 -47
  50. package/dist/types.d.ts +9 -0
  51. package/package.json +7 -7
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. */
@@ -316,15 +389,97 @@ export function coverFiles(cwd, globs) {
316
389
  walk(cwd);
317
390
  return found.sort();
318
391
  }
319
- function parseModule(jsFile, modules) {
392
+ /** The interop helpers a compiler wraps around `require` for an ES module import: tsc's, tslib's and esbuild's. */
393
+ const interopHelpers = new Set(['__importStar', '__importDefault', '__toESM']);
394
+ /**
395
+ * The relative path in `require('./x')`, or in that call wrapped, possibly more than once, in an interop helper such as
396
+ * `__importStar(require('./x'))`. Undefined for anything else.
397
+ */
398
+ function relativeRequire(expression) {
399
+ let call = expression;
400
+ while (ts.isCallExpression(call) && call.arguments.length >= 1) {
401
+ const callee = call.expression;
402
+ const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : '';
403
+ if (!interopHelpers.has(name))
404
+ break;
405
+ call = call.arguments[0];
406
+ }
407
+ if (ts.isCallExpression(call) &&
408
+ ts.isIdentifier(call.expression) &&
409
+ call.expression.text === 'require' &&
410
+ call.arguments.length === 1 &&
411
+ ts.isStringLiteral(call.arguments[0]) &&
412
+ call.arguments[0].text.startsWith('.'))
413
+ return call.arguments[0].text;
414
+ return undefined;
415
+ }
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) {
320
451
  const known = modules.get(jsFile);
321
452
  if (known !== undefined)
322
453
  return known;
323
- 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 {
324
473
  return undefined;
325
- const text = readFileSync(jsFile, 'utf8');
474
+ }
326
475
  const source = ts.createSourceFile(jsFile, text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
327
- 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
+ };
328
483
  modules.set(jsFile, module);
329
484
  const exempt = (statement) => (ts.getLeadingCommentRanges(text, statement.getFullStart()) ?? []).some((r) => text.slice(r.pos, r.end).includes('@tslaws-exempt'));
330
485
  for (const statement of source.statements) {
@@ -338,14 +493,102 @@ function parseModule(jsFile, modules) {
338
493
  const init = declaration.initializer;
339
494
  if (ts.isArrowFunction(init) || ts.isFunctionExpression(init) || ts.isClassExpression(init))
340
495
  module.nodes.set(declaration.name.text, { name: declaration.name.text, body: init, exempt: exempt(statement) });
341
- else if (ts.isCallExpression(init) &&
342
- ts.isIdentifier(init.expression) &&
343
- init.expression.text === 'require' &&
344
- init.arguments.length === 1 &&
345
- ts.isStringLiteral(init.arguments[0]) &&
346
- init.arguments[0].text.startsWith('.')) {
347
- const base = resolve(dirname(jsFile), init.arguments[0].text);
348
- module.imports.set(declaration.name.text, /\.[cm]?js$/.test(base) ? base : `${base}.js`);
496
+ else {
497
+ const specifier = relativeRequire(init);
498
+ if (specifier === undefined)
499
+ continue;
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);
349
592
  }
350
593
  }
351
594
  }
@@ -383,6 +626,8 @@ const sourceOf = (outDir, cwd, js) => {
383
626
  return candidates.find((c) => existsSync(join(cwd, c))) ?? candidates[0];
384
627
  };
385
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;
386
631
  const modules = new Map();
387
632
  const key = (js, name) => `${js}::${name}`;
388
633
  const edges = (js, node) => {
@@ -394,7 +639,7 @@ export function analyzeCoverage(input) {
394
639
  if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression)) {
395
640
  const target = module.imports.get(n.expression.text);
396
641
  if (target !== undefined) {
397
- parseModule(target, modules);
642
+ parseModule(target, modules, pluginCtx);
398
643
  out.push(key(target, n.name.text));
399
644
  }
400
645
  }
@@ -408,7 +653,7 @@ export function analyzeCoverage(input) {
408
653
  const queue = [];
409
654
  const lawJs = input.lawFiles.map((f) => jsOf(input.outDir, f));
410
655
  for (const js of lawJs) {
411
- const module = parseModule(js, modules);
656
+ const module = parseModule(js, modules, pluginCtx);
412
657
  if (module === undefined)
413
658
  continue;
414
659
  for (const node of module.nodes.values())
@@ -420,12 +665,35 @@ export function analyzeCoverage(input) {
420
665
  continue;
421
666
  reached.add(current);
422
667
  const [js, name] = current.split('::');
423
- const module = parseModule(js, modules);
424
- 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);
425
672
  if (node !== undefined)
426
673
  for (const next of edges(js, node))
427
674
  if (!reached.has(next))
428
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
+ }
429
697
  }
430
698
  // The modules in scope: the cover globs, or every project module the laws import.
431
699
  const scope = new Set();
@@ -433,13 +701,18 @@ export function analyzeCoverage(input) {
433
701
  for (const f of input.coverFiles)
434
702
  scope.add(jsOf(input.outDir, f));
435
703
  else {
704
+ const visited = new Set();
436
705
  const visit = (js) => {
437
- const module = parseModule(js, modules);
706
+ if (visited.has(js))
707
+ return;
708
+ visited.add(js);
709
+ const module = parseModule(js, modules, pluginCtx);
438
710
  if (module === undefined)
439
711
  return;
440
- for (const target of module.imports.values()) {
441
- if (!scope.has(target) && !lawJs.includes(target)) {
442
- 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);
443
716
  visit(target);
444
717
  }
445
718
  }
@@ -450,7 +723,7 @@ export function analyzeCoverage(input) {
450
723
  const uncovered = [];
451
724
  const exempt = [];
452
725
  for (const js of scope) {
453
- const module = parseModule(js, modules);
726
+ const module = parseModule(js, modules, pluginCtx);
454
727
  if (module === undefined)
455
728
  continue;
456
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).