tslaws 1.1.0 → 1.3.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/check.js CHANGED
@@ -7,6 +7,7 @@ import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, wa
7
7
  import { analyzeCoverage, coverFiles, lawEnv, readConfig } from "./coverage.js";
8
8
  import { parseGithubConfig } from "./github.js";
9
9
  import { derivedStore } from "./derived.js";
10
+ import { openProofCache } from "./proofCache.js";
10
11
  import { budget, configureJobs } from "./pool.js";
11
12
  import { hostConfig, LawLoadError, Sandbox, useSandbox, warnE2e, warmSandbox } from "./sandbox.js";
12
13
  import { bindingOf, certificateFailure, hashOf, noCertificate, recordOf, staleRecord, verifyRecord, writeRecords, readRecords, } from "./certificates.js";
@@ -21,6 +22,7 @@ import { inProposals } from "./lawFiles.js";
21
22
  import { classifyLawFile } from "./lawKinds.js";
22
23
  import { normaliseProposal } from "./proposals.js";
23
24
  import { declarationOf, exercisesOf, markFailing, Sources } from "./exercises.js";
25
+ let checkSequence = 0;
24
26
  /** Runs at most `limit` tasks at once. The CPU limit is the process-wide budget (pool.ts); this holds the single page. */
25
27
  class Semaphore {
26
28
  free;
@@ -293,6 +295,10 @@ export async function check(options, enforceLock) {
293
295
  : undefined;
294
296
  // What the type checker works out is kept with the build it came from, so an unchanged project skips the checker.
295
297
  const derived = derivedStore(options.cwd, built.key);
298
+ const proofCache = openProofCache(options.cwd);
299
+ // Identifies this check invocation for pooled sandbox/worker processes so laws in the same check reuse loaded modules
300
+ // while a subsequent `check()` cleanly evicts stale module state and plugin-loaded assets once.
301
+ const runBuildKey = `${built.key ?? 'nobuild'}:${++checkSequence}`;
296
302
  let programOf;
297
303
  const program = () => (programOf ??=
298
304
  built.program ?? ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions)));
@@ -370,15 +376,27 @@ export async function check(options, enforceLock) {
370
376
  // One property run of the law: in the sandbox, or in a worker of this process when it is off or the law is end to end.
371
377
  const execute = async (runOptions) => {
372
378
  if (!sandboxed || e2e)
373
- return runLawGuarded(built.outDir, law, runOptions, types.plans);
379
+ return runLawGuarded(built.outDir, law, runOptions, types.plans, runBuildKey);
374
380
  if (sandbox === undefined)
375
381
  throw new Error('the law sandbox is on but was not set up');
376
- const ran = await sandbox.run(built.outDir, law, runOptions, types.plans);
382
+ const ran = await sandbox.run(built.outDir, law, runOptions, types.plans, runBuildKey);
377
383
  if (ran === 'timeout')
378
384
  return ran;
379
385
  isAsync = ran.async;
380
386
  return ran.outcome;
381
387
  };
388
+ const holds = (inputs) => {
389
+ if (sandboxed && sandbox === undefined)
390
+ return false;
391
+ if (sandbox !== undefined)
392
+ return sandbox.holds(built.outDir, law, inputs, limitMs);
393
+ try {
394
+ return fn(...inputs) !== false;
395
+ }
396
+ catch (error) {
397
+ return isDiscard(error);
398
+ }
399
+ };
382
400
  let details;
383
401
  // Counterexamples found before are tried first.
384
402
  let lawOptions = options.noRegressions
@@ -393,6 +411,32 @@ export async function check(options, enforceLock) {
393
411
  if (!options.explicit?.includes('property-timeout'))
394
412
  limitMs = e2eConfig?.timeoutMs ?? 120000;
395
413
  }
414
+ // For provable sync node laws, start SMT proving concurrently with fast-check when extra budget slots are available.
415
+ const looksAsync = isAsync || /\basync\s*(?:law|\(|function|[A-Za-z_$])/.test(law.text);
416
+ const canProve = !browser && !e2e && !options.noProve && !looksAsync;
417
+ const startProof = () => proveLaw({
418
+ law,
419
+ shapes: types.shapes,
420
+ jsFile: jsPath(built.outDir, law.file),
421
+ bound: options.bound,
422
+ timeoutMs: options.proofTimeoutMs,
423
+ holds,
424
+ solvers: config.solvers,
425
+ cache: proofCache,
426
+ certify: certifyMode === false
427
+ ? undefined
428
+ : { mode: certifyMode, dir: join(options.cwd, '.tslaws', 'certificates'), root: options.cwd },
429
+ });
430
+ let earlyProof;
431
+ let releaseProofSlot;
432
+ if (canProve) {
433
+ releaseProofSlot = budget.tryHold();
434
+ if (releaseProofSlot !== undefined) {
435
+ earlyProof = startProof().finally(() => releaseProofSlot?.());
436
+ // Prevent unhandled rejection if the property run fails or throws before we await `earlyProof`.
437
+ earlyProof.catch(() => undefined);
438
+ }
439
+ }
396
440
  try {
397
441
  details = e2e
398
442
  ? await runE2eLaw({ file: law.file, name: law.name, fn: fn, generators: types.generators }, lawOptions, await ensureServer(e2eConfig ?? {}, options.cwd), limitMs)
@@ -403,6 +447,7 @@ export async function check(options, enforceLock) {
403
447
  symbol: law.symbol,
404
448
  jsFile: jsPath(built.outDir, law.file),
405
449
  generators: types.generators,
450
+ plans: types.plans,
406
451
  }, lawOptions)
407
452
  : await execute(lawOptions);
408
453
  }
@@ -458,30 +503,7 @@ export async function check(options, enforceLock) {
458
503
  });
