tslaws 0.9.0 → 1.0.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 (123) hide show
  1. package/README.md +8 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +36 -7
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +215 -28
  14. package/dist/cli.d.ts +4 -0
  15. package/dist/cli.js +324 -41
  16. package/dist/compile.d.ts +17 -1
  17. package/dist/compile.js +244 -25
  18. package/dist/coverage.d.ts +55 -3
  19. package/dist/coverage.js +231 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +70 -0
  54. package/dist/projects.js +457 -0
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +13 -2
  58. package/dist/propertyWorker.js +11 -1
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +32 -0
  63. package/dist/runtimeEnv.js +146 -0
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/env.d.ts +17 -0
  122. package/hooks/claude-hook.mjs +2 -0
  123. package/package.json +22 -6
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,33 +11,45 @@ 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 { affectedProjects, changedSince, discoverProjects, isMonorepoRoot } from "./projects.js";
14
15
  import { promoteFiles, promoteProposal } from "./promote.js";
15
16
  import { addProposal, ProposalError } from "./proposals.js";
16
17
  import { clearCorpus, listCorpus } from "./regressions.js";
17
18
  import { proposalText, reporterNames, reportAs } from "./reporters.js";
18
19
  import { readConfig } from "./coverage.js";
20
+ import { parseGithubConfig } from "./github.js";
19
21
  import { migrateCommand, migrateUsage } from "./migrate/index.js";
20
22
  import { mutate, renderMutation } from "./mutate.js";
21
23
  import { mutateDefaults, resolveSettings } from "./settings.js";
22
24
  import { serveUi } from "./ui.js";
23
25
  import { acceptGate, defaultDuration, describeGrants, fileHash, grantFor, logDelegatedAccept, parseDuration, personOnly, revokeFor, } from "./delegation.js";
24
- import { writeLock } from "./lock.js";
26
+ import { certificateLabel } from "./certificates.js";
27
+ import { fileOfKey, lockFormat, lockOf, mergeScoped, readLock, scopeOf, writeLockValue } from "./lock.js";
25
28
  import { lockLevels } from "./lawKinds.js";
