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/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;
@@ -168,6 +170,9 @@ export async function check(options, enforceLock) {
168
170
  }
169
171
  return verdict;
170
172
  };
173
+ // `only` (names) and `onlyKeys` (`file::name`) narrow the run; a law they leave out has no result and no event.
174
+ const keyed = (law) => options.onlyKeys === undefined || options.onlyKeys.includes(lawKey(law.file, law.name));
175
+ const selected = (law) => (options.only === undefined || options.only.includes(law.name)) && keyed(law);
171
176
  const sources = new Sources(options.cwd);
172
177
  // What a law reaches is syntactic and cheap; a project that cannot be read this way just has no locations.
173
178
  const exercisesFor = (law) => {
@@ -268,13 +273,13 @@ export async function check(options, enforceLock) {
268
273
  }
269
274
  }
270
275
  for (const law of laws) {
271
- if (law.problems.length > 0 && !blocked.has(lawKey(law.file, law.name)))
276
+ if (keyed(law) && law.problems.length > 0 && !blocked.has(lawKey(law.file, law.name)))
272
277
  add(law, 'error', 'manifest', { message: law.problems.join('; ') });
273
278
  }
274
279
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
275
280
  const compiled = [...new Set([...options.files, ...covered])];
276
- const nodeLaws = laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind === 'node').length;
277
- const runsHere = laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind !== 'browser').length;
281
+ const nodeLaws = laws.filter((law) => selected(law) && law.problems.length === 0 && verdictOf(law.file).kind === 'node').length;
282
+ const runsHere = laws.filter((law) => selected(law) && law.problems.length === 0 && verdictOf(law.file).kind !== 'browser').length;
278
283
  // The sandbox is on unless the person turned it off with `sandbox: false` (`--no-sandbox`), and a Node that cannot
279
284
  // enforce it is an error here, never a quiet fallback. End-to-end laws are no exception: see `allowE2e`.
280
285
  const sandboxed = runsHere > 0 && useSandbox(options);
@@ -290,6 +295,10 @@ export async function check(options, enforceLock) {
290
295
  : undefined;
291
296
  // What the type checker works out is kept with the build it came from, so an unchanged project skips the checker.
292
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}`;
293
302
  let programOf;
294
303
  const program = () => (programOf ??=
295
304
  built.program ?? ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions)));
@@ -312,7 +321,7 @@ export async function check(options, enforceLock) {
312
321
  }
313
322
  };
314
323
  const runBody = async (law, add) => {
315
- if (options.only !== undefined && !options.only.includes(law.name))
324
+ if (!selected(law))
316
325
  return;
317
326
  if (blocked.has(lawKey(law.file, law.name)))
318
327
  return;
@@ -367,15 +376,27 @@ export async function check(options, enforceLock) {
367
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.
368
377
  const execute = async (runOptions) => {
369
378
  if (!sandboxed || e2e)
370
- return runLawGuarded(built.outDir, law, runOptions, types.plans);
379
+ return runLawGuarded(built.outDir, law, runOptions, types.plans, runBuildKey);
371
380
  if (sandbox === undefined)
372
381
  throw new Error('the law sandbox is on but was not set up');
373
- const ran = await sandbox.run(built.outDir, law, runOptions, types.plans);
382
+ const ran = await sandbox.run(built.outDir, law, runOptions, types.plans, runBuildKey);
374
383
  if (ran === 'timeout')
375
384
  return ran;
376
385
  isAsync = ran.async;
377
386
  return ran.outcome;
378
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
+ };
379
400
  let details;
380
401
  // Counterexamples found before are tried first.
381
402
  let lawOptions = options.noRegressions
@@ -390,6 +411,32 @@ export async function check(options, enforceLock) {
390
411
  if (!options.explicit?.includes('property-timeout'))
391
412
  limitMs = e2eConfig?.timeoutMs ?? 120000;
392
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
+ }
393
440
  try {
394
441
  details = e2e
395
442
  ? await runE2eLaw({ file: law.file, name: law.name, fn: fn, generators: types.generators }, lawOptions, await ensureServer(e2eConfig ?? {}, options.cwd), limitMs)
@@ -400,6 +447,7 @@ export async function check(options, enforceLock) {
400
447
  symbol: law.symbol,
401
448
  jsFile: jsPath(built.outDir, law.file),
402
449
  generators: types.generators,
450
+ plans: types.plans,
403
451
  }, lawOptions)
404
452
  : await execute(lawOptions);
405
453
  }
@@ -455,30 +503,7 @@ export async function check(options, enforceLock) {
455
503
  });
456
504
  return;
457
505
  }
458
- const holds = (inputs) => {
459
- if (sandboxed && sandbox === undefined)
460
- return false;
461
- if (sandbox !== undefined)
462
- return sandbox.holds(built.outDir, law, inputs, limitMs);
463
- try {
464
- return fn(...inputs) !== false;
465
- }
466
- catch (error) {
467
- return isDiscard(error);
468
- }
469
- };
470
- const proof = await proveLaw({
471
- law,
472
- shapes: types.shapes,
473
- jsFile: jsPath(built.outDir, law.file),
474
- bound: options.bound,
475
- timeoutMs: options.proofTimeoutMs,
476
- holds,
477
- solvers: config.solvers,
478
- certify: certifyMode === false
479
- ? undefined
480
- : { mode: certifyMode, dir: join(options.cwd, '.tslaws', 'certificates'), root: options.cwd },
481
- });
506
+ const proof = await (earlyProof ?? startProof());
482
507
  const certified = (certificate) => certificate === undefined ? {} : { certificate };
483
508
  const assumed = (list) => (list.length > 0 ? { assumptions: list } : {});
484
509
  if (proof.kind === 'proved' || proof.kind === 'bounded') {
@@ -574,20 +599,21 @@ export async function check(options, enforceLock) {
574
599
  nextToFlush += 1;
575
600
  }
576
601
  };
577
- // Every law takes a slot of the process-wide CPU budget, and what it starts (a proof, a solver, a law process) runs on
578
- // that slot. Browser and end-to-end laws also share one page and one server, so they queue for it first.
579
- 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);
580
606
  await Promise.all(laws.map(async (law, index) => {
581
- const skipped = (options.only !== undefined && !options.only.includes(law.name)) || blocked.has(lawKey(law.file, law.name));
607
+ const skipped = !selected(law) || blocked.has(lawKey(law.file, law.name));
582
608
  if (skipped) {
583
609
  finished.set(index, []);
584
610
  flush();
585
611
  return;
586
612
  }
587
613
  const inSlot = () => budget.run(() => runOne(law, index));
588
- await (verdictOf(law.file).kind !== 'node' ? page.run(inSlot) : inSlot());
614
+ await (verdictOf(law.file).kind === 'e2e' ? e2eGate.run(inSlot) : inSlot());
589
615
  }));
590
- if (enforceLock) {
616
+ if (enforceLock && options.onlyKeys === undefined) {
591
617
  const coverage = derived.coverage(() => analyzeCoverage({
592
618
  cwd: options.cwd,
593
619
  outDir: built.outDir,
@@ -621,6 +647,8 @@ export async function check(options, enforceLock) {
621
647
  });
622
648
  }
623
649
  }
650
+ derived.flush();
651
+ proofCache.flush();
624
652
  await closeBrowser();
625
653
  await stopServer();
626
654
  // Records for `tslaws accept` to consider; a law that did not end proved or bounded keeps no certificate.
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import type { CheckReport } from './check.ts';
2
2
  export declare function totals(report: CheckReport): string;
3
+ /**
4
+ * Where a run of one project writes and what it leaves alone. A root run gives each project its own: `out` can be a
5
+ * buffer, `skip` lists the projects nested below this one (so a root that is itself a project does not run theirs) and
6
+ * `tag` names the project on every ndjson line.
7
+ */
8
+ interface Run {
9
+ out: (text: string) => void;
10
+ skip: string[];
11
+ tag?: string;
12
+ }
3
13
  export declare function watched(filename: string | null): boolean;
4
14
  /** What a command needs from its caller. `home` is for unit tests; the CLI never sets it. */
5
15
  export interface CommandContext {
@@ -15,6 +25,11 @@ export interface CommandContext {
15
25
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
16
26
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
17
27
  export declare function runDelegateCommand(argv: string[], cwd: string, ctx: CommandContext): number;
28
+ /**
29
+ * `tslaws badge [--out DIR]`: the two endpoint badges of the project, from a check run now or from the `check --json`
30
+ * output in `--report`. Writes only the two files and prints the markdown; never touches the lock.
31
+ */
32
+ export declare function badgeCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext, run?: Run): Promise<number>;
18
33
  /** What `promote` and `propose` ask of their surroundings, beyond the context every command has. `ask`, `stdin` and `checkFile` are for unit tests; the CLI never sets them. */
19
34
  export interface ProposalContext extends CommandContext {
20
35
  ask?: (question: string) => Promise<string>;
@@ -33,3 +48,4 @@ export declare function proposeCommand(cwd: string, flags: Map<string, string |
33
48
  */
34
49
  export declare function promoteCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: ProposalContext): Promise<number>;
35
50
  export declare function main(args: string[]): Promise<number>;
51
+ export {};
package/dist/cli.js CHANGED
@@ -23,6 +23,7 @@ import { mutate, renderMutation } from "./mutate.js";
23
23
  import { mutateDefaults, resolveSettings } from "./settings.js";
24
24
  import { serveUi } from "./ui.js";
25
25
  import { acceptGate, defaultDuration, describeGrants, fileHash, grantFor, logDelegatedAccept, parseDuration, personOnly, revokeFor, } from "./delegation.js";
26
+ import { badgeFiles, badgeMarkdown, badgesOf, gitFacts, repoRelative, standingsOf, writeBadges, writeCertificatesPage, } from "./badge.js";
26
27
  import { certificateLabel } from "./certificates.js";
27
28
  import { fileOfKey, lockFormat, lockOf, mergeScoped, readLock, scopeOf, writeLockValue } from "./lock.js";
28
29
  import { lockLevels } from "./lawKinds.js";
@@ -30,7 +31,7 @@ import { securityUsage } from "./security/cli.js";
30
31
  import { plural } from "./plural.js";
31
32
  import { configureJobs } from "./pool.js";
32
33
  const usage = `tslaws init [--force] scaffold tslaws.json, .gitignore, AGENTS.md, Claude Code hooks and a starter law (never writes the lock)
33
- 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]
34
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
35
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
36
37
  tslaws regressions [list|clear] show or delete the stored counterexamples (.tslaws/regressions); check replays them first, --no-regressions skips them
@@ -42,6 +43,7 @@ tslaws propose <file.ts> [--from PATH] write a proposal into .tslaws/proposals
42
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
43
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)
44
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, 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
45
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)
46
48
  ${migrateUsage}
47
49
  ${securityUsage}
@@ -79,6 +81,7 @@ function parse(args) {
79
81
  'property-timeout',
80
82
  'jobs',
81
83
  'browser',
84
+ 'browser-mode',
82
85
  'port',
83
86
  'reporter',
84
87
  'law',
@@ -91,6 +94,10 @@ function parse(args) {
91
94
  'pr',
92
95
  'config-from',
93
96
  'results',
97
+ 'report',
98
+ 'repo',
99
+ 'branch',
100
+ 'link',
94
101
  'results-out',
95
102
  'head-sha',
96
103
  'rerun-workflow',
@@ -130,6 +137,7 @@ function parse(args) {
130
137
  arg === 'promote' ||
131
138
  arg === 'propose' ||
132
139
  arg === 'list' ||
140
+ arg === 'badge' ||
133
141
  arg === 'migrate' ||
134
142
  arg === 'delegate' ||
135
143
  arg === 'github' ||
@@ -238,6 +246,15 @@ function options(cwd, flags, chosen) {
238
246
  browser: flags.has('browser')
239
247
  ? resolveEngine(String(flags.get('browser')))
240
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,
241
258
  };
242
259
  }
243
260
  /** Files outside the directories `skip` (project-relative paths of projects nested in this one). */
@@ -432,6 +449,64 @@ function delegateCommand(cwd, action, flags, ctx) {
432
449
  out(`accept is lent to agents for ${granted.root} until ${granted.expires}\n`);
433
450
  return 0;
434
451
  }
452
+ /**
453
+ * `tslaws badge [--out DIR]`: the two endpoint badges of the project, from a check run now or from the `check --json`
454
+ * output in `--report`. Writes only the two files and prints the markdown; never touches the lock.
455
+ */
456
+ export async function badgeCommand(cwd, flags, files, ctx, run = direct) {
457
+ const err = ctx.err ?? stderrWrite;
458
+ const out = ctx.out ?? run.out;
459
+ for (const name of ['out', 'report', 'repo', 'branch', 'link']) {
460
+ if (flags.get(name) === true || flags.get(name) === '') {
461
+ err(`--${name} takes a value\n`);
462
+ return 1;
463
+ }
464
+ }
465
+ const text = (name) => {
466
+ const value = flags.get(name);
467
+ return typeof value === 'string' ? value : undefined;
468
+ };
469
+ const repoFlag = text('repo');
470
+ if (repoFlag !== undefined && !/^[\w.-]+\/[\w.-]+$/.test(repoFlag)) {
471
+ err('--repo takes OWNER/NAME\n');
472
+ return 1;
473
+ }
474
+ const report = text('report');
475
+ let results;
476
+ if (report !== undefined) {
477
+ const given = JSON.parse(readFileSync(resolve(cwd, report), 'utf8'));
478
+ if (!Array.isArray(given.results)) {
479
+ err(`${report} is not the output of \`tslaws check --json\` for one project (it has no results)\n`);
480
+ return 1;
481
+ }
482
+ results = given.results;
483
+ }
484
+ else {
485
+ const chosen = lawFiles(cwd, flags, files, run.skip);
486
+ if (chosen.length === 0) {
487
+ err('no laws files found (looking for *.laws.ts)\n');
488
+ return 1;
489
+ }
490
+ results = (await check({ ...options(cwd, flags, chosen), partial: files.length > 0 }, true)).results;
491
+ }
492
+ const dir = text('out') ?? 'badges';
493
+ const lock = readLock(join(cwd, 'tsc-laws.lock'));
494
+ const badges = badgesOf(standingsOf(results, lock));
495
+ writeBadges(resolve(cwd, dir), badges);
496
+ const page = writeCertificatesPage(cwd, resolve(cwd, dir), results, lock);
497
+ const git = gitFacts(cwd);
498
+ const repo = repoFlag ?? ctx.env.GITHUB_REPOSITORY ?? git.repo;
499
+ const where = repoRelative(cwd, dir, git.top);
500
+ const markdown = badgeMarkdown({ repo, branch: text('branch') ?? 'main', dir: where, link: text('link'), page });
501
+ out(`${badges.laws.label}: ${badges.laws.message}\n${badges.certificates.label}: ${badges.certificates.message}\n`);
502
+ out(`wrote ${where}/${badgeFiles.laws} and ${where}/${badgeFiles.certificates}; commit them and add to your README:\n\n`);
503
+ out(`${markdown}\n`);
504
+ if (page && text('link') === undefined)
505
+ out(`\nboth badges link to ${where}/README.md, the certificates page written beside them\n`);
506
+ if (repo === undefined)
507
+ out('\nreplace OWNER/REPO: no GitHub remote was found (name it with --repo OWNER/NAME)\n');
508
+ return 0;
509
+ }
435
510
  const readStdin = async () => {
436
511
  let text = '';
437
512
  for await (const chunk of process.stdin)
@@ -770,6 +845,8 @@ async function runOne(command, flags, files, cwd, run) {
770
845
  err: (text) => void process.stderr.write(text),
771
846
  });
772
847
  }
848
+ if (command === 'badge')
849
+ return badgeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env }, run);
773
850
  if (command === 'accept')
774
851
  return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
775
852
  if (command === 'delegate')
package/dist/compile.js CHANGED
@@ -25,6 +25,9 @@ function launch(compiler, args, options) {
25
25
  }
26
26
  /** The compiler finds its lib files in TSC_TS_LIB_DIR; without it, use the TypeScript 7 libs scriptc ships. */
27
27
  function compilerEnv(cwd, compiler) {
28
+ // A caller outside the CLI (the API, a test) can reach here with no compiler resolved; say so, not a TypeError from dirname.
29
+ if (typeof compiler !== 'string')
30
+ throw new Error(noCompiler('none'));
28
31
  if (process.env.TSC_TS_LIB_DIR !== undefined)
29
32
  return process.env;
30
33
  // The npm compiler package keeps the lib files beside the executable.
@@ -44,11 +47,12 @@ function compilerEnv(cwd, compiler) {
44
47
  return process.env;
45
48
  }
46
49
  }
50
+ const noCompiler = (compiler) => `no tsc-laws compiler found (${compiler}): install the tslaws-compiler package for this platform, or set TSC_LAWS_BIN / --compiler to the compiler executable`;
47
51
  /** Lists the laws of `files` with the problems that stop them running. */
48
52
  /** Says what to do when the compiler cannot start, in particular when none was found at all. */
49
53
  function cannotRun(compiler, error) {
50
54
  if (error.code === 'ENOENT')
51
- return `no tsc-laws compiler found (${compiler}): install the tslaws-compiler package for this platform, or set TSC_LAWS_BIN / --compiler to the compiler executable`;
55
+ return noCompiler(compiler);
52
56
  return `cannot run ${compiler}: ${error.message}`;
53
57
  }
54
58
  /** The compiler name that selects the built-in path: stock TypeScript, with laws written as `law(...)` calls. */
@@ -210,6 +214,9 @@ const awaitStub = (file) => `throw new Error(${JSON.stringify(`${file}: ${awaitA
210
214
  * words is left alone. Returns the new text and whether the module waits at its top level.
211
215
  */
212
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 };
213
220
  const parsed = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, false, ts.ScriptKind.JS);
214
221
  const edits = [];
215
222
  const env = `globalThis.${importMetaEnvGlobal}`;
@@ -340,9 +347,20 @@ function compile(compiler, files, cwd, resolution) {
340
347
  ...extra,
341
348
  ];
342
349
  const args = ['--ignoreConfig', ...flags, ...files];
343
- // What the options say is part of what was built.
344
- const keyArgs = [...args, JSON.stringify(resolution?.options ?? null)];
345
- 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);
346
364
  if (reused !== undefined)
347
365
  return reused;
348
366
  rmSync(outDir, { recursive: true, force: true });
@@ -398,11 +416,34 @@ function compile(compiler, files, cwd, resolution) {
398
416
  again(argsFor(used, [envTypes]));
399
417
  const problems = lowering ? lowerEmittedModules(outDir, { outDir, root }) : [];
400
418
  // The project's own files sit where they do under the root, so its output is that deep in `outDir`.
401
- return {
419
+ const result = {
402
420
  outDir: join(outDir, relative(root, cwd)),
403
421
  diagnostics: [output().trim(), ...problems].filter((part) => part !== '').join('\n'),
404
422
  ok: run.status === 0 && problems.length === 0,
405
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;
406
447
  }
407
448
  /** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
408
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
  /**