459
504
  return;
460
505
  }
461
- const holds = (inputs) => {
462
- if (sandboxed && sandbox === undefined)
463
- return false;
464
- if (sandbox !== undefined)
465
- return sandbox.holds(built.outDir, law, inputs, limitMs);
466
- try {
467
- return fn(...inputs) !== false;
468
- }
469
- catch (error) {
470
- return isDiscard(error);
471
- }
472
- };
473
- const proof = await proveLaw({
474
- law,
475
- shapes: types.shapes,
476
- jsFile: jsPath(built.outDir, law.file),
477
- bound: options.bound,
478
- timeoutMs: options.proofTimeoutMs,
479
- holds,
480
- solvers: config.solvers,
481
- certify: certifyMode === false
482
- ? undefined
483
- : { mode: certifyMode, dir: join(options.cwd, '.tslaws', 'certificates'), root: options.cwd },
484
- });
506
+ const proof = await (earlyProof ?? startProof());
485
507
  const certified = (certificate) => certificate === undefined ? {} : { certificate };
486
508
  const assumed = (list) => (list.length > 0 ? { assumptions: list } : {});
487
509
  if (proof.kind === 'proved' || proof.kind === 'bounded') {
@@ -577,9 +599,10 @@ export async function check(options, enforceLock) {
577
599
  nextToFlush += 1;
578
600
  }
579
601
  };
580
- // Every law takes a slot of the process-wide CPU budget, and what it starts (a proof, a solver, a law process) runs on
581
- // that slot. Browser and end-to-end laws also share one page and one server, so they queue for it first.
582
- const page = new Semaphore(1);
602
+ // Every law takes a slot of the process-wide CPU budget, and what it starts (a proof, a solver, a law process,
603
+ // or an isolated BrowserContext) runs on that slot. Browser laws run in parallel across isolated contexts (no
604
+ // single-page bottleneck); end-to-end laws share one app dev server and serialize unless configured otherwise.
605
+ const e2eGate = new Semaphore(1);
583
606
  await Promise.all(laws.map(async (law, index) => {
584
607
  const skipped = !selected(law) || blocked.has(lawKey(law.file, law.name));
585
608
  if (skipped) {
@@ -588,7 +611,7 @@ export async function check(options, enforceLock) {
588
611
  return;
589
612
  }
590
613
  const inSlot = () => budget.run(() => runOne(law, index));
591
- await (verdictOf(law.file).kind !== 'node' ? page.run(inSlot) : inSlot());
614
+ await (verdictOf(law.file).kind === 'e2e' ? e2eGate.run(inSlot) : inSlot());
592
615
  }));
593
616
  if (enforceLock && options.onlyKeys === undefined) {
594
617
  const coverage = derived.coverage(() => analyzeCoverage({
@@ -624,6 +647,8 @@ export async function check(options, enforceLock) {
624
647
  });
625
648
  }
626
649
  }
650
+ derived.flush();
651
+ proofCache.flush();
627
652
  await closeBrowser();
628
653
  await stopServer();
629
654
  // Records for `tslaws accept` to consider; a law that did not end proved or bounded keeps no certificate.
package/dist/cli.js CHANGED
@@ -31,7 +31,7 @@ import { securityUsage } from "./security/cli.js";
31
31
  import { plural } from "./plural.js";
32
32
  import { configureJobs } from "./pool.js";
33
33
  const usage = `tslaws init [--force] scaffold tslaws.json, .gitignore, AGENTS.md, Claude Code hooks and a starter law (never writes the lock)
34
- tslaws check [files...] [--reporter text|json|junit|github|ndjson] [--law NAME[,NAME]] [--json] [--summary] [--watch] [--runs N] [--seed N] [--no-prove] [--certify] [--require-certify] [--no-regressions] [--no-sandbox] [--allow-e2e] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--jobs N] [--proposed] [--compiler PATH] [--browser chromium|firefox|webkit]
34
+ tslaws check [files...] [--reporter text|json|junit|github|ndjson] [--law NAME[,NAME]] [--json] [--summary] [--watch] [--runs N] [--seed N] [--no-prove] [--certify] [--require-certify] [--no-regressions] [--no-sandbox] [--allow-e2e] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--jobs N] [--proposed] [--compiler PATH] [--browser chromium|firefox|webkit] [--browser-mode page|iframe] [--headed]
35
35
  tslaws ui [files...] [--port N] [--no-open] [--tab] open a dashboard of the laws in its own desktop window (--tab: a browser tab): tree, filters, search, source, live reruns on save
36
36
  tslaws mutate [files...] [--max N] [--seed N] [--runs N] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--jobs N] [--browser ENGINE] [--no-sandbox] [--allow-e2e] [--json] mutation-test the laws: mutate covered code, report mutants no law kills
37
37
  tslaws regressions [list|clear] show or delete the stored counterexamples (.tslaws/regressions); check replays them first, --no-regressions skips them
@@ -43,7 +43,7 @@ tslaws propose <file.ts> [--from PATH] write a proposal into .tslaws/proposals
43
43
  tslaws promote <proposal> [--to PATH] [--yes] move a proposal from .tslaws/proposals/ into the tree at a path you confirm (people only: needs a terminal; run accept afterwards). It prints the imports and helper code it would add and asks first, and refuses an import of a file outside the project, under .tslaws/, node_modules or .git, or git-ignored; --yes adds it without asking (it is still printed; it never lets promote run without a terminal). In-tree *.proposed.laws.ts files (the usual proposals) promote with --all or by name
44
44
  tslaws list [--json] the laws files and proposals of the project: the level each runs at (from its name, or its imports with levels: imports) and whether it is accepted, unaccepted or proposed (reads files and the lock; runs nothing)
45
45
  tslaws github report|command|merge|verify accept laws on GitHub: flag and run each proposal on a pull request, record /tslaws accept comments, and write tsc-laws.lock on merge or on demand (workflow_dispatch) (CI only; see "github" in tslaws.json)
46
- tslaws badge [files...] [--out DIR] [--report FILE] [--repo OWNER/NAME] [--branch NAME] [--link URL] [--certify] write the shields.io endpoint badges "laws: N proved" and "certificates: N verified" (badge-laws.json and badge-certificates.json) into DIR (default badges) from a check, or from the check --json output in FILE, and print the markdown that shows them. When a law is certified it also writes DIR/README.md, a page of the laws, their status and their proof files (copied to DIR/certificates). The URLs name the GitHub repository from --repo, $GITHUB_REPOSITORY or the origin remote (else OWNER/REPO), and both badges link to --link (default: that page, or tsc-laws.lock on the branch when no law is certified; the branch defaults to main). Commit the files; see docs/certificates.md
46
+ tslaws badge [files...] [--out DIR] [--report FILE] [--repo OWNER/NAME] [--branch NAME] [--link URL] [--certify] write the shields.io endpoint badges, each a breakdown by category such as "laws: 7 proved · 1 tested" and "certificates: 7 certified · 1 not certifiable" (badge-laws.json and badge-certificates.json) into DIR (default badges) from a check, or from the check --json output in FILE, and print the markdown that shows them. When a law is certified it also writes DIR/README.md, a page of the laws, their status and their proof files (copied to DIR/certificates). The URLs name the GitHub repository from --repo, $GITHUB_REPOSITORY or the origin remote (else OWNER/REPO), and both badges link to --link (default: that page, or tsc-laws.lock on the branch when no law is certified; the branch defaults to main). Commit the files; see docs/certificates.md
47
47
  tslaws mcp [--compiler PATH] serve check, check_proposed, explain and propose as Model Context Protocol tools on stdio (cannot accept, promote or touch the lock)
48
48
  ${migrateUsage}
49
49
  ${securityUsage}
@@ -81,6 +81,7 @@ function parse(args) {
81
81
  'property-timeout',
82
82
  'jobs',
83
83
  'browser',
84
+ 'browser-mode',
84
85
  'port',
85
86
  'reporter',
86
87
  'law',
@@ -245,6 +246,15 @@ function options(cwd, flags, chosen) {
245
246
  browser: flags.has('browser')
246
247
  ? resolveEngine(String(flags.get('browser')))
247
248
  : undefined,
249
+ browserIsolation: flags.has('browser-mode')
250
+ ? (() => {
251
+ const mode = String(flags.get('browser-mode'));
252
+ if (mode !== 'page' && mode !== 'iframe')
253
+ throw new Error(`unknown --browser-mode '${mode}': use page or iframe`);
254
+ return mode;
255
+ })()
256
+ : undefined,
257
+ headed: flags.has('headed') ? true : undefined,
248
258
  };
249
259
  }
250
260
  /** Files outside the directories `skip` (project-relative paths of projects nested in this one). */
package/dist/compile.js CHANGED
@@ -214,6 +214,9 @@ const awaitStub = (file) => `throw new Error(${JSON.stringify(`${file}: ${awaitA
214
214
  * words is left alone. Returns the new text and whether the module waits at its top level.
215
215
  */
216
216
  function rewriteImportMeta(text, file, source) {
217
+ // Fast path: skip parsing when the emitted file mentions neither `import.meta` nor `await`.
218
+ if (!text.includes('import.meta') && !/\bawait\b/.test(text))
219
+ return { text, awaits: false };
217
220
  const parsed = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, false, ts.ScriptKind.JS);
218
221
  const edits = [];
219
222
  const env = `globalThis.${importMetaEnvGlobal}`;
@@ -344,9 +347,20 @@ function compile(compiler, files, cwd, resolution) {
344
347
  ...extra,
345
348
  ];
346
349
  const args = ['--ignoreConfig', ...flags, ...files];
347
- // What the options say is part of what was built.
348
- const keyArgs = [...args, JSON.stringify(resolution?.options ?? null)];
349
- const reused = builtin ? cachedBuild(keyArgs, files, cwd, outDir) : undefined;
350
+ // What the options say is part of what was built (including the compiler binary stamp for native builds).
351
+ const compilerStamp = builtin
352
+ ? 'builtin'
353
+ : (() => {
354
+ try {
355
+ const st = statSync(compiler);
356
+ return `${compiler}:${st.size}:${st.mtimeMs}`;
357
+ }
358
+ catch {
359
+ return compiler;
360
+ }
361
+ })();
362
+ const keyArgs = [...args, JSON.stringify(resolution?.options ?? null), compilerStamp];
363
+ const reused = cachedBuild(keyArgs, files, cwd, outDir);
350
364
  if (reused !== undefined)
351
365
  return reused;
352
366
  rmSync(outDir, { recursive: true, force: true });
@@ -402,11 +416,34 @@ function compile(compiler, files, cwd, resolution) {
402
416
  again(argsFor(used, [envTypes]));
403
417
  const problems = lowering ? lowerEmittedModules(outDir, { outDir, root }) : [];
404
418
  // The project's own files sit where they do under the root, so its output is that deep in `outDir`.
405
- return {
419
+ const result = {
406
420
  outDir: join(outDir, relative(root, cwd)),
407
421
  diagnostics: [output().trim(), ...problems].filter((part) => part !== '').join('\n'),
408
422
  ok: run.status === 0 && problems.length === 0,
409
423
  };
424
+ if (result.ok) {
425
+ // Collect source files corresponding to emitted JS files so native builds can also reuse the build cache.
426
+ const emittedSources = new Set(files.map((f) => resolve(cwd, f)));
427
+ const collect = (dir) => {
428
+ if (!existsSync(dir))
429
+ return;
430
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
431
+ const p = join(dir, entry.name);
432
+ if (entry.isDirectory())
433
+ collect(p);
434
+ else if (/\.m?js$/.test(entry.name)) {
435
+ const src = sourceOfOutput(p, outDir, root);
436
+ if (existsSync(src))
437
+ emittedSources.add(src);
438
+ }
439
+ }
440
+ };
441
+ collect(outDir);
442
+ if (resolution !== undefined && existsSync(resolution.file))
443
+ emittedSources.add(resolution.file);
444
+ saveBuildCache(keyArgs, files, cwd, result, [...emittedSources]);
445
+ }
446
+ return result;
410
447
  }
411
448
  /** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
412
449
  function typeRootsOf(cwd) {
@@ -3,6 +3,21 @@ import { type E2eConfig } from './e2e.ts';
3
3
  import { type CertifyMode } from './certificates.ts';
4
4
  import { type ImportMetaEnv } from './runtimeEnv.ts';
5
5
  import { type SolverName } from './solvers.ts';
6
+ export interface BrowserConfig {
7
+ /** 'page' (default): top-level BrowserContext + Page (`window.top === window.self`). 'iframe': isolated iframe inside runner page. */
8
+ isolation?: 'page' | 'iframe';
9
+ /** Run browser laws headless (default true). Set false or pass `--headed` for interactive debugging. */
10
+ headless?: boolean;
11
+ viewport?: {
12
+ width: number;
13
+ height: number;
14
+ };
15
+ colorScheme?: 'light' | 'dark' | 'no-preference';
16
+ /** Run fast-check property loops inside the browser page to eliminate per-input IPC (default true). */
17
+ inBrowser?: boolean;
18
+ /** Record a Playwright trace into `.tslaws/traces/` when a browser law fails (default false). */
19
+ traceOnFailure?: boolean;
20
+ }
6
21
  export interface CoverageConfig {
7
22
  cover?: string[];
8
23
  /** Compiler options the runner passes to tsc; see `compilerFlags` in compile.ts for the supported keys. */
@@ -12,6 +27,8 @@ export interface CoverageConfig {
12
27
  * tslaws.json, or `false` for none. Default: the nearest tsconfig.json above the project. See tsconfigResolve.ts.
13
28
  */
14
29
  tsconfig?: string | false;
30
+ /** Browser component laws configuration: isolation mode (`page` or `iframe`), viewport, Vite middleware, traces. */
31
+ browser?: BrowserConfig;
15
32
  /** End-to-end laws: the app to drive; see `parseE2eConfig`. */
16
33
  e2e?: E2eConfig;
17
34
  /**