29
+ import { securityUsage } from "./security/cli.js";
30
+ import { plural } from "./plural.js";
31
+ import { configureJobs } from "./pool.js";
26
32
  const usage = `tslaws init [--force] scaffold tslaws.json, .gitignore, AGENTS.md, Claude Code hooks and a starter law (never writes the lock)
27
- 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]
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]
28
34
  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
29
- 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
35
+ 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
30
36
  tslaws regressions [list|clear] show or delete the stored counterexamples (.tslaws/regressions); check replays them first, --no-regressions skips them
31
37
  tslaws accept [files...] record the current laws in tsc-laws.lock (people only: needs a terminal, or a live delegation; never under CI)
32
38
  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)
33
39
  tslaws delegate revoke [--root DIR] withdraw the delegation for a project (people only)
34
40
  tslaws delegate status list delegations and when they end
35
41
  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)
36
- 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
42
+ 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
37
43
  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)
38
- 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)
44
+ 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)
39
45
  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)
40
46
  ${migrateUsage}
47
+ ${securityUsage}
48
+
49
+ 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.
50
+ --project run only in this project directory (repeat it, or comma-separate: --project packages/a,packages/b)
51
+ --filter run only in projects whose path matches this glob (repeatable; a leading ! excludes), for example --filter 'packages/*'
52
+ --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
41
53
 
42
54
  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.
43
55
  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.
@@ -55,6 +67,8 @@ function discover(cwd, proposed) {
55
67
  function parse(args) {
56
68
  const flags = new Map();
57
69
  const files = [];
70
+ const projects = [];
71
+ const filters = [];
58
72
  let command = 'check';
59
73
  const valued = new Set([
60
74
  'runs',
@@ -63,6 +77,7 @@ function parse(args) {
63
77
  'bound',
64
78
  'proof-timeout',
65
79
  'property-timeout',
80
+ 'jobs',
66
81
  'browser',
67
82
  'port',
68
83
  'reporter',
@@ -75,16 +90,31 @@ function parse(args) {
75
90
  'out',
76
91
  'pr',
77
92
  'config-from',
93
+ 'results',
94
+ 'results-out',
78
95
  'head-sha',
79
96
  'rerun-workflow',
80
97
  'protect',
81
98
  'project-path',
99
+ 'fail-on',
100
+ 'changed',
82
101
  ]);
83
102
  for (let i = 0; i < args.length; i += 1) {
84
103
  const arg = args[i];
85
104
  if (arg.startsWith('--')) {
86
105
  const name = arg.slice(2);
87
- if (valued.has(name))
106
+ if (name === 'project') {
107
+ projects.push(...(args[(i += 1)] ?? '')
108
+ .split(',')
109
+ .map((p) => p.trim())
110
+ .filter(Boolean));
111
+ }
112
+ else if (name === 'filter') {
113
+ const glob = args[(i += 1)] ?? '';
114
+ if (glob !== '')
115
+ filters.push(glob);
116
+ }
117
+ else if (valued.has(name))
88
118
  flags.set(name, args[(i += 1)] ?? '');
89
119
  else
90
120
  flags.set(name, true);
@@ -102,12 +132,13 @@ function parse(args) {
102
132
  arg === 'list' ||
103
133
  arg === 'migrate' ||
104
134
  arg === 'delegate' ||
105
- arg === 'github'))
135
+ arg === 'github' ||
136
+ arg === 'security'))
106
137
  command = arg;
107
138
  else
108
139
  files.push(arg);
109
140
  }
110
- return { command, flags, files };
141
+ return { command, flags, files, projects, filters };
111
142
  }
112
143
  function describe(result) {
113
144
  const where = `${result.file}:${result.line}`;
@@ -117,6 +148,8 @@ function describe(result) {
117
148
  lines.push(` ${result.message}`);
118
149
  if (result.assumptions !== undefined && result.assumptions.length > 0)
119
150
  lines.push(` assuming: ${result.assumptions.join('; ')}`);
151
+ if (result.certificate !== undefined)
152
+ lines.push(` certificate: ${certificateLabel(result.certificate)}`);
120
153
  const proposed = proposalText(result);
121
154
  if (proposed !== undefined)
122
155
  lines.push(` ${proposed}`);
@@ -140,11 +173,11 @@ function summarise(result) {
140
173
  .replace(/\s+/g, ' ');
141
174
  return `${result.status.toUpperCase()} ${result.name} (${result.file}:${result.line})${detail === '' ? '' : ` ${detail}`}`;
142
175
  }
143
- function totals(report) {
176
+ export function totals(report) {
144
177
  const count = (status) => report.results.filter((r) => r.status === status).length;
145
- 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`;
178
+ 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')}`;
146
179
  }
147
- function render(report, flags) {
180
+ function render(report, flags, project) {
148
181
  const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
149
182
  if (!reporterNames.includes(reporter)) {
150
183
  throw new Error(`unknown reporter '${reporter}' (expected ${reporterNames.join(', ')})`);
@@ -155,7 +188,7 @@ function render(report, flags) {
155
188
  return `${JSON.stringify({ ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) }, null, 2)}\n`;
156
189
  }
157
190
  if (reporter === 'ndjson') {
158
- return `${JSON.stringify({ type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
191
+ return `${JSON.stringify({ ...(project === undefined ? {} : { project }), type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
159
192
  }
160
193
  let text = '';
161
194
  if (report.compileDiagnostics !== '')
@@ -186,7 +219,17 @@ function options(cwd, flags, chosen) {
186
219
  compiler: String(flags.get('compiler') ?? process.env.TSC_LAWS_BIN ?? bundledCompiler() ?? checkoutCompiler(cwd) ?? 'tsc-laws'),
187
220
  lockFile: join(cwd, 'tsc-laws.lock'),
188
221
  noProve: flags.has('no-prove'),
222
+ // `--certify` turns certificates on (and keeps a "require" from tslaws.json); `--require-certify` makes them required.
223
+ certify: flags.has('require-certify')
224
+ ? 'require'
225
+ : flags.has('certify')
226
+ ? readConfig(cwd).certify === 'require'
227
+ ? 'require'
228
+ : true
229
+ : undefined,
189
230
  noRegressions: flags.has('no-regressions'),
231
+ sandbox: !flags.has('no-sandbox'),
232
+ allowE2e: flags.has('allow-e2e'),
190
233
  only: typeof flags.get('law') === 'string' ? String(flags.get('law')).split(',').filter(Boolean) : undefined,
191
234
  bound: settings.bound,
192
235
  proofTimeoutMs: settings.proofTimeoutMs,
@@ -197,14 +240,19 @@ function options(cwd, flags, chosen) {
197
240
  : undefined,
198
241
  };
199
242
  }
200
- function lawFiles(cwd, flags, files) {
243
+ /** Files outside the directories `skip` (project-relative paths of projects nested in this one). */
244
+ function outside(files, skip) {
245
+ return skip.length === 0 ? files : files.filter((f) => !skip.some((dir) => f === dir || f.startsWith(`${dir}/`)));
246
+ }
247
+ function lawFiles(cwd, flags, files, skip = []) {
201
248
  return files.length > 0
202
249
  ? files.map((f) => relative(cwd, resolve(cwd, f)).replace(/\\/g, '/'))
203
- : discover(cwd, flags.has('proposed'));
250
+ : outside(discover(cwd, flags.has('proposed')), skip);
204
251
  }
252
+ const direct = { out: (text) => void process.stdout.write(text), skip: [] };
205
253
  /** One check of the project. Resolves the exit status. */
206
- async function runCheck(cwd, flags, files) {
207
- const chosen = lawFiles(cwd, flags, files);
254
+ async function runCheck(cwd, flags, files, run = direct) {
255
+ const chosen = lawFiles(cwd, flags, files, run.skip);
208
256
  if (chosen.length === 0) {
209
257
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
210
258
  return 1;
@@ -214,11 +262,11 @@ async function runCheck(cwd, flags, files) {
214
262
  const onEvent = stream
215
263
  ? (event) => {
216
264
  if (event.type !== 'frame')
217
- process.stdout.write(`${JSON.stringify(event)}\n`);
265
+ run.out(`${JSON.stringify(run.tag === undefined ? event : { project: run.tag, ...event })}\n`);
218
266
  }
219
267
  : undefined;
220
- const report = await check({ ...options(cwd, flags, chosen), onEvent }, !flags.has('proposed'));
221
- process.stdout.write(render(report, flags));
268
+ const report = await check({ ...options(cwd, flags, chosen), partial: files.length > 0, onEvent }, !flags.has('proposed'));
269
+ run.out(render(report, flags, run.tag));
222
270
  return report.ok ? 0 : 1;
223
271
  }
224
272
  export function watched(filename) {
@@ -279,13 +327,15 @@ const stderrWrite = (text) => void process.stderr.write(text);
279
327
  export async function acceptCommand(cwd, flags, files, ctx) {
280
328
  const out = ctx.out ?? stdoutWrite;
281
329
  const err = ctx.err ?? stderrWrite;
282
- const chosen = lawFiles(cwd, flags, files);
330
+ const chosen = lawFiles(cwd, flags, files, ctx.skip);
283
331
  if (chosen.length === 0) {
284
332
  err('no laws files found (looking for *.laws.ts)\n');
285
333
  return 1;
286
334
  }
287
- if (readConfig(cwd).github !== undefined) {
288
- 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');
335
+ // A project that accepts laws on GitHub still lets a person accept by hand, unless it sets "github.local" to false.
336
+ const github = readConfig(cwd).github;
337
+ if (github !== undefined && !parseGithubConfig(github).local) {
338
+ 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');
289
339
  return 1;
290
340
  }
291
341
  const gate = acceptGate({ isTTY: ctx.isTTY, env: ctx.env, root: cwd, now: ctx.now, home: ctx.home });
@@ -295,7 +345,7 @@ export async function acceptCommand(cwd, flags, files, ctx) {
295
345
  }
296
346
  const opts = options(cwd, flags, chosen);
297
347
  const laws = readManifest(opts.compiler, opts.files, cwd);
298
- out(`${laws.length} laws in ${chosen.length} files:\n${laws.map((l) => ` ${l.file}:${l.line} ${l.name}`).join('\n')}\n`);
348
+ out(`${plural(laws.length, 'law')} in ${plural(chosen.length, 'file')}:\n${laws.map((l) => ` ${l.file}:${l.line} ${l.name}`).join('\n')}\n`);
299
349
  if (!gate.delegated) {
300
350
  const rl = createInterface({ input: process.stdin, output: process.stdout });
301
351
  const answer = await rl.question('Write tsc-laws.lock? Type accept, yes or y to confirm: ');
@@ -313,7 +363,22 @@ export async function acceptCommand(cwd, flags, files, ctx) {
313
363
  // tslaws/browser reads as tampered until a person accepts again. By name (the default) the lock is unchanged.
314
364
  const mode = readConfig(cwd).levels ?? 'names';
315
365
  const levels = lockLevels(cwd, laws, mode);
316
- writeLock(opts.lockFile, laws, exempt, levels);
366
+ // Certificates enter the lock only for the proofs and problems of this run; see certificatesToAccept.
367
+ // Naming files accepts only those: the lock keeps every entry it has for the other files.
368
+ const held = readLock(opts.lockFile);
369
+ // The entries a partial accept keeps for the other files were hashed in the old format; keeping them under the new
370
+ // version would make every one of them read as changed. Only a full accept can write the whole lock again.
371
+ if (files.length > 0 && held !== undefined && (held.version ?? lockFormat) < lockFormat) {
372
+ 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');
373
+ return 1;
374
+ }
375
+ const scope = scopeOf(chosen);
376
+ const heldHere = files.length === 0
377
+ ? held?.certificates
378
+ : Object.fromEntries(Object.entries(held?.certificates ?? {}).filter(([key]) => scope.has(fileOfKey(key))));
379
+ const certificates = await certificatesToAccept(opts, laws, heldHere, out);
380
+ const next = lockOf(laws, exempt, levels, certificates);
381
+ writeLockValue(opts.lockFile, files.length === 0 ? next : mergeScoped(held, scope, next));
317
382
  out('tsc-laws.lock written\n');
318
383
  if (gate.delegated) {
319
384
  logDelegatedAccept(cwd, gate.grant, before, fileHash(opts.lockFile), ctx.now ?? new Date());
@@ -435,6 +500,7 @@ export async function promoteCommand(cwd, flags, files, ctx) {
435
500
  err('--to takes one path, for one proposal\n');
436
501
  return 1;
437
502
  }
503
+ const yes = flags.get('yes') === true;
438
504
  const rl = ctx.ask === undefined ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
439
505
  const ask = ctx.ask ?? ((question) => rl.question(question));
440
506
  const checkFile = ctx.checkFile ??
@@ -447,11 +513,11 @@ export async function promoteCommand(cwd, flags, files, ctx) {
447
513
  for (const file of chosen) {
448
514
  const rel = relative(cwd, resolve(cwd, file)).replaceAll('\\', '/');
449
515
  if (isProposedLawFile(rel) && !file.startsWith('.tslaws')) {
450
- await promoteFiles({ cwd, ask, out, checkFile }, [rel]);
516
+ await promoteFiles({ cwd, ask, out, checkFile, yes }, [rel]);
451
517
  continue;
452
518
  }
453
519
  try {
454
- await promoteProposal({ cwd, ask, out, checkFile }, file, to);
520
+ await promoteProposal({ cwd, ask, out, checkFile, yes }, file, to);
455
521
  }
456
522
  catch (error) {
457
523
  if (!(error instanceof ProposalError))
@@ -466,21 +532,226 @@ export async function promoteCommand(cwd, flags, files, ctx) {
466
532
  }
467
533
  return 0;
468
534
  }
535
+ const list = (projects) => projects.map((p) => (p.path === '' ? '.' : p.path)).join(', ');
536
+ /** `undefined` for an ordinary single-project run: no project flags, and the directory is not a monorepo root. */
537
+ function selectProjects(cwd, only, filter, changed) {
538
+ const asked = only.length > 0 || filter.length > 0;
539
+ const monorepo = isMonorepoRoot(cwd);
540
+ if (!asked && !monorepo) {
541
+ if (changed === undefined)
542
+ return undefined;
543
+ const { files } = changedSince(cwd, changed);
544
+ if (files.length > 0)
545
+ return undefined;
546
+ return {
547
+ chosen: [],
548
+ all: [],
549
+ fanOut: false,
550
+ notes: [`--changed ${changed}: nothing changed in this project, nothing to run`],
551
+ };
552
+ }
553
+ // A standalone project ("standalone": true) is in `all`, but a run covers it only when --project names it.
554
+ const all = discoverProjects(cwd, { standalone: true });
555
+ let chosen = asked ? discoverProjects(cwd, { only, filter }) : all.filter((p) => !p.standalone);
556
+ if (chosen.length === 0) {
557
+ const named = [...only.map((p) => `--project ${p}`), ...filter.map((g) => `--filter ${g}`)].join(' ');
558
+ throw new Error(all.length === 0
559
+ ? 'no tslaws project found here (a project is a directory with a tslaws.json; see "projects" in tslaws.json)'
560
+ : asked
561
+ ? `no project matches ${named}; projects: ${list(all)}`
562
+ : `every project here is standalone ("standalone": true), so a root run covers none of them: pick one with --project <dir> (${list(all)})`);
563
+ }
564
+ const notes = [];
565
+ if (changed !== undefined) {
566
+ const { base, files } = changedSince(cwd, changed);
567
+ const reasons = new Map(affectedProjects(cwd, files).map((a) => [a.project.path, a.reason]));
568
+ chosen = chosen.filter((p) => reasons.has(p.path));
569
+ 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)}`));
570
+ }
571
+ return { chosen, all, fanOut: monorepo || chosen.some((p) => p.path !== ''), notes };
572
+ }
573
+ /** The projects nested below `project`, relative to it. */
574
+ function nestedIn(project, all) {
575
+ const prefix = project.path === '' ? '' : `${project.path}/`;
576
+ return all
577
+ .filter((other) => other.path !== project.path && other.path.startsWith(prefix))
578
+ .map((other) => other.path.slice(prefix.length));
579
+ }
580
+ /** Commands that run once for every project of a monorepo; the rest run in one project. */
581
+ const fansOut = new Set(['check', 'accept', 'list', 'mutate', 'regressions', 'security']);
582
+ /** How a root run lays out machine output: one JSON object keyed by project, or ndjson lines tagged with `project`. */
583
+ function machineOf(command, flags) {
584
+ if (command === 'check') {
585
+ const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
586
+ if (reporter === 'junit')
587
+ throw new Error('--reporter junit writes one XML document per project: pick one project with --project <dir>');
588
+ return reporter === 'json' || reporter === 'ndjson' ? reporter : 'text';
589
+ }
590
+ return (command === 'list' || command === 'mutate' || command === 'security') && flags.has('json') ? 'json' : 'text';
591
+ }
592
+ /** One project at a time, each under a `── path ──` header, then one summary line. Nonzero if any project failed. */
593
+ async function runProjects(selection, machine, run) {
594
+ const failed = [];
595
+ const keyed = {};
596
+ for (const [index, project] of selection.chosen.entries()) {
597
+ const label = project.path === '' ? '.' : project.path;
598
+ let buffer = '';
599
+ const io = {
600
+ out: machine === 'json' ? (text) => void (buffer += text) : stdoutWrite,
601
+ skip: nestedIn(project, selection.all),
602
+ tag: machine === 'ndjson' ? label : undefined,
603
+ };
604
+ if (machine === 'text')
605
+ stdoutWrite(`${index === 0 ? '' : '\n'}── ${label} ──\n`);
606
+ let status;
607
+ let problem;
608
+ try {
609
+ status = await run(project, io);
610
+ }
611
+ catch (error) {
612
+ problem = error instanceof Error ? error.message : String(error);
613
+ stderrWrite(`${label}: ${problem}\n`);
614
+ status = 1;
615
+ }
616
+ if (status !== 0)
617
+ failed.push(label);
618
+ if (machine === 'json') {
619
+ try {
620
+ keyed[label] = buffer === '' ? { error: problem ?? 'no output (see stderr)' } : JSON.parse(buffer);
621
+ }
622
+ catch {
623
+ keyed[label] = { error: problem ?? 'output was not JSON' };
624
+ }
625
+ }
626
+ }
627
+ if (machine === 'json')
628
+ stdoutWrite(`${JSON.stringify(keyed, null, 2)}\n`);
629
+ const count = selection.chosen.length;
630
+ const summary = `${count} project${count === 1 ? '' : 's'}, ${failed.length} failed${failed.length === 0 ? '' : ` (${failed.join(', ')})`}\n`;
631
+ if (machine === 'text')
632
+ stdoutWrite(`\n${summary}`);
633
+ else
634
+ stderrWrite(summary);
635
+ return failed.length === 0 ? 0 : 1;
636
+ }
469
637
  export async function main(args) {
470
638
  if (args.includes('--help') || args.includes('-h')) {
471
639
  process.stdout.write(`${usage}\n`);
472
640
  return 0;
473
641
  }
474
- const { command, flags, files } = parse(args);
642
+ const { command, flags, files, projects, filters } = parse(args);
475
643
  const cwd = process.cwd();
644
+ if (flags.has('jobs')) {
645
+ const given = Number(flags.get('jobs'));
646
+ if (!Number.isInteger(given) || given < 1) {
647
+ stderrWrite(`--jobs must be an integer of at least 1, got ${JSON.stringify(flags.get('jobs'))}
648
+ `);
649
+ return 1;
650
+ }
651
+ configureJobs({ flag: given });
652
+ }
653
+ const changed = flags.has('changed') ? String(flags.get('changed')) : undefined;
654
+ // `init --project .` scaffolds right here, in a root that has projects or not.
655
+ const here = command === 'init' && projects.some((p) => p === '.' || p === './');
656
+ let selection;
657
+ try {
658
+ selection = here ? undefined : selectProjects(cwd, projects, filters, changed);
659
+ }
660
+ catch (error) {
661
+ stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
662
+ return 1;
663
+ }
664
+ if (selection === undefined)
665
+ return runOne(command, flags, files, cwd, direct);
666
+ // The decision goes to stderr so that machine output on stdout stays whole.
667
+ for (const note of selection.notes)
668
+ stderrWrite(`${note}\n`);
669
+ if (selection.chosen.length === 0) {
670
+ if (flags.has('json') || flags.get('reporter') === 'json')
671
+ stdoutWrite('{}\n');
672
+ return 0;
673
+ }
674
+ // From the root with no --project: every project in one process (one comment, one commit for all the locks).
675
+ if (command === 'github' && projects.length === 0 && isMonorepoRoot(cwd))
676
+ return githubRoot(flags, files, cwd, selection);
677
+ // One project and a reporter that writes one document (junit) runs plainly: there is nothing to join.
678
+ const oneDocument = command === 'check' && flags.get('reporter') === 'junit' && selection.chosen.length === 1 && !flags.has('watch');
679
+ if (selection.fanOut && fansOut.has(command) && !flags.has('watch') && !oneDocument) {
680
+ // `security deps` names a subcommand, not a file.
681
+ if (files.length > 0 && command !== 'regressions' && command !== 'security') {
682
+ stderrWrite(`name files only inside one project: run \`tslaws ${command} ${files[0]}\` there, or pick it with --project <dir>\n`);
683
+ return 1;
684
+ }
685
+ let machine;
686
+ try {
687
+ machine = machineOf(command, flags);
688
+ }
689
+ catch (error) {
690
+ stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
691
+ return 1;
692
+ }
693
+ return runProjects(selection, machine, (project, io) => runOne(command, flags, files, project.dir, io));
694
+ }
695
+ if (selection.chosen.length > 1) {
696
+ stderrWrite(`tslaws ${flags.has('watch') ? 'check --watch' : command} runs in one project and this repository has ${selection.chosen.length}: pick one with --project <dir> (${list(selection.chosen)})${command === 'init' ? ', or --project . to scaffold here' : ''}\n`);
697
+ return 1;
698
+ }
699
+ const [only] = selection.chosen;
700
+ return runOne(command, flags, files, only.dir, { ...direct, skip: nestedIn(only, selection.all) });
701
+ }
702
+ /**
703
+ * `tslaws github <mode>` from a monorepo root: every selected project in one run. Each project keeps its own options
704
+ * and its own `github` settings (read in githubCli.ts); the projects nested in another are left out of that one's laws.
705
+ */
706
+ async function githubRoot(flags, files, cwd, selection) {
707
+ const { githubCommand, projectPathOf, joinRepo } = await import("./githubCli.js");
708
+ // The token stays with tslaws, as in a single project (see runOne): laws run in a child that never gets it.
709
+ const env = { ...process.env };
710
+ delete process.env.GITHUB_TOKEN;
711
+ delete process.env.GH_TOKEN;
712
+ const trusted = flags.get('config-from');
713
+ const prefix = projectPathOf(cwd, flags.get('project-path'));
714
+ const optionsOf = (project) => {
715
+ const skip = nestedIn(project, selection.all);
716
+ const chosen = options(project.dir, flags, outside(discover(project.dir, false), skip));
717
+ // With --config-from the projects are a pull request's files, read as data: never run a compiler from among them.
718
+ if (typeof trusted === 'string' && chosen.compiler === checkoutCompiler(project.dir))
719
+ chosen.compiler = checkoutCompiler(resolve(cwd, trusted, project.path)) ?? 'tsc-laws';
720
+ return chosen;
721
+ };
722
+ return githubCommand(files[0], {
723
+ cwd,
724
+ projectPath: prefix,
725
+ options: optionsOf(selection.chosen[0]),
726
+ projects: selection.chosen.map((project) => ({
727
+ cwd: project.dir,
728
+ rel: project.path,
729
+ path: joinRepo(prefix, project.path),
730
+ options: optionsOf(project),
731
+ })),
732
+ discovered: selection.all.map((project) => project.path),
733
+ optionsFor: (rel) => {
734
+ // A directory the files here no longer discover still has the laws it had: merge checks it if the base had it.
735
+ const project = selection.all.find((candidate) => candidate.path === rel) ??
736
+ (existsSync(join(cwd, rel, 'tslaws.json')) ? { dir: join(cwd, rel), path: rel, standalone: false } : undefined);
737
+ return project === undefined ? undefined : optionsOf(project);
738
+ },
739
+ env,
740
+ flags,
741
+ out: (text) => void process.stdout.write(text),
742
+ err: (text) => void process.stderr.write(text),
743
+ });
744
+ }
745
+ /** One command in one project directory. */
746
+ async function runOne(command, flags, files, cwd, run) {
476
747
  if (command === 'init') {
477
748
  process.stdout.write(`${init({ cwd, force: flags.has('force') }).join('\n')}\n\n${nextStep}\n`);
478
749
  return 0;
479
750
  }
480
751
  if (command === 'github') {
481
752
  const { githubCommand, projectPathOf } = await import("./githubCli.js");
482
- // The token stays with tslaws: laws run in worker threads and the compiler in a child process, and both get a copy of
483
- // process.env, so a law under test could otherwise read the token and act as the bot.
753
+ // The token stays with tslaws: the laws run in a child process whose environment is an allowlist (see isolate.ts), so
754
+ // a law under test cannot read it from process.env or /proc/self/environ and act as the bot.
484
755
  const env = { ...process.env };
485
756
  delete process.env.GITHUB_TOKEN;
486
757
  delete process.env.GH_TOKEN;
@@ -500,25 +771,29 @@ export async function main(args) {
500
771
  });
501
772
  }
502
773
  if (command === 'accept')
503
- return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
774
+ return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
504
775
  if (command === 'delegate')
505
776
  return delegateCommand(cwd, files[0], flags, { isTTY: process.stdin.isTTY === true, env: process.env });
506
777
  if (command === 'migrate')
507
778
  return migrateCommand(cwd, files[0], files.slice(1), flags, (text) => process.stdout.write(text));
779
+ if (command === 'security') {
780
+ const { securityCommand } = await import("./security/cli.js");
781
+ return securityCommand(cwd, files, flags, run.out, undefined, run.skip);
782
+ }
508
783
  if (command === 'mcp')
509
784
  return serveMcp({ cwd, compiler: options(cwd, flags, []).compiler });
510
785
  if (command === 'promote')
511
786
  return promoteCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
512
787
  if (command === 'list') {
513
- const listed = listLawFiles(cwd);
514
- process.stdout.write(flags.has('json') ? `${JSON.stringify({ files: listed }, null, 2)}\n` : renderList(listed));
788
+ const listed = listLawFiles(cwd).filter((f) => outside([f.file], run.skip).length > 0);
789
+ run.out(flags.has('json') ? `${JSON.stringify({ files: listed }, null, 2)}\n` : renderList(listed));
515
790
  return 0;
516
791
  }
517
792
  if (command === 'propose')
518
793
  return proposeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
519
794
  if (command === 'mutate') {
520
795
  // *.laws.ts arguments choose the laws; other files restrict which covered sources are mutated.
521
- const chosen = lawFiles(cwd, flags, files.filter((f) => f.endsWith('.laws.ts')));
796
+ const chosen = lawFiles(cwd, flags, files.filter((f) => f.endsWith('.laws.ts')), run.skip);
522
797
  if (chosen.length === 0) {
523
798
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
524
799
  return 1;
@@ -537,15 +812,17 @@ export async function main(args) {
537
812
  compiler: options(cwd, flags, chosen).compiler,
538
813
  max: Number(flags.get('max') ?? 50),
539
814
  seed: flags.has('seed') ? Number(flags.get('seed')) : undefined,
815
+ sandbox: !flags.has('no-sandbox'),
816
+ allowE2e: flags.has('allow-e2e'),
540
817
  onProgress: flags.has('json') ? undefined : (line) => process.stderr.write(`${line}\n`),
541
818
  });
542
- process.stdout.write(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
819
+ run.out(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
543
820
  return report.ok ? 0 : 1;
544
821
  }
545
822
  if (command === 'regressions') {
546
823
  const action = files[0] ?? 'list';
547
824
  if (action === 'clear') {
548
- process.stdout.write(clearCorpus(cwd) ? 'cleared .tslaws/regressions\n' : 'no regression corpus to clear\n');
825
+ run.out(clearCorpus(cwd) ? 'cleared .tslaws/regressions\n' : 'no regression corpus to clear\n');
549
826
  return 0;
550
827
  }
551
828
  if (action !== 'list') {
@@ -553,13 +830,13 @@ export async function main(args) {
553
830
  return 1;
554
831
  }
555
832
  const corpus = listCorpus(cwd);
556
- process.stdout.write(corpus.length === 0
833
+ run.out(corpus.length === 0
557
834
  ? 'no stored counterexamples\n'
558
835
  : `${corpus.map((e) => `${e.file} ${e.law}: ${e.count} example${e.count === 1 ? '' : 's'}`).join('\n')}\n`);
559
836
  return 0;
560
837
  }
561
838
  if (command === 'ui') {
562
- const chosen = lawFiles(cwd, flags, files);
839
+ const chosen = lawFiles(cwd, flags, files, run.skip);
563
840
  if (chosen.length === 0) {
564
841
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
565
842
  return 1;
@@ -570,9 +847,15 @@ export async function main(args) {
570
847
  open: !flags.has('no-open'),
571
848
  appWindow: !flags.has('tab'),
572
849
  // A watcher sees a browser page only if it stays as the law left it for a moment.
573
- run: (only, onEvent, laws) => check({ ...options(cwd, flags, only ?? chosen), only: laws, onEvent, browserPauseMs: 120 }, !flags.has('proposed')),
850
+ run: (only, onEvent, laws) => check({
851
+ ...options(cwd, flags, only ?? chosen),
852
+ partial: only !== undefined || files.length > 0,
853
+ only: laws,
854
+ onEvent,
855
+ browserPauseMs: 120,
856
+ }, !flags.has('proposed')),
574
857
  log: (line) => process.stdout.write(`${line}\n`),
575
858
  });
576
859
  }
577
- return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files);
860
+ return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files, run);
578
861
  }
package/dist/compile.d.ts CHANGED
@@ -23,5 +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
- /** Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. */
26
+ /**
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.
42
+ */
27
43
  export declare function build(compiler: string, files: string[], cwd: string): BuildResult;