tslaws 0.10.0 → 1.1.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 (124) hide show
  1. package/README.md +13 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/badge.d.ts +64 -0
  4. package/dist/badge.js +121 -0
  5. package/dist/browser.d.ts +1 -1
  6. package/dist/browser.js +25 -5
  7. package/dist/bundled.js +2 -2
  8. package/dist/bundlerPlugins.d.ts +2 -0
  9. package/dist/bundlerPlugins.js +7 -0
  10. package/dist/certificates.d.ts +139 -0
  11. package/dist/certificates.js +433 -0
  12. package/dist/chc.d.ts +97 -0
  13. package/dist/chc.js +307 -0
  14. package/dist/check.d.ts +13 -1
  15. package/dist/check.js +218 -31
  16. package/dist/cli.d.ts +18 -0
  17. package/dist/cli.js +242 -34
  18. package/dist/compile.d.ts +15 -5
  19. package/dist/compile.js +203 -70
  20. package/dist/coverage.d.ts +38 -1
  21. package/dist/coverage.js +123 -19
  22. package/dist/e2eApi.js +3 -1
  23. package/dist/generators.js +12 -2
  24. package/dist/github.d.ts +49 -5
  25. package/dist/github.js +107 -24
  26. package/dist/githubCli.d.ts +28 -0
  27. package/dist/githubCli.js +1113 -212
  28. package/dist/hints.js +2 -1
  29. package/dist/init.js +42 -0
  30. package/dist/isolate.d.ts +33 -0
  31. package/dist/isolate.js +262 -0
  32. package/dist/isolatedCheck.d.ts +1 -0
  33. package/dist/isolatedCheck.js +16 -0
  34. package/dist/lawHost.d.ts +50 -0
  35. package/dist/lawHost.js +197 -0
  36. package/dist/lawRuntime.d.ts +45 -0
  37. package/dist/lawRuntime.js +321 -0
  38. package/dist/lock.d.ts +49 -9
  39. package/dist/lock.js +132 -21
  40. package/dist/mcp.js +28 -7
  41. package/dist/mutate.d.ts +4 -0
  42. package/dist/mutate.js +7 -1
  43. package/dist/plan.d.ts +1 -0
  44. package/dist/plan.js +4 -0
  45. package/dist/pluginHooks.d.ts +20 -0
  46. package/dist/pluginHooks.js +57 -0
  47. package/dist/pluginHost.d.ts +5 -0
  48. package/dist/pluginHost.js +43 -0
  49. package/dist/pluginWorker.d.ts +1 -0
  50. package/dist/pluginWorker.js +40 -0
  51. package/dist/plural.d.ts +2 -0
  52. package/dist/plural.js +4 -0
  53. package/dist/pool.d.ts +80 -7
  54. package/dist/pool.js +222 -11
  55. package/dist/projects.d.ts +43 -1
  56. package/dist/projects.js +283 -11
  57. package/dist/promote.d.ts +56 -2
  58. package/dist/promote.js +429 -13
  59. package/dist/property.js +5 -1
  60. package/dist/propertyWorker.js +9 -4
  61. package/dist/proposals.d.ts +52 -4
  62. package/dist/proposals.js +484 -21
  63. package/dist/reporters.js +5 -1
  64. package/dist/runtimeEnv.d.ts +13 -5
  65. package/dist/runtimeEnv.js +48 -10
  66. package/dist/sandbox.d.ts +98 -0
  67. package/dist/sandbox.js +673 -0
  68. package/dist/sandboxGuard.d.ts +56 -0
  69. package/dist/sandboxGuard.js +249 -0
  70. package/dist/seal.d.ts +9 -0
  71. package/dist/seal.js +426 -0
  72. package/dist/security/cli.d.ts +6 -0
  73. package/dist/security/cli.js +39 -0
  74. package/dist/security/cwe.d.ts +14 -0
  75. package/dist/security/cwe.js +40 -0
  76. package/dist/security/deps/cache.d.ts +28 -0
  77. package/dist/security/deps/cache.js +107 -0
  78. package/dist/security/deps/config.d.ts +16 -0
  79. package/dist/security/deps/config.js +43 -0
  80. package/dist/security/deps/imports.d.ts +4 -0
  81. package/dist/security/deps/imports.js +33 -0
  82. package/dist/security/deps/lockfiles.d.ts +23 -0
  83. package/dist/security/deps/lockfiles.js +153 -0
  84. package/dist/security/deps/osv.d.ts +66 -0
  85. package/dist/security/deps/osv.js +137 -0
  86. package/dist/security/deps/run.d.ts +54 -0
  87. package/dist/security/deps/run.js +135 -0
  88. package/dist/security/deps/severity.d.ts +26 -0
  89. package/dist/security/deps/severity.js +78 -0
  90. package/dist/security/generators.d.ts +9 -0
  91. package/dist/security/generators.js +36 -0
  92. package/dist/security/index.d.ts +27 -0
  93. package/dist/security/index.js +18 -0
  94. package/dist/security/integers.d.ts +31 -0
  95. package/dist/security/integers.js +105 -0
  96. package/dist/security/law.d.ts +54 -0
  97. package/dist/security/law.js +54 -0
  98. package/dist/security/pathTraversal.d.ts +29 -0
  99. package/dist/security/pathTraversal.js +146 -0
  100. package/dist/security/prototypePollution.d.ts +30 -0
  101. package/dist/security/prototypePollution.js +142 -0
  102. package/dist/security/redirect.d.ts +21 -0
  103. package/dist/security/redirect.js +154 -0
  104. package/dist/security/redos.d.ts +21 -0
  105. package/dist/security/redos.js +93 -0
  106. package/dist/security/validation.d.ts +25 -0
  107. package/dist/security/validation.js +89 -0
  108. package/dist/security/xss.d.ts +21 -0
  109. package/dist/security/xss.js +90 -0
  110. package/dist/settings.d.ts +20 -0
  111. package/dist/settings.js +32 -0
  112. package/dist/smt.d.ts +37 -1
  113. package/dist/smt.js +277 -111
  114. package/dist/smtWorker.d.ts +1 -0
  115. package/dist/smtWorker.js +26 -0
  116. package/dist/solvers.d.ts +9 -0
  117. package/dist/solvers.js +11 -5
  118. package/dist/symbolic.d.ts +54 -1
  119. package/dist/symbolic.js +239 -13
  120. package/dist/tsconfigResolve.d.ts +28 -0
  121. package/dist/tsconfigResolve.js +141 -0
  122. package/dist/types.d.ts +33 -0
  123. package/hooks/claude-hook.mjs +2 -0
  124. package/package.json +19 -7
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { createInterface } from 'node:readline/promises';
2
- import { readFileSync, watch } from 'node:fs';
2
+ import { existsSync, readFileSync, watch } from 'node:fs';
3
3
  import { join, relative, resolve, sep } from 'node:path';
4
4
  import { resolveEngine } from "./browser.js";
5
5
  import { bundledCompiler, checkoutCompiler } from "./bundled.js";
6
- import { check, exemptionsOf } from "./check.js";
6
+ import { certificatesToAccept, check, exemptionsOf } from "./check.js";
7
7
  import { readManifest } from "./compile.js";
8
8
  import { hintFor } from "./hints.js";
9
9
  import { discoverLaws, discoverProposals, ignoredDirs } from "./lawFiles.js";
@@ -11,38 +11,47 @@ import { isProposedLawFile } from "./lawNames.js";
11
11
  import { init, nextStep } from "./init.js";
12
12
  import { listLawFiles, renderList } from "./list.js";
13
13
  import { serveMcp } from "./mcp.js";
14
- import { discoverProjects, isMonorepoRoot } from "./projects.js";
14
+ import { affectedProjects, changedSince, discoverProjects, isMonorepoRoot } from "./projects.js";
15
15
  import { promoteFiles, promoteProposal } from "./promote.js";
16
16
  import { addProposal, ProposalError } from "./proposals.js";
17
17
  import { clearCorpus, listCorpus } from "./regressions.js";
18
18
  import { proposalText, reporterNames, reportAs } from "./reporters.js";
19
19
  import { readConfig } from "./coverage.js";
20
+ import { parseGithubConfig } from "./github.js";
20
21
  import { migrateCommand, migrateUsage } from "./migrate/index.js";
21
22
  import { mutate, renderMutation } from "./mutate.js";
22
23
  import { mutateDefaults, resolveSettings } from "./settings.js";
23
24
  import { serveUi } from "./ui.js";
24
25
  import { acceptGate, defaultDuration, describeGrants, fileHash, grantFor, logDelegatedAccept, parseDuration, personOnly, revokeFor, } from "./delegation.js";
25
- import { writeLock } from "./lock.js";
26
+ import { badgeFiles, badgeMarkdown, badgesOf, gitFacts, repoRelative, standingsOf, writeBadges, writeCertificatesPage, } from "./badge.js";
27
+ import { certificateLabel } from "./certificates.js";
28
+ import { fileOfKey, lockFormat, lockOf, mergeScoped, readLock, scopeOf, writeLockValue } from "./lock.js";
26
29
  import { lockLevels } from "./lawKinds.js";
30
+ import { securityUsage } from "./security/cli.js";
31
+ import { plural } from "./plural.js";
32
+ import { configureJobs } from "./pool.js";
27
33
  const usage = `tslaws init [--force] scaffold tslaws.json, .gitignore, AGENTS.md, Claude Code hooks and a starter law (never writes the lock)
28
- tslaws check [files...] [--reporter text|json|junit|github|ndjson] [--law NAME[,NAME]] [--json] [--summary] [--watch] [--runs N] [--seed N] [--no-prove] [--no-regressions] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--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]
29
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
30
- tslaws mutate [files...] [--max N] [--seed N] [--runs N] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--browser ENGINE] [--json] mutation-test the laws: mutate covered code, report mutants no law kills
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
31
37
  tslaws regressions [list|clear] show or delete the stored counterexamples (.tslaws/regressions); check replays them first, --no-regressions skips them
32
38
  tslaws accept [files...] record the current laws in tsc-laws.lock (people only: needs a terminal, or a live delegation; never under CI)
33
39
  tslaws delegate grant [--for 1h|8h|1d|7d] [--root DIR] lend accept to an agent for a limited time (people only; default 8h, max 7d)
34
40
  tslaws delegate revoke [--root DIR] withdraw the delegation for a project (people only)
35
41
  tslaws delegate status list delegations and when they end
36
42
  tslaws propose <file.ts> [--from PATH] write a proposal into .tslaws/proposals/ from PATH or stdin (outside the tree, git-ignored; never touches the lock or any other file)
37
- tslaws promote <proposal> [--to PATH] move a proposal from .tslaws/proposals/ into the tree at a path you confirm (people only: needs a terminal; run accept afterwards). In-tree *.proposed.laws.ts files (the usual proposals) promote with --all or by name
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
38
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)
39
- 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 (CI only; see "github" in tslaws.json)
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
40
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)
41
48
  ${migrateUsage}
49
+ ${securityUsage}
42
50
 
43
- In a monorepo (a root tslaws.json with "projects", or package.json/pnpm workspaces whose packages have a tslaws.json), run from the root: check, accept, list, mutate and regressions run in every project, one after another, each with its own config and lock, and end with one summary line. --json and --reporter json print one object keyed by project path; --reporter ndjson tags each line with "project". init, ui, mcp, github, propose, promote, delegate, migrate and --watch run in one project: pick it with --project when the root has several.
51
+ In a monorepo (a root tslaws.json with "projects", or package.json/pnpm workspaces whose packages have a tslaws.json), run from the root: check, accept, list, mutate, regressions and security deps run in every project, one after another, each with its own config and lock, and end with one summary line. --json and --reporter json print one object keyed by project path; --reporter ndjson tags each line with "project". init, ui, mcp, github, propose, promote, delegate, migrate and --watch run in one project: pick it with --project when the root has several.
44
52
  --project run only in this project directory (repeat it, or comma-separate: --project packages/a,packages/b)
45
53
  --filter run only in projects whose path matches this glob (repeatable; a leading ! excludes), for example --filter 'packages/*'
54
+ --changed run only the projects affected since the merge-base of this ref and HEAD (committed, staged and untracked changes): the projects holding a changed file and everything that depends on them; a root config change runs all. Combines with --project and --filter. In one project: runs only if something there changed. For example --changed origin/main
46
55
 
47
56
  Without files, every *.laws.ts under the current directory (and every file the "laws" globs of tslaws.json pick that declares a law) is checked; with --proposed, the in-tree *.proposed.laws.ts files are (and any proposals in .tslaws/proposals/), with no lock and no coverage gate.
48
57
  A laws file's level comes from its name by default: *.browser.laws.ts is a browser law, *.e2e.laws.ts an end-to-end law, anything else runs in Node. With "levels": "imports" in tslaws.json it comes from the import graph instead (tslaws/browser, tslaws/adapters/* or tslaws/e2e, directly or through the file's own modules), and the names are hints.
@@ -70,6 +79,7 @@ function parse(args) {
70
79
  'bound',
71
80
  'proof-timeout',
72
81
  'property-timeout',
82
+ 'jobs',
73
83
  'browser',
74
84
  'port',
75
85
  'reporter',
@@ -82,10 +92,18 @@ function parse(args) {
82
92
  'out',
83
93
  'pr',
84
94
  'config-from',
95
+ 'results',
96
+ 'report',
97
+ 'repo',
98
+ 'branch',
99
+ 'link',
100
+ 'results-out',
85
101
  'head-sha',
86
102
  'rerun-workflow',
87
103
  'protect',
88
104
  'project-path',
105
+ 'fail-on',
106
+ 'changed',
89
107
  ]);
90
108
  for (let i = 0; i < args.length; i += 1) {
91
109
  const arg = args[i];
@@ -118,9 +136,11 @@ function parse(args) {
118
136
  arg === 'promote' ||
119
137
  arg === 'propose' ||
120
138
  arg === 'list' ||
139
+ arg === 'badge' ||
121
140
  arg === 'migrate' ||
122
141
  arg === 'delegate' ||
123
- arg === 'github'))
142
+ arg === 'github' ||
143
+ arg === 'security'))
124
144
  command = arg;
125
145
  else
126
146
  files.push(arg);
@@ -135,6 +155,8 @@ function describe(result) {
135
155
  lines.push(` ${result.message}`);
136
156
  if (result.assumptions !== undefined && result.assumptions.length > 0)
137
157
  lines.push(` assuming: ${result.assumptions.join('; ')}`);
158
+ if (result.certificate !== undefined)
159
+ lines.push(` certificate: ${certificateLabel(result.certificate)}`);
138
160
  const proposed = proposalText(result);
139
161
  if (proposed !== undefined)
140
162
  lines.push(` ${proposed}`);
@@ -158,9 +180,9 @@ function summarise(result) {
158
180
  .replace(/\s+/g, ' ');
159
181
  return `${result.status.toUpperCase()} ${result.name} (${result.file}:${result.line})${detail === '' ? '' : ` ${detail}`}`;
160
182
  }
161
- function totals(report) {
183
+ export function totals(report) {
162
184
  const count = (status) => report.results.filter((r) => r.status === status).length;
163
- return `${report.results.length} laws: ${count('proved')} proved, ${count('bounded')} bounded, ${count('tested')} tested, ${count('open')} open, ${count('failed')} failed, ${count('tampered')} tampered, ${count('error')} errors`;
185
+ return `${plural(report.results.length, 'law')}: ${count('proved')} proved, ${count('bounded')} bounded, ${count('tested')} tested, ${count('open')} open, ${count('failed')} failed, ${count('tampered')} tampered, ${plural(count('error'), 'error')}`;
164
186
  }
165
187
  function render(report, flags, project) {
166
188
  const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
@@ -204,7 +226,17 @@ function options(cwd, flags, chosen) {
204
226
  compiler: String(flags.get('compiler') ?? process.env.TSC_LAWS_BIN ?? bundledCompiler() ?? checkoutCompiler(cwd) ?? 'tsc-laws'),
205
227
  lockFile: join(cwd, 'tsc-laws.lock'),
206
228
  noProve: flags.has('no-prove'),
229
+ // `--certify` turns certificates on (and keeps a "require" from tslaws.json); `--require-certify` makes them required.
230
+ certify: flags.has('require-certify')
231
+ ? 'require'
232
+ : flags.has('certify')
233
+ ? readConfig(cwd).certify === 'require'
234
+ ? 'require'
235
+ : true
236
+ : undefined,
207
237
  noRegressions: flags.has('no-regressions'),
238
+ sandbox: !flags.has('no-sandbox'),
239
+ allowE2e: flags.has('allow-e2e'),
208
240
  only: typeof flags.get('law') === 'string' ? String(flags.get('law')).split(',').filter(Boolean) : undefined,
209
241
  bound: settings.bound,
210
242
  proofTimeoutMs: settings.proofTimeoutMs,
@@ -240,7 +272,7 @@ async function runCheck(cwd, flags, files, run = direct) {
240
272
  run.out(`${JSON.stringify(run.tag === undefined ? event : { project: run.tag, ...event })}\n`);
241
273
  }
242
274
  : undefined;
243
- const report = await check({ ...options(cwd, flags, chosen), onEvent }, !flags.has('proposed'));
275
+ const report = await check({ ...options(cwd, flags, chosen), partial: files.length > 0, onEvent }, !flags.has('proposed'));
244
276
  run.out(render(report, flags, run.tag));
245
277
  return report.ok ? 0 : 1;
246
278
  }
@@ -307,8 +339,10 @@ export async function acceptCommand(cwd, flags, files, ctx) {
307
339
  err('no laws files found (looking for *.laws.ts)\n');
308
340
  return 1;
309
341
  }
310
- if (readConfig(cwd).github !== undefined) {
311
- err('this project accepts laws on GitHub: tsc-laws.lock is written only by the tslaws workflow when a pull request merges (see "github" in tslaws.json); propose the laws in a pull request instead\n');
342
+ // A project that accepts laws on GitHub still lets a person accept by hand, unless it sets "github.local" to false.
343
+ const github = readConfig(cwd).github;
344
+ if (github !== undefined && !parseGithubConfig(github).local) {
345
+ err('this project accepts laws on GitHub only: tsc-laws.lock is written by the tslaws workflow, on merge or on demand (see "github" in tslaws.json, where "local" is false); propose the laws in a pull request instead\n');
312
346
  return 1;
313
347
  }
314
348
  const gate = acceptGate({ isTTY: ctx.isTTY, env: ctx.env, root: cwd, now: ctx.now, home: ctx.home });
@@ -318,7 +352,7 @@ export async function acceptCommand(cwd, flags, files, ctx) {
318
352
  }
319
353
  const opts = options(cwd, flags, chosen);
320
354
  const laws = readManifest(opts.compiler, opts.files, cwd);
321
- out(`${laws.length} laws in ${chosen.length} files:\n${laws.map((l) => ` ${l.file}:${l.line} ${l.name}`).join('\n')}\n`);
355
+ out(`${plural(laws.length, 'law')} in ${plural(chosen.length, 'file')}:\n${laws.map((l) => ` ${l.file}:${l.line} ${l.name}`).join('\n')}\n`);
322
356
  if (!gate.delegated) {
323
357
  const rl = createInterface({ input: process.stdin, output: process.stdout });
324
358
  const answer = await rl.question('Write tsc-laws.lock? Type accept, yes or y to confirm: ');
@@ -336,7 +370,22 @@ export async function acceptCommand(cwd, flags, files, ctx) {
336
370
  // tslaws/browser reads as tampered until a person accepts again. By name (the default) the lock is unchanged.
337
371
  const mode = readConfig(cwd).levels ?? 'names';
338
372
  const levels = lockLevels(cwd, laws, mode);
339
- writeLock(opts.lockFile, laws, exempt, levels);
373
+ // Certificates enter the lock only for the proofs and problems of this run; see certificatesToAccept.
374
+ // Naming files accepts only those: the lock keeps every entry it has for the other files.
375
+ const held = readLock(opts.lockFile);
376
+ // The entries a partial accept keeps for the other files were hashed in the old format; keeping them under the new
377
+ // version would make every one of them read as changed. Only a full accept can write the whole lock again.
378
+ if (files.length > 0 && held !== undefined && (held.version ?? lockFormat) < lockFormat) {
379
+ out('Nothing written: lock format upgraded. The lock holds laws hashed in the old format for files you did not name; run `tslaws accept` without files to record them all.\n');
380
+ return 1;
381
+ }
382
+ const scope = scopeOf(chosen);
383
+ const heldHere = files.length === 0
384
+ ? held?.certificates
385
+ : Object.fromEntries(Object.entries(held?.certificates ?? {}).filter(([key]) => scope.has(fileOfKey(key))));
386
+ const certificates = await certificatesToAccept(opts, laws, heldHere, out);
387
+ const next = lockOf(laws, exempt, levels, certificates);
388
+ writeLockValue(opts.lockFile, files.length === 0 ? next : mergeScoped(held, scope, next));
340
389
  out('tsc-laws.lock written\n');
341
390
  if (gate.delegated) {
342
391
  logDelegatedAccept(cwd, gate.grant, before, fileHash(opts.lockFile), ctx.now ?? new Date());
@@ -390,6 +439,64 @@ function delegateCommand(cwd, action, flags, ctx) {
390
439
  out(`accept is lent to agents for ${granted.root} until ${granted.expires}\n`);
391
440
  return 0;
392
441
  }
442
+ /**
443
+ * `tslaws badge [--out DIR]`: the two endpoint badges of the project, from a check run now or from the `check --json`
444
+ * output in `--report`. Writes only the two files and prints the markdown; never touches the lock.
445
+ */
446
+ export async function badgeCommand(cwd, flags, files, ctx, run = direct) {
447
+ const err = ctx.err ?? stderrWrite;
448
+ const out = ctx.out ?? run.out;
449
+ for (const name of ['out', 'report', 'repo', 'branch', 'link']) {
450
+ if (flags.get(name) === true || flags.get(name) === '') {
451
+ err(`--${name} takes a value\n`);
452
+ return 1;
453
+ }
454
+ }
455
+ const text = (name) => {
456
+ const value = flags.get(name);
457
+ return typeof value === 'string' ? value : undefined;
458
+ };
459
+ const repoFlag = text('repo');
460
+ if (repoFlag !== undefined && !/^[\w.-]+\/[\w.-]+$/.test(repoFlag)) {
461
+ err('--repo takes OWNER/NAME\n');
462
+ return 1;
463
+ }
464
+ const report = text('report');
465
+ let results;
466
+ if (report !== undefined) {
467
+ const given = JSON.parse(readFileSync(resolve(cwd, report), 'utf8'));
468
+ if (!Array.isArray(given.results)) {
469
+ err(`${report} is not the output of \`tslaws check --json\` for one project (it has no results)\n`);
470
+ return 1;
471
+ }
472
+ results = given.results;
473
+ }
474
+ else {
475
+ const chosen = lawFiles(cwd, flags, files, run.skip);
476
+ if (chosen.length === 0) {
477
+ err('no laws files found (looking for *.laws.ts)\n');
478
+ return 1;
479
+ }
480
+ results = (await check({ ...options(cwd, flags, chosen), partial: files.length > 0 }, true)).results;
481
+ }
482
+ const dir = text('out') ?? 'badges';
483
+ const lock = readLock(join(cwd, 'tsc-laws.lock'));
484
+ const badges = badgesOf(standingsOf(results, lock));
485
+ writeBadges(resolve(cwd, dir), badges);
486
+ const page = writeCertificatesPage(cwd, resolve(cwd, dir), results, lock);
487
+ const git = gitFacts(cwd);
488
+ const repo = repoFlag ?? ctx.env.GITHUB_REPOSITORY ?? git.repo;
489
+ const where = repoRelative(cwd, dir, git.top);
490
+ const markdown = badgeMarkdown({ repo, branch: text('branch') ?? 'main', dir: where, link: text('link'), page });
491
+ out(`${badges.laws.label}: ${badges.laws.message}\n${badges.certificates.label}: ${badges.certificates.message}\n`);
492
+ out(`wrote ${where}/${badgeFiles.laws} and ${where}/${badgeFiles.certificates}; commit them and add to your README:\n\n`);
493
+ out(`${markdown}\n`);
494
+ if (page && text('link') === undefined)
495
+ out(`\nboth badges link to ${where}/README.md, the certificates page written beside them\n`);
496
+ if (repo === undefined)
497
+ out('\nreplace OWNER/REPO: no GitHub remote was found (name it with --repo OWNER/NAME)\n');
498
+ return 0;
499
+ }
393
500
  const readStdin = async () => {
394
501
  let text = '';
395
502
  for await (const chunk of process.stdin)
@@ -458,6 +565,7 @@ export async function promoteCommand(cwd, flags, files, ctx) {
458
565
  err('--to takes one path, for one proposal\n');
459
566
  return 1;
460
567
  }
568
+ const yes = flags.get('yes') === true;
461
569
  const rl = ctx.ask === undefined ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
462
570
  const ask = ctx.ask ?? ((question) => rl.question(question));
463
571
  const checkFile = ctx.checkFile ??
@@ -470,11 +578,11 @@ export async function promoteCommand(cwd, flags, files, ctx) {
470
578
  for (const file of chosen) {
471
579
  const rel = relative(cwd, resolve(cwd, file)).replaceAll('\\', '/');
472
580
  if (isProposedLawFile(rel) && !file.startsWith('.tslaws')) {
473
- await promoteFiles({ cwd, ask, out, checkFile }, [rel]);
581
+ await promoteFiles({ cwd, ask, out, checkFile, yes }, [rel]);
474
582
  continue;
475
583
  }
476
584
  try {
477
- await promoteProposal({ cwd, ask, out, checkFile }, file, to);
585
+ await promoteProposal({ cwd, ask, out, checkFile, yes }, file, to);
478
586
  }
479
587
  catch (error) {
480
588
  if (!(error instanceof ProposalError))
@@ -491,20 +599,41 @@ export async function promoteCommand(cwd, flags, files, ctx) {
491
599
  }
492
600
  const list = (projects) => projects.map((p) => (p.path === '' ? '.' : p.path)).join(', ');
493
601
  /** `undefined` for an ordinary single-project run: no project flags, and the directory is not a monorepo root. */
494
- function selectProjects(cwd, only, filter) {
602
+ function selectProjects(cwd, only, filter, changed) {
495
603
  const asked = only.length > 0 || filter.length > 0;
496
604
  const monorepo = isMonorepoRoot(cwd);
497
- if (!asked && !monorepo)
498
- return undefined;
499
- const all = discoverProjects(cwd);
500
- const chosen = asked ? discoverProjects(cwd, { only, filter }) : all;
605
+ if (!asked && !monorepo) {
606
+ if (changed === undefined)
607
+ return undefined;
608
+ const { files } = changedSince(cwd, changed);
609
+ if (files.length > 0)
610
+ return undefined;
611
+ return {
612
+ chosen: [],
613
+ all: [],
614
+ fanOut: false,
615
+ notes: [`--changed ${changed}: nothing changed in this project, nothing to run`],
616
+ };
617
+ }
618
+ // A standalone project ("standalone": true) is in `all`, but a run covers it only when --project names it.
619
+ const all = discoverProjects(cwd, { standalone: true });
620
+ let chosen = asked ? discoverProjects(cwd, { only, filter }) : all.filter((p) => !p.standalone);
501
621
  if (chosen.length === 0) {
502
622
  const named = [...only.map((p) => `--project ${p}`), ...filter.map((g) => `--filter ${g}`)].join(' ');
503
623
  throw new Error(all.length === 0
504
624
  ? 'no tslaws project found here (a project is a directory with a tslaws.json; see "projects" in tslaws.json)'
505
- : `no project matches ${named}; projects: ${list(all)}`);
506
- }
507
- return { chosen, all, fanOut: monorepo || chosen.some((p) => p.path !== '') };
625
+ : asked
626
+ ? `no project matches ${named}; projects: ${list(all)}`
627
+ : `every project here is standalone ("standalone": true), so a root run covers none of them: pick one with --project <dir> (${list(all)})`);
628
+ }
629
+ const notes = [];
630
+ if (changed !== undefined) {
631
+ const { base, files } = changedSince(cwd, changed);
632
+ const reasons = new Map(affectedProjects(cwd, files).map((a) => [a.project.path, a.reason]));
633
+ chosen = chosen.filter((p) => reasons.has(p.path));
634
+ notes.push(`--changed ${changed} (merge-base ${base.slice(0, 8)}, ${files.length} changed file${files.length === 1 ? '' : 's'}): ${chosen.length} of ${all.length} project${all.length === 1 ? '' : 's'} selected`, ...chosen.map((p) => ` ${p.path === '' ? '.' : p.path}: ${reasons.get(p.path)}`));
635
+ }
636
+ return { chosen, all, fanOut: monorepo || chosen.some((p) => p.path !== ''), notes };
508
637
  }
509
638
  /** The projects nested below `project`, relative to it. */
510
639
  function nestedIn(project, all) {
@@ -514,7 +643,7 @@ function nestedIn(project, all) {
514
643
  .map((other) => other.path.slice(prefix.length));
515
644
  }
516
645
  /** Commands that run once for every project of a monorepo; the rest run in one project. */
517
- const fansOut = new Set(['check', 'accept', 'list', 'mutate', 'regressions']);
646
+ const fansOut = new Set(['check', 'accept', 'list', 'mutate', 'regressions', 'security']);
518
647
  /** How a root run lays out machine output: one JSON object keyed by project, or ndjson lines tagged with `project`. */
519
648
  function machineOf(command, flags) {
520
649
  if (command === 'check') {
@@ -523,7 +652,7 @@ function machineOf(command, flags) {
523
652
  throw new Error('--reporter junit writes one XML document per project: pick one project with --project <dir>');
524
653
  return reporter === 'json' || reporter === 'ndjson' ? reporter : 'text';
525
654
  }
526
- return (command === 'list' || command === 'mutate') && flags.has('json') ? 'json' : 'text';
655
+ return (command === 'list' || command === 'mutate' || command === 'security') && flags.has('json') ? 'json' : 'text';
527
656
  }
528
657
  /** One project at a time, each under a `── path ──` header, then one summary line. Nonzero if any project failed. */
529
658
  async function runProjects(selection, machine, run) {
@@ -577,11 +706,21 @@ export async function main(args) {
577
706
  }
578
707
  const { command, flags, files, projects, filters } = parse(args);
579
708
  const cwd = process.cwd();
709
+ if (flags.has('jobs')) {
710
+ const given = Number(flags.get('jobs'));
711
+ if (!Number.isInteger(given) || given < 1) {
712
+ stderrWrite(`--jobs must be an integer of at least 1, got ${JSON.stringify(flags.get('jobs'))}
713
+ `);
714
+ return 1;
715
+ }
716
+ configureJobs({ flag: given });
717
+ }
718
+ const changed = flags.has('changed') ? String(flags.get('changed')) : undefined;
580
719
  // `init --project .` scaffolds right here, in a root that has projects or not.
581
720
  const here = command === 'init' && projects.some((p) => p === '.' || p === './');
582
721
  let selection;
583
722
  try {
584
- selection = here ? undefined : selectProjects(cwd, projects, filters);
723
+ selection = here ? undefined : selectProjects(cwd, projects, filters, changed);
585
724
  }
586
725
  catch (error) {
587
726
  stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
@@ -589,10 +728,22 @@ export async function main(args) {
589
728
  }
590
729
  if (selection === undefined)
591
730
  return runOne(command, flags, files, cwd, direct);
731
+ // The decision goes to stderr so that machine output on stdout stays whole.
732
+ for (const note of selection.notes)
733
+ stderrWrite(`${note}\n`);
734
+ if (selection.chosen.length === 0) {
735
+ if (flags.has('json') || flags.get('reporter') === 'json')
736
+ stdoutWrite('{}\n');
737
+ return 0;
738
+ }
739
+ // From the root with no --project: every project in one process (one comment, one commit for all the locks).
740
+ if (command === 'github' && projects.length === 0 && isMonorepoRoot(cwd))
741
+ return githubRoot(flags, files, cwd, selection);
592
742
  // One project and a reporter that writes one document (junit) runs plainly: there is nothing to join.
593
743
  const oneDocument = command === 'check' && flags.get('reporter') === 'junit' && selection.chosen.length === 1 && !flags.has('watch');
594
744
  if (selection.fanOut && fansOut.has(command) && !flags.has('watch') && !oneDocument) {
595
- if (files.length > 0 && command !== 'regressions') {
745
+ // `security deps` names a subcommand, not a file.
746
+ if (files.length > 0 && command !== 'regressions' && command !== 'security') {
596
747
  stderrWrite(`name files only inside one project: run \`tslaws ${command} ${files[0]}\` there, or pick it with --project <dir>\n`);
597
748
  return 1;
598
749
  }
@@ -613,6 +764,49 @@ export async function main(args) {
613
764
  const [only] = selection.chosen;
614
765
  return runOne(command, flags, files, only.dir, { ...direct, skip: nestedIn(only, selection.all) });
615
766
  }
767
+ /**
768
+ * `tslaws github <mode>` from a monorepo root: every selected project in one run. Each project keeps its own options
769
+ * and its own `github` settings (read in githubCli.ts); the projects nested in another are left out of that one's laws.
770
+ */
771
+ async function githubRoot(flags, files, cwd, selection) {
772
+ const { githubCommand, projectPathOf, joinRepo } = await import("./githubCli.js");
773
+ // The token stays with tslaws, as in a single project (see runOne): laws run in a child that never gets it.
774
+ const env = { ...process.env };
775
+ delete process.env.GITHUB_TOKEN;
776
+ delete process.env.GH_TOKEN;
777
+ const trusted = flags.get('config-from');
778
+ const prefix = projectPathOf(cwd, flags.get('project-path'));
779
+ const optionsOf = (project) => {
780
+ const skip = nestedIn(project, selection.all);
781
+ const chosen = options(project.dir, flags, outside(discover(project.dir, false), skip));
782
+ // With --config-from the projects are a pull request's files, read as data: never run a compiler from among them.
783
+ if (typeof trusted === 'string' && chosen.compiler === checkoutCompiler(project.dir))
784
+ chosen.compiler = checkoutCompiler(resolve(cwd, trusted, project.path)) ?? 'tsc-laws';
785
+ return chosen;
786
+ };
787
+ return githubCommand(files[0], {
788
+ cwd,
789
+ projectPath: prefix,
790
+ options: optionsOf(selection.chosen[0]),
791
+ projects: selection.chosen.map((project) => ({
792
+ cwd: project.dir,
793
+ rel: project.path,
794
+ path: joinRepo(prefix, project.path),
795
+ options: optionsOf(project),
796
+ })),
797
+ discovered: selection.all.map((project) => project.path),
798
+ optionsFor: (rel) => {
799
+ // A directory the files here no longer discover still has the laws it had: merge checks it if the base had it.
800
+ const project = selection.all.find((candidate) => candidate.path === rel) ??
801
+ (existsSync(join(cwd, rel, 'tslaws.json')) ? { dir: join(cwd, rel), path: rel, standalone: false } : undefined);
802
+ return project === undefined ? undefined : optionsOf(project);
803
+ },
804
+ env,
805
+ flags,
806
+ out: (text) => void process.stdout.write(text),
807
+ err: (text) => void process.stderr.write(text),
808
+ });
809
+ }
616
810
  /** One command in one project directory. */
617
811
  async function runOne(command, flags, files, cwd, run) {
618
812
  if (command === 'init') {
@@ -621,8 +815,8 @@ async function runOne(command, flags, files, cwd, run) {
621
815
  }
622
816
  if (command === 'github') {
623
817
  const { githubCommand, projectPathOf } = await import("./githubCli.js");
624
- // The token stays with tslaws: laws run in worker threads and the compiler in a child process, and both get a copy of
625
- // process.env, so a law under test could otherwise read the token and act as the bot.
818
+ // The token stays with tslaws: the laws run in a child process whose environment is an allowlist (see isolate.ts), so
819
+ // a law under test cannot read it from process.env or /proc/self/environ and act as the bot.
626
820
  const env = { ...process.env };
627
821
  delete process.env.GITHUB_TOKEN;
628
822
  delete process.env.GH_TOKEN;
@@ -641,12 +835,18 @@ async function runOne(command, flags, files, cwd, run) {
641
835
  err: (text) => void process.stderr.write(text),
642
836
  });
643
837
  }
838
+ if (command === 'badge')
839
+ return badgeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env }, run);
644
840
  if (command === 'accept')
645
841
  return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
646
842
  if (command === 'delegate')
647
843
  return delegateCommand(cwd, files[0], flags, { isTTY: process.stdin.isTTY === true, env: process.env });
648
844
  if (command === 'migrate')
649
845
  return migrateCommand(cwd, files[0], files.slice(1), flags, (text) => process.stdout.write(text));
846
+ if (command === 'security') {
847
+ const { securityCommand } = await import("./security/cli.js");
848
+ return securityCommand(cwd, files, flags, run.out, undefined, run.skip);
849
+ }
650
850
  if (command === 'mcp')
651
851
  return serveMcp({ cwd, compiler: options(cwd, flags, []).compiler });
652
852
  if (command === 'promote')
@@ -679,6 +879,8 @@ async function runOne(command, flags, files, cwd, run) {
679
879
  compiler: options(cwd, flags, chosen).compiler,
680
880
  max: Number(flags.get('max') ?? 50),
681
881
  seed: flags.has('seed') ? Number(flags.get('seed')) : undefined,
882
+ sandbox: !flags.has('no-sandbox'),
883
+ allowE2e: flags.has('allow-e2e'),
682
884
  onProgress: flags.has('json') ? undefined : (line) => process.stderr.write(`${line}\n`),
683
885
  });
684
886
  run.out(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
@@ -712,7 +914,13 @@ async function runOne(command, flags, files, cwd, run) {
712
914
  open: !flags.has('no-open'),
713
915
  appWindow: !flags.has('tab'),
714
916
  // A watcher sees a browser page only if it stays as the law left it for a moment.
715
- run: (only, onEvent, laws) => check({ ...options(cwd, flags, only ?? chosen), only: laws, onEvent, browserPauseMs: 120 }, !flags.has('proposed')),
917
+ run: (only, onEvent, laws) => check({
918
+ ...options(cwd, flags, only ?? chosen),
919
+ partial: only !== undefined || files.length > 0,
920
+ only: laws,
921
+ onEvent,
922
+ browserPauseMs: 120,
923
+ }, !flags.has('proposed')),
716
924
  log: (line) => process.stdout.write(`${line}\n`),
717
925
  });
718
926
  }
package/dist/compile.d.ts CHANGED
@@ -23,11 +23,21 @@ export declare function readManifest(compiler: string, files: string[], cwd: str
23
23
  * error rather than an arbitrary flag handed to the compiler. `strict` is the one default these can override.
24
24
  */
25
25
  export declare function compilerFlags(options: Record<string, unknown> | undefined): string[];
26
- /** Lowers every `.js` file the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed. */
27
- export declare function lowerEmittedModules(dir: string): void;
28
26
  /**
29
- * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. The
30
- * built-in compiler always reads the project as ES modules and lowers the output. The native compiler does so only for a
31
- * project that uses `import.meta` (it reports TS1343 as CommonJS), so every other project builds exactly as before.
27
+ * Lowers what the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed: `.js` becomes
28
+ * CommonJS and the `import.meta` of a `.mjs` (from a `.mts`, kept as an ES module Node can load) is rewritten in place.
29
+ * `outDir` and `root` say where `dir` sits and what it mirrors, so `import.meta` can name the source. Returns one line
30
+ * per module that cannot be lowered.
31
+ */
32
+ export declare function lowerEmittedModules(dir: string, where?: {
33
+ outDir?: string;
34
+ root?: string;
35
+ }): string[];
36
+ /**
37
+ * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves.
38
+ * Module resolution follows the project's tsconfig (see tsconfigResolve.ts), for the compiler and, through the runtime
39
+ * hooks, for Node when it loads the output. The built-in compiler always reads the project as ES modules and lowers the
40
+ * output. The native compiler does so only for a project that uses `import.meta` (it reports TS1343 as CommonJS), so
41
+ * every other project builds exactly as before.
32
42
  */
33
43
  export declare function build(compiler: string, files: string[], cwd: string): BuildResult;