tslaws 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/browser.js +11 -2
- package/dist/check.js +4 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +163 -21
- package/dist/compile.d.ts +7 -1
- package/dist/compile.js +95 -5
- package/dist/coverage.d.ts +17 -2
- package/dist/coverage.js +147 -10
- package/dist/projects.d.ts +28 -0
- package/dist/projects.js +185 -0
- package/dist/property.js +8 -1
- package/dist/propertyWorker.js +4 -1
- package/dist/runtimeEnv.d.ts +24 -0
- package/dist/runtimeEnv.js +108 -0
- package/env.d.ts +17 -0
- package/package.json +10 -6
package/README.md
CHANGED
|
@@ -167,6 +167,7 @@ See [docs/laws.md](../../docs/laws.md#the-dashboard).
|
|
|
167
167
|
`tslaws mutate [files...] [--max N] [--seed N] [--json]` mutation-tests the laws: it mutates the covered code, re-runs the laws against each mutant, and lists the survivors no law caught. It handles `.tsx`/`.jsx` and projects with a lock, and takes the run flags of `check`. See [docs/laws.md](../../docs/laws.md#mutation-testing).
|
|
168
168
|
|
|
169
169
|
- **Other source formats:** `tslaws.json` `bundlerPlugins` lists esbuild plugin modules (paths relative to the file) that teach the browser bundler formats like `.tsrx`. See [docs/laws.md](../../docs/laws.md#bundler-plugins).
|
|
170
|
+
- **Bundler-style source:** `import.meta.env` works in laws, in the code they reach and in browser pages (`tslaws.json` `env` adds or overrides entries), and a TypeScript dependency may import its own files without extensions. See [docs/laws.md](../../docs/laws.md#source-written-for-a-bundler).
|
|
170
171
|
- **Settings:** `tslaws.json` `runs`, `bound`, `proofTimeoutMs` and `propertyTimeoutMs` set the run defaults; a command line flag beats them. `"solvers": ["z3", "cvc5"]` makes cvc5 confirm every Z3 proof (set `TSLAWS_CVC5` to its path, or put it on the PATH). See [docs/laws.md](../../docs/laws.md#settings).
|
|
171
172
|
|
|
172
173
|
## Agents cannot move the goalposts
|
package/dist/browser.js
CHANGED
|
@@ -5,7 +5,8 @@ import { mkdirSync } from 'node:fs';
|
|
|
5
5
|
import { delimiter, join, relative as pathRelative, resolve, sep } from 'node:path';
|
|
6
6
|
import { build as bundleWith } from 'esbuild';
|
|
7
7
|
import { explainBundleError, loadBundlerPlugins } from "./bundlerPlugins.js";
|
|
8
|
-
import { readConfig } from "./coverage.js";
|
|
8
|
+
import { lawEnv, readConfig } from "./coverage.js";
|
|
9
|
+
import { importMetaEnvGlobal } from "./runtimeEnv.js";
|
|
9
10
|
import { chromium, firefox, webkit } from 'playwright-core';
|
|
10
11
|
import { toWire } from "./generators.js";
|
|
11
12
|
import { runProperty, summarise } from "./property.js";
|
|
@@ -207,7 +208,12 @@ async function bundleOf(jsFile, cwd) {
|
|
|
207
208
|
target: 'es2022',
|
|
208
209
|
absWorkingDir: cwd,
|
|
209
210
|
logLevel: 'silent',
|
|
210
|
-
|
|
211
|
+
// A dependency's `import.meta.env` reads the same global the compiled laws do; the page sets it before the bundle.
|
|
212
|
+
define: {
|
|
213
|
+
'process.env.NODE_ENV': '"development"',
|
|
214
|
+
global: 'globalThis',
|
|
215
|
+
'import.meta.env': `globalThis.${importMetaEnvGlobal}`,
|
|
216
|
+
},
|
|
211
217
|
});
|
|
212
218
|
const emitted = (extension) => result.outputFiles
|
|
213
219
|
.filter((file) => file.path.endsWith(extension))
|
|
@@ -266,6 +272,9 @@ export async function runBrowserLaw(law, options) {
|
|
|
266
272
|
// The stylesheet goes in before the script runs, as a linked one would.
|
|
267
273
|
if (css !== '')
|
|
268
274
|
await page.addStyleTag({ content: css });
|
|
275
|
+
await page.addScriptTag({
|
|
276
|
+
content: `globalThis.${importMetaEnvGlobal} = ${JSON.stringify(lawEnv(options.cwd, 'browser'))};`,
|
|
277
|
+
});
|
|
269
278
|
await page.addScriptTag({ content: code });
|
|
270
279
|
await page.addScriptTag({ content: harness });
|
|
271
280
|
const call = async (...args) => {
|
package/dist/check.js
CHANGED
|
@@ -3,11 +3,12 @@ import { resolve } from 'node:path';
|
|
|
3
3
|
import ts from 'typescript';
|
|
4
4
|
import { build, readManifest } from "./compile.js";
|
|
5
5
|
import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, warmWorkers, typesOf, } from "./property.js";
|
|
6
|
-
import { analyzeCoverage, coverFiles, readConfig } from "./coverage.js";
|
|
6
|
+
import { analyzeCoverage, coverFiles, lawEnv, readConfig } from "./coverage.js";
|
|
7
7
|
import { derivedStore } from "./derived.js";
|
|
8
8
|
import { jobs } from "./pool.js";
|
|
9
9
|
import { compareLock, lawKey, readLock } from "./lock.js";
|
|
10
10
|
import { crossCheck, disagreement } from "./propertyRun.js";
|
|
11
|
+
import { prepareRuntime } from "./runtimeEnv.js";
|
|
11
12
|
import { proveLaw } from "./smt.js";
|
|
12
13
|
import { decodeExample, loadExamples, regressionMessage, saveExample } from "./regressions.js";
|
|
13
14
|
import { closeBrowser, runBrowserLaw } from "./browser.js";
|
|
@@ -184,6 +185,8 @@ export async function check(options, enforceLock) {
|
|
|
184
185
|
const program = () => (programOf ??= built.program ?? ts.createProgram(declarationFiles(built.outDir), compilerOptions));
|
|
185
186
|
const sourceCwd = built.program === undefined ? undefined : options.cwd;
|
|
186
187
|
const require = createRequire(import.meta.url);
|
|
188
|
+
// Laws that run here (end to end) and the code they load read `import.meta.env` and extensionless imports as bundled.
|
|
189
|
+
prepareRuntime(lawEnv(options.cwd, 'node'));
|
|
187
190
|
const runOne = async (law, index) => {
|
|
188
191
|
const buffered = [];
|
|
189
192
|
try {
|
package/dist/cli.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface CommandContext {
|
|
|
7
7
|
now?: Date;
|
|
8
8
|
out?: (text: string) => void;
|
|
9
9
|
err?: (text: string) => void;
|
|
10
|
+
/** Projects nested below `cwd`, project-relative: their laws are not this project's (set by a root run). */
|
|
11
|
+
skip?: string[];
|
|
10
12
|
}
|
|
11
13
|
export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
|
|
12
14
|
/** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
|
package/dist/cli.js
CHANGED
|
@@ -11,6 +11,7 @@ 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
15
|
import { promoteFiles, promoteProposal } from "./promote.js";
|
|
15
16
|
import { addProposal, ProposalError } from "./proposals.js";
|
|
16
17
|
import { clearCorpus, listCorpus } from "./regressions.js";
|
|
@@ -39,6 +40,10 @@ tslaws github report|command|merge|verify accept laws on GitHub: flag and run
|
|
|
39
40
|
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
41
|
${migrateUsage}
|
|
41
42
|
|
|
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.
|
|
44
|
+
--project run only in this project directory (repeat it, or comma-separate: --project packages/a,packages/b)
|
|
45
|
+
--filter run only in projects whose path matches this glob (repeatable; a leading ! excludes), for example --filter 'packages/*'
|
|
46
|
+
|
|
42
47
|
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
48
|
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.
|
|
44
49
|
Exit status is 0 only when every law is proved, bounded or tested and nothing is open, failed, uncovered or tampered with.
|
|
@@ -55,6 +60,8 @@ function discover(cwd, proposed) {
|
|
|
55
60
|
function parse(args) {
|
|
56
61
|
const flags = new Map();
|
|
57
62
|
const files = [];
|
|
63
|
+
const projects = [];
|
|
64
|
+
const filters = [];
|
|
58
65
|
let command = 'check';
|
|
59
66
|
const valued = new Set([
|
|
60
67
|
'runs',
|
|
@@ -84,7 +91,18 @@ function parse(args) {
|
|
|
84
91
|
const arg = args[i];
|
|
85
92
|
if (arg.startsWith('--')) {
|
|
86
93
|
const name = arg.slice(2);
|
|
87
|
-
if (
|
|
94
|
+
if (name === 'project') {
|
|
95
|
+
projects.push(...(args[(i += 1)] ?? '')
|
|
96
|
+
.split(',')
|
|
97
|
+
.map((p) => p.trim())
|
|
98
|
+
.filter(Boolean));
|
|
99
|
+
}
|
|
100
|
+
else if (name === 'filter') {
|
|
101
|
+
const glob = args[(i += 1)] ?? '';
|
|
102
|
+
if (glob !== '')
|
|
103
|
+
filters.push(glob);
|
|
104
|
+
}
|
|
105
|
+
else if (valued.has(name))
|
|
88
106
|
flags.set(name, args[(i += 1)] ?? '');
|
|
89
107
|
else
|
|
90
108
|
flags.set(name, true);
|
|
@@ -107,7 +125,7 @@ function parse(args) {
|
|
|
107
125
|
else
|
|
108
126
|
files.push(arg);
|
|
109
127
|
}
|
|
110
|
-
return { command, flags, files };
|
|
128
|
+
return { command, flags, files, projects, filters };
|
|
111
129
|
}
|
|
112
130
|
function describe(result) {
|
|
113
131
|
const where = `${result.file}:${result.line}`;
|
|
@@ -144,7 +162,7 @@ function totals(report) {
|
|
|
144
162
|
const count = (status) => report.results.filter((r) => r.status === status).length;
|
|
145
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`;
|
|
146
164
|
}
|
|
147
|
-
function render(report, flags) {
|
|
165
|
+
function render(report, flags, project) {
|
|
148
166
|
const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
|
|
149
167
|
if (!reporterNames.includes(reporter)) {
|
|
150
168
|
throw new Error(`unknown reporter '${reporter}' (expected ${reporterNames.join(', ')})`);
|
|
@@ -155,7 +173,7 @@ function render(report, flags) {
|
|
|
155
173
|
return `${JSON.stringify({ ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) }, null, 2)}\n`;
|
|
156
174
|
}
|
|
157
175
|
if (reporter === 'ndjson') {
|
|
158
|
-
return `${JSON.stringify({ type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
|
|
176
|
+
return `${JSON.stringify({ ...(project === undefined ? {} : { project }), type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
|
|
159
177
|
}
|
|
160
178
|
let text = '';
|
|
161
179
|
if (report.compileDiagnostics !== '')
|
|
@@ -197,14 +215,19 @@ function options(cwd, flags, chosen) {
|
|
|
197
215
|
: undefined,
|
|
198
216
|
};
|
|
199
217
|
}
|
|
200
|
-
|
|
218
|
+
/** Files outside the directories `skip` (project-relative paths of projects nested in this one). */
|
|
219
|
+
function outside(files, skip) {
|
|
220
|
+
return skip.length === 0 ? files : files.filter((f) => !skip.some((dir) => f === dir || f.startsWith(`${dir}/`)));
|
|
221
|
+
}
|
|
222
|
+
function lawFiles(cwd, flags, files, skip = []) {
|
|
201
223
|
return files.length > 0
|
|
202
224
|
? files.map((f) => relative(cwd, resolve(cwd, f)).replace(/\\/g, '/'))
|
|
203
|
-
: discover(cwd, flags.has('proposed'));
|
|
225
|
+
: outside(discover(cwd, flags.has('proposed')), skip);
|
|
204
226
|
}
|
|
227
|
+
const direct = { out: (text) => void process.stdout.write(text), skip: [] };
|
|
205
228
|
/** One check of the project. Resolves the exit status. */
|
|
206
|
-
async function runCheck(cwd, flags, files) {
|
|
207
|
-
const chosen = lawFiles(cwd, flags, files);
|
|
229
|
+
async function runCheck(cwd, flags, files, run = direct) {
|
|
230
|
+
const chosen = lawFiles(cwd, flags, files, run.skip);
|
|
208
231
|
if (chosen.length === 0) {
|
|
209
232
|
process.stderr.write('no laws files found (looking for *.laws.ts)\n');
|
|
210
233
|
return 1;
|
|
@@ -214,11 +237,11 @@ async function runCheck(cwd, flags, files) {
|
|
|
214
237
|
const onEvent = stream
|
|
215
238
|
? (event) => {
|
|
216
239
|
if (event.type !== 'frame')
|
|
217
|
-
|
|
240
|
+
run.out(`${JSON.stringify(run.tag === undefined ? event : { project: run.tag, ...event })}\n`);
|
|
218
241
|
}
|
|
219
242
|
: undefined;
|
|
220
243
|
const report = await check({ ...options(cwd, flags, chosen), onEvent }, !flags.has('proposed'));
|
|
221
|
-
|
|
244
|
+
run.out(render(report, flags, run.tag));
|
|
222
245
|
return report.ok ? 0 : 1;
|
|
223
246
|
}
|
|
224
247
|
export function watched(filename) {
|
|
@@ -279,7 +302,7 @@ const stderrWrite = (text) => void process.stderr.write(text);
|
|
|
279
302
|
export async function acceptCommand(cwd, flags, files, ctx) {
|
|
280
303
|
const out = ctx.out ?? stdoutWrite;
|
|
281
304
|
const err = ctx.err ?? stderrWrite;
|
|
282
|
-
const chosen = lawFiles(cwd, flags, files);
|
|
305
|
+
const chosen = lawFiles(cwd, flags, files, ctx.skip);
|
|
283
306
|
if (chosen.length === 0) {
|
|
284
307
|
err('no laws files found (looking for *.laws.ts)\n');
|
|
285
308
|
return 1;
|
|
@@ -466,13 +489,132 @@ export async function promoteCommand(cwd, flags, files, ctx) {
|
|
|
466
489
|
}
|
|
467
490
|
return 0;
|
|
468
491
|
}
|
|
492
|
+
const list = (projects) => projects.map((p) => (p.path === '' ? '.' : p.path)).join(', ');
|
|
493
|
+
/** `undefined` for an ordinary single-project run: no project flags, and the directory is not a monorepo root. */
|
|
494
|
+
function selectProjects(cwd, only, filter) {
|
|
495
|
+
const asked = only.length > 0 || filter.length > 0;
|
|
496
|
+
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;
|
|
501
|
+
if (chosen.length === 0) {
|
|
502
|
+
const named = [...only.map((p) => `--project ${p}`), ...filter.map((g) => `--filter ${g}`)].join(' ');
|
|
503
|
+
throw new Error(all.length === 0
|
|
504
|
+
? '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 !== '') };
|
|
508
|
+
}
|
|
509
|
+
/** The projects nested below `project`, relative to it. */
|
|
510
|
+
function nestedIn(project, all) {
|
|
511
|
+
const prefix = project.path === '' ? '' : `${project.path}/`;
|
|
512
|
+
return all
|
|
513
|
+
.filter((other) => other.path !== project.path && other.path.startsWith(prefix))
|
|
514
|
+
.map((other) => other.path.slice(prefix.length));
|
|
515
|
+
}
|
|
516
|
+
/** 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']);
|
|
518
|
+
/** How a root run lays out machine output: one JSON object keyed by project, or ndjson lines tagged with `project`. */
|
|
519
|
+
function machineOf(command, flags) {
|
|
520
|
+
if (command === 'check') {
|
|
521
|
+
const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
|
|
522
|
+
if (reporter === 'junit')
|
|
523
|
+
throw new Error('--reporter junit writes one XML document per project: pick one project with --project <dir>');
|
|
524
|
+
return reporter === 'json' || reporter === 'ndjson' ? reporter : 'text';
|
|
525
|
+
}
|
|
526
|
+
return (command === 'list' || command === 'mutate') && flags.has('json') ? 'json' : 'text';
|
|
527
|
+
}
|
|
528
|
+
/** One project at a time, each under a `── path ──` header, then one summary line. Nonzero if any project failed. */
|
|
529
|
+
async function runProjects(selection, machine, run) {
|
|
530
|
+
const failed = [];
|
|
531
|
+
const keyed = {};
|
|
532
|
+
for (const [index, project] of selection.chosen.entries()) {
|
|
533
|
+
const label = project.path === '' ? '.' : project.path;
|
|
534
|
+
let buffer = '';
|
|
535
|
+
const io = {
|
|
536
|
+
out: machine === 'json' ? (text) => void (buffer += text) : stdoutWrite,
|
|
537
|
+
skip: nestedIn(project, selection.all),
|
|
538
|
+
tag: machine === 'ndjson' ? label : undefined,
|
|
539
|
+
};
|
|
540
|
+
if (machine === 'text')
|
|
541
|
+
stdoutWrite(`${index === 0 ? '' : '\n'}── ${label} ──\n`);
|
|
542
|
+
let status;
|
|
543
|
+
let problem;
|
|
544
|
+
try {
|
|
545
|
+
status = await run(project, io);
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
problem = error instanceof Error ? error.message : String(error);
|
|
549
|
+
stderrWrite(`${label}: ${problem}\n`);
|
|
550
|
+
status = 1;
|
|
551
|
+
}
|
|
552
|
+
if (status !== 0)
|
|
553
|
+
failed.push(label);
|
|
554
|
+
if (machine === 'json') {
|
|
555
|
+
try {
|
|
556
|
+
keyed[label] = buffer === '' ? { error: problem ?? 'no output (see stderr)' } : JSON.parse(buffer);
|
|
557
|
+
}
|
|
558
|
+
catch {
|
|
559
|
+
keyed[label] = { error: problem ?? 'output was not JSON' };
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (machine === 'json')
|
|
564
|
+
stdoutWrite(`${JSON.stringify(keyed, null, 2)}\n`);
|
|
565
|
+
const count = selection.chosen.length;
|
|
566
|
+
const summary = `${count} project${count === 1 ? '' : 's'}, ${failed.length} failed${failed.length === 0 ? '' : ` (${failed.join(', ')})`}\n`;
|
|
567
|
+
if (machine === 'text')
|
|
568
|
+
stdoutWrite(`\n${summary}`);
|
|
569
|
+
else
|
|
570
|
+
stderrWrite(summary);
|
|
571
|
+
return failed.length === 0 ? 0 : 1;
|
|
572
|
+
}
|
|
469
573
|
export async function main(args) {
|
|
470
574
|
if (args.includes('--help') || args.includes('-h')) {
|
|
471
575
|
process.stdout.write(`${usage}\n`);
|
|
472
576
|
return 0;
|
|
473
577
|
}
|
|
474
|
-
const { command, flags, files } = parse(args);
|
|
578
|
+
const { command, flags, files, projects, filters } = parse(args);
|
|
475
579
|
const cwd = process.cwd();
|
|
580
|
+
// `init --project .` scaffolds right here, in a root that has projects or not.
|
|
581
|
+
const here = command === 'init' && projects.some((p) => p === '.' || p === './');
|
|
582
|
+
let selection;
|
|
583
|
+
try {
|
|
584
|
+
selection = here ? undefined : selectProjects(cwd, projects, filters);
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
588
|
+
return 1;
|
|
589
|
+
}
|
|
590
|
+
if (selection === undefined)
|
|
591
|
+
return runOne(command, flags, files, cwd, direct);
|
|
592
|
+
// One project and a reporter that writes one document (junit) runs plainly: there is nothing to join.
|
|
593
|
+
const oneDocument = command === 'check' && flags.get('reporter') === 'junit' && selection.chosen.length === 1 && !flags.has('watch');
|
|
594
|
+
if (selection.fanOut && fansOut.has(command) && !flags.has('watch') && !oneDocument) {
|
|
595
|
+
if (files.length > 0 && command !== 'regressions') {
|
|
596
|
+
stderrWrite(`name files only inside one project: run \`tslaws ${command} ${files[0]}\` there, or pick it with --project <dir>\n`);
|
|
597
|
+
return 1;
|
|
598
|
+
}
|
|
599
|
+
let machine;
|
|
600
|
+
try {
|
|
601
|
+
machine = machineOf(command, flags);
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
605
|
+
return 1;
|
|
606
|
+
}
|
|
607
|
+
return runProjects(selection, machine, (project, io) => runOne(command, flags, files, project.dir, io));
|
|
608
|
+
}
|
|
609
|
+
if (selection.chosen.length > 1) {
|
|
610
|
+
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`);
|
|
611
|
+
return 1;
|
|
612
|
+
}
|
|
613
|
+
const [only] = selection.chosen;
|
|
614
|
+
return runOne(command, flags, files, only.dir, { ...direct, skip: nestedIn(only, selection.all) });
|
|
615
|
+
}
|
|
616
|
+
/** One command in one project directory. */
|
|
617
|
+
async function runOne(command, flags, files, cwd, run) {
|
|
476
618
|
if (command === 'init') {
|
|
477
619
|
process.stdout.write(`${init({ cwd, force: flags.has('force') }).join('\n')}\n\n${nextStep}\n`);
|
|
478
620
|
return 0;
|
|
@@ -500,7 +642,7 @@ export async function main(args) {
|
|
|
500
642
|
});
|
|
501
643
|
}
|
|
502
644
|
if (command === 'accept')
|
|
503
|
-
return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
|
|
645
|
+
return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
|
|
504
646
|
if (command === 'delegate')
|
|
505
647
|
return delegateCommand(cwd, files[0], flags, { isTTY: process.stdin.isTTY === true, env: process.env });
|
|
506
648
|
if (command === 'migrate')
|
|
@@ -510,15 +652,15 @@ export async function main(args) {
|
|
|
510
652
|
if (command === 'promote')
|
|
511
653
|
return promoteCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
|
|
512
654
|
if (command === 'list') {
|
|
513
|
-
const listed = listLawFiles(cwd);
|
|
514
|
-
|
|
655
|
+
const listed = listLawFiles(cwd).filter((f) => outside([f.file], run.skip).length > 0);
|
|
656
|
+
run.out(flags.has('json') ? `${JSON.stringify({ files: listed }, null, 2)}\n` : renderList(listed));
|
|
515
657
|
return 0;
|
|
516
658
|
}
|
|
517
659
|
if (command === 'propose')
|
|
518
660
|
return proposeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
|
|
519
661
|
if (command === 'mutate') {
|
|
520
662
|
// *.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')));
|
|
663
|
+
const chosen = lawFiles(cwd, flags, files.filter((f) => f.endsWith('.laws.ts')), run.skip);
|
|
522
664
|
if (chosen.length === 0) {
|
|
523
665
|
process.stderr.write('no laws files found (looking for *.laws.ts)\n');
|
|
524
666
|
return 1;
|
|
@@ -539,13 +681,13 @@ export async function main(args) {
|
|
|
539
681
|
seed: flags.has('seed') ? Number(flags.get('seed')) : undefined,
|
|
540
682
|
onProgress: flags.has('json') ? undefined : (line) => process.stderr.write(`${line}\n`),
|
|
541
683
|
});
|
|
542
|
-
|
|
684
|
+
run.out(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
|
|
543
685
|
return report.ok ? 0 : 1;
|
|
544
686
|
}
|
|
545
687
|
if (command === 'regressions') {
|
|
546
688
|
const action = files[0] ?? 'list';
|
|
547
689
|
if (action === 'clear') {
|
|
548
|
-
|
|
690
|
+
run.out(clearCorpus(cwd) ? 'cleared .tslaws/regressions\n' : 'no regression corpus to clear\n');
|
|
549
691
|
return 0;
|
|
550
692
|
}
|
|
551
693
|
if (action !== 'list') {
|
|
@@ -553,13 +695,13 @@ export async function main(args) {
|
|
|
553
695
|
return 1;
|
|
554
696
|
}
|
|
555
697
|
const corpus = listCorpus(cwd);
|
|
556
|
-
|
|
698
|
+
run.out(corpus.length === 0
|
|
557
699
|
? 'no stored counterexamples\n'
|
|
558
700
|
: `${corpus.map((e) => `${e.file} ${e.law}: ${e.count} example${e.count === 1 ? '' : 's'}`).join('\n')}\n`);
|
|
559
701
|
return 0;
|
|
560
702
|
}
|
|
561
703
|
if (command === 'ui') {
|
|
562
|
-
const chosen = lawFiles(cwd, flags, files);
|
|
704
|
+
const chosen = lawFiles(cwd, flags, files, run.skip);
|
|
563
705
|
if (chosen.length === 0) {
|
|
564
706
|
process.stderr.write('no laws files found (looking for *.laws.ts)\n');
|
|
565
707
|
return 1;
|
|
@@ -574,5 +716,5 @@ export async function main(args) {
|
|
|
574
716
|
log: (line) => process.stdout.write(`${line}\n`),
|
|
575
717
|
});
|
|
576
718
|
}
|
|
577
|
-
return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files);
|
|
719
|
+
return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files, run);
|
|
578
720
|
}
|
package/dist/compile.d.ts
CHANGED
|
@@ -23,5 +23,11 @@ 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
|
-
/**
|
|
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
|
+
/**
|
|
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.
|
|
32
|
+
*/
|
|
27
33
|
export declare function build(compiler: string, files: string[], cwd: string): BuildResult;
|
package/dist/compile.js
CHANGED
|
@@ -2,10 +2,12 @@ import { spawnSync } from 'node:child_process';
|
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { transformSync } from 'esbuild';
|
|
6
7
|
import ts from 'typescript';
|
|
7
8
|
import { lowerLawFile, usesLegacySyntax } from "./lower.js";
|
|
8
9
|
import { readConfig } from "./coverage.js";
|
|
10
|
+
import { importMetaEnvGlobal } from "./runtimeEnv.js";
|
|
9
11
|
/**
|
|
10
12
|
* Runs the compiler, trying again when the system could not start it. On Windows a freshly built executable can be
|
|
11
13
|
* briefly unavailable (a scanner holds it, the machine is out of handles), which surfaces as ENOENT or UNKNOWN.
|
|
@@ -162,7 +164,66 @@ export function compilerFlags(options) {
|
|
|
162
164
|
}
|
|
163
165
|
return flags;
|
|
164
166
|
}
|
|
165
|
-
/**
|
|
167
|
+
/**
|
|
168
|
+
* Turns emitted ES modules into CommonJS, and `import.meta.env` into the global the runner sets before any law loads
|
|
169
|
+
* (see runtimeEnv.ts). Everything else in `import.meta` is left to esbuild, which makes it an empty object.
|
|
170
|
+
*/
|
|
171
|
+
function lowerModule(text, sourcefile) {
|
|
172
|
+
return transformSync(text, {
|
|
173
|
+
format: 'cjs',
|
|
174
|
+
target: 'es2022',
|
|
175
|
+
sourcefile,
|
|
176
|
+
define: { 'import.meta.env': `globalThis.${importMetaEnvGlobal}` },
|
|
177
|
+
logLevel: 'silent',
|
|
178
|
+
}).code;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* CommonJS for ES module text the native compiler emitted, with `import.meta.env` read from the runner's global. TypeScript
|
|
182
|
+
* does the lowering, not esbuild, so the comments stay: the coverage analysis reads `@tslaws-exempt` from this output.
|
|
183
|
+
*/
|
|
184
|
+
function lowerEmitted(text, file) {
|
|
185
|
+
const source = text
|
|
186
|
+
.replace(/\bimport\.meta\.env\b/g, `globalThis.${importMetaEnvGlobal}`)
|
|
187
|
+
.replace(/\bimport\.meta\b/g, '({})');
|
|
188
|
+
return ts.transpileModule(source, {
|
|
189
|
+
fileName: file,
|
|
190
|
+
compilerOptions: {
|
|
191
|
+
module: ts.ModuleKind.CommonJS,
|
|
192
|
+
target: ts.ScriptTarget.ES2022,
|
|
193
|
+
esModuleInterop: true,
|
|
194
|
+
allowJs: true,
|
|
195
|
+
},
|
|
196
|
+
}).outputText;
|
|
197
|
+
}
|
|
198
|
+
/** Lowers every `.js` file the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed. */
|
|
199
|
+
export function lowerEmittedModules(dir) {
|
|
200
|
+
if (!existsSync(dir))
|
|
201
|
+
return;
|
|
202
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
203
|
+
const path = join(dir, entry.name);
|
|
204
|
+
if (entry.isDirectory())
|
|
205
|
+
lowerEmittedModules(path);
|
|
206
|
+
else if (entry.name.endsWith('.js')) {
|
|
207
|
+
try {
|
|
208
|
+
writeFileSync(path, lowerEmitted(readFileSync(path, 'utf8'), path));
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// Output that does not parse (JSX kept because the project sets no `jsx`): the compiler's diagnostics say why.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** The ambient `ImportMeta.env` declaration that ships with tslaws; also importable as `tslaws/env`. */
|
|
217
|
+
const envTypes = fileURLToPath(new URL('../env.d.ts', import.meta.url));
|
|
218
|
+
/** Whether `text` (compiler output) says `import.meta.env` has no declaration. */
|
|
219
|
+
const lacksEnvTypes = (text) => /TS2339.*'ImportMeta'/.test(text);
|
|
220
|
+
/** Whether `text` (compiler output) says the project uses `import.meta`, which CommonJS output does not allow. */
|
|
221
|
+
const usesImportMeta = (text) => /TS1343/.test(text);
|
|
222
|
+
/**
|
|
223
|
+
* Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. The
|
|
224
|
+
* built-in compiler always reads the project as ES modules and lowers the output. The native compiler does so only for a
|
|
225
|
+
* project that uses `import.meta` (it reports TS1343 as CommonJS), so every other project builds exactly as before.
|
|
226
|
+
*/
|
|
166
227
|
export function build(compiler, files, cwd) {
|
|
167
228
|
const outDir = join(cwd, '.tslaws', 'out');
|
|
168
229
|
const extra = compilerFlags(readConfig(cwd).compilerOptions);
|
|
@@ -204,6 +265,30 @@ export function build(compiler, files, cwd) {
|
|
|
204
265
|
run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
|
|
205
266
|
if (run.error !== undefined)
|
|
206
267
|
throw new Error(cannotRun(compiler, run.error));
|
|
268
|
+
const output = () => `${run.stdout ?? ''}${run.stderr ?? ''}`;
|
|
269
|
+
const again = (again) => {
|
|
270
|
+
const next = launch(compiler, again, {
|
|
271
|
+
cwd,
|
|
272
|
+
encoding: 'utf8',
|
|
273
|
+
maxBuffer: 64 << 20,
|
|
274
|
+
env: compilerEnv(cwd, compiler),
|
|
275
|
+
});
|
|
276
|
+
if (next.error === undefined)
|
|
277
|
+
run = next;
|
|
278
|
+
};
|
|
279
|
+
// CommonJS output does not allow `import.meta`: read the project as ES modules instead, and lower the output below.
|
|
280
|
+
let lowering = false;
|
|
281
|
+
let used = args;
|
|
282
|
+
if (usesImportMeta(output())) {
|
|
283
|
+
used = args.map((arg, i) => (args[i - 1] === '--module' ? 'preserve' : arg));
|
|
284
|
+
lowering = true;
|
|
285
|
+
again(used);
|
|
286
|
+
}
|
|
287
|
+
// A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, and the build runs again.
|
|
288
|
+
if (lacksEnvTypes(output()))
|
|
289
|
+
again([...used, envTypes]);
|
|
290
|
+
if (lowering)
|
|
291
|
+
lowerEmittedModules(outDir);
|
|
207
292
|
return { outDir, diagnostics: `${run.stdout ?? ''}${run.stderr ?? ''}`.trim(), ok: run.status === 0 };
|
|
208
293
|
}
|
|
209
294
|
/** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
|
|
@@ -248,6 +333,7 @@ function buildBuiltin(args, files, cwd, outDir) {
|
|
|
248
333
|
: ts.createSourceFile(name, text, languageVersion, true);
|
|
249
334
|
};
|
|
250
335
|
const roots = parsed.fileNames.map((f) => resolve(cwd, f));
|
|
336
|
+
let used = options;
|
|
251
337
|
let program = ts.createProgram(roots, options, host);
|
|
252
338
|
let diagnostics = ts.getPreEmitDiagnostics(program);
|
|
253
339
|
// An error may only be a global the narrow setup left out (`process`, `document`, a test runner's types): check again
|
|
@@ -257,14 +343,18 @@ function buildBuiltin(args, files, cwd, outDir) {
|
|
|
257
343
|
// `@types` is looked up from the project, not from wherever the process happens to be (the compiler remembers the first directory it saw).
|
|
258
344
|
const typeRoots = parsed.options.typeRoots ?? typeRootsOf(cwd);
|
|
259
345
|
const full = { ...options, types: parsed.options.types, lib: parsed.options.lib, typeRoots };
|
|
346
|
+
used = full;
|
|
260
347
|
program = ts.createProgram(roots, full, host);
|
|
261
348
|
diagnostics = ts.getPreEmitDiagnostics(program);
|
|
262
349
|
}
|
|
350
|
+
// A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, checked the same way.
|
|
351
|
+
if (diagnostics.some((d) => d.code === 2339 && ts.flattenDiagnosticMessageText(d.messageText, ' ').includes("'ImportMeta'"))) {
|
|
352
|
+
program = ts.createProgram([...roots, envTypes], used, host);
|
|
353
|
+
diagnostics = ts.getPreEmitDiagnostics(program);
|
|
354
|
+
}
|
|
263
355
|
program.emit(undefined, (name, text) => {
|
|
264
356
|
mkdirSync(dirname(name), { recursive: true });
|
|
265
|
-
const code = name.endsWith('.js')
|
|
266
|
-
? transformSync(text, { format: 'cjs', target: 'es2022', sourcefile: name }).code
|
|
267
|
-
: text;
|
|
357
|
+
const code = name.endsWith('.js') ? lowerModule(text, name) : text;
|
|
268
358
|
writeFileSync(name, code);
|
|
269
359
|
});
|
|
270
360
|
const text = ts.formatDiagnostics(diagnostics, {
|
|
@@ -287,7 +377,7 @@ function buildBuiltin(args, files, cwd, outDir) {
|
|
|
287
377
|
const buildCachePath = (cwd) => join(cwd, '.tslaws', 'build-cache.json');
|
|
288
378
|
function buildKey(args, files, cwd) {
|
|
289
379
|
const hash = createHash('sha256');
|
|
290
|
-
hash.update(JSON.stringify([args, ts.version, toolStamp]));
|
|
380
|
+
hash.update(JSON.stringify([args, ts.version, toolStamp, importMetaEnvGlobal, envTypes]));
|
|
291
381
|
for (const file of files)
|
|
292
382
|
if (isLawFile(file, cwd) && existsSync(join(cwd, file)))
|
|
293
383
|
hash.update(`
|
package/dist/coverage.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
2
|
import { type E2eConfig } from './e2e.ts';
|
|
3
|
+
import { type ImportMetaEnv } from './runtimeEnv.ts';
|
|
3
4
|
import { type SolverName } from './solvers.ts';
|
|
4
5
|
export interface CoverageConfig {
|
|
5
6
|
cover?: string[];
|
|
@@ -24,6 +25,11 @@ export interface CoverageConfig {
|
|
|
24
25
|
solvers?: SolverName[];
|
|
25
26
|
/** esbuild plugin modules (paths relative to tslaws.json) that teach the browser bundler new source formats. */
|
|
26
27
|
bundlerPlugins?: string[];
|
|
28
|
+
/**
|
|
29
|
+
* `import.meta.env` for code laws reach, on top of `process.env` and the defaults (`MODE` `test`, `DEV`, `PROD`, `SSR`,
|
|
30
|
+
* `BASE_URL`); its entries override both. See runtimeEnv.ts.
|
|
31
|
+
*/
|
|
32
|
+
env?: Record<string, string | boolean>;
|
|
27
33
|
/** Run settings; a command line flag beats them and they beat the built-in default. */
|
|
28
34
|
runs?: number;
|
|
29
35
|
propertyTimeoutMs?: number;
|
|
@@ -43,9 +49,18 @@ export interface CoverageReport {
|
|
|
43
49
|
/** The source files the check covers, for the compiler to emit. */
|
|
44
50
|
files: string[];
|
|
45
51
|
}
|
|
46
|
-
/**
|
|
47
|
-
export declare function
|
|
52
|
+
/** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
|
|
53
|
+
export declare function projectsProblem(value: unknown): string | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. `extends`
|
|
56
|
+
* and `projects` are accepted (a string, and a list of globs) but are not part of the result: `readConfig` has
|
|
57
|
+
* already acted on `extends`, and discovery reads `projects` from the file itself.
|
|
58
|
+
*/
|
|
59
|
+
export declare function parseConfig(raw: unknown, source?: string): CoverageConfig;
|
|
60
|
+
/** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
|
|
48
61
|
export declare function readConfig(cwd: string): CoverageConfig;
|
|
62
|
+
/** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
|
|
63
|
+
export declare function lawEnv(cwd: string, surface: 'node' | 'browser'): ImportMetaEnv;
|
|
49
64
|
/** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
|
|
50
65
|
export declare function coverFiles(cwd: string, globs: string[]): string[];
|
|
51
66
|
export interface CoverageInput {
|
package/dist/coverage.js
CHANGED
|
@@ -6,11 +6,12 @@
|
|
|
6
6
|
// but only once the exemption is in tsc-laws.lock, so an agent cannot exempt its own code.
|
|
7
7
|
import { parseGithubConfig } from "./github.js";
|
|
8
8
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
9
|
-
import { dirname, join, relative, resolve } from 'node:path';
|
|
9
|
+
import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';
|
|
10
10
|
import ts from 'typescript';
|
|
11
11
|
import { parseE2eConfig } from "./e2e.js";
|
|
12
12
|
import { globMatcher } from "./globs.js";
|
|
13
13
|
import { customLawFile } from "./lawFiles.js";
|
|
14
|
+
import { importMetaEnvOf, parseEnvConfig } from "./runtimeEnv.js";
|
|
14
15
|
import { solversProblem } from "./solvers.js";
|
|
15
16
|
const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
|
|
16
17
|
const configKeys = [
|
|
@@ -21,21 +22,36 @@ const configKeys = [
|
|
|
21
22
|
'compilerOptions',
|
|
22
23
|
'e2e',
|
|
23
24
|
'bundlerPlugins',
|
|
25
|
+
'env',
|
|
24
26
|
'github',
|
|
25
27
|
...settingKeys,
|
|
26
28
|
];
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
+
/** Keys that steer inheritance and discovery rather than a run; `readConfig` acts on them and drops them. */
|
|
30
|
+
const structuralKeys = ['extends', 'projects'];
|
|
31
|
+
/** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
|
|
32
|
+
export function projectsProblem(value) {
|
|
33
|
+
if (!Array.isArray(value) ||
|
|
34
|
+
value.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/')))
|
|
35
|
+
return `"projects" must be an array of directory globs relative to tslaws.json, got ${JSON.stringify(value)}`;
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
/** The top-level checks that hold for one file on its own; `source` names that file in every message. */
|
|
39
|
+
function checkFile(raw, source) {
|
|
29
40
|
const fail = (message) => {
|
|
30
|
-
throw new Error(
|
|
41
|
+
throw new Error(`${source}: ${message}`);
|
|
31
42
|
};
|
|
32
43
|
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
33
44
|
return fail('must be a JSON object');
|
|
34
45
|
const object = raw;
|
|
35
46
|
for (const key of Object.keys(object)) {
|
|
36
|
-
if (key !== '$schema' && !configKeys.includes(key))
|
|
37
|
-
fail(`unknown option "${key}"; supported options are ${configKeys.join(', ')}`);
|
|
47
|
+
if (key !== '$schema' && !configKeys.includes(key) && !structuralKeys.includes(key))
|
|
48
|
+
fail(`unknown option "${key}"; supported options are ${[...configKeys, ...structuralKeys].join(', ')}`);
|
|
38
49
|
}
|
|
50
|
+
if (object.extends !== undefined && (typeof object.extends !== 'string' || object.extends === ''))
|
|
51
|
+
fail(`"extends" must be a path to another tslaws.json, got ${JSON.stringify(object.extends)}`);
|
|
52
|
+
const projects = object.projects === undefined ? undefined : projectsProblem(object.projects);
|
|
53
|
+
if (projects !== undefined)
|
|
54
|
+
fail(projects);
|
|
39
55
|
for (const key of settingKeys) {
|
|
40
56
|
const value = object[key];
|
|
41
57
|
if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value) || value < 1))
|
|
@@ -45,6 +61,8 @@ export function parseConfig(raw) {
|
|
|
45
61
|
if (plugins !== undefined &&
|
|
46
62
|
(!Array.isArray(plugins) || plugins.some((entry) => typeof entry !== 'string' || entry === '')))
|
|
47
63
|
fail(`"bundlerPlugins" must be an array of module paths, got ${JSON.stringify(plugins)}`);
|
|
64
|
+
if (object.env !== undefined)
|
|
65
|
+
parseEnvConfig(object.env);
|
|
48
66
|
const levels = object.levels;
|
|
49
67
|
if (levels !== undefined && levels !== 'names' && levels !== 'imports')
|
|
50
68
|
fail(`"levels" must be "names" or "imports", got ${JSON.stringify(levels)}`);
|
|
@@ -56,19 +74,138 @@ export function parseConfig(raw) {
|
|
|
56
74
|
(!Array.isArray(laws) ||
|
|
57
75
|
laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
|
|
58
76
|
fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
|
|
77
|
+
return object;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. `extends`
|
|
81
|
+
* and `projects` are accepted (a string, and a list of globs) but are not part of the result: `readConfig` has
|
|
82
|
+
* already acted on `extends`, and discovery reads `projects` from the file itself.
|
|
83
|
+
*/
|
|
84
|
+
export function parseConfig(raw, source = 'tslaws.json') {
|
|
85
|
+
const object = checkFile(raw, source);
|
|
59
86
|
if (object.github !== undefined)
|
|
60
87
|
parseGithubConfig(object.github);
|
|
61
|
-
|
|
88
|
+
const config = { ...object };
|
|
89
|
+
for (const key of structuralKeys)
|
|
90
|
+
delete config[key];
|
|
91
|
+
return config;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The settings that name a file or directory by path, rebased when inherited through `extends`: a value is written
|
|
95
|
+
* relative to the file that declares it (as in tsconfig), so it is rebased to the extending file. `bundlerPlugins` are
|
|
96
|
+
* module paths and `e2e.server.cwd` is the directory the dev server runs in. A trailing `[]` means every element of an
|
|
97
|
+
* array. `cover` and `laws` are not here on purpose: they are globs relative to the project that uses the config, so a
|
|
98
|
+
* shared base saying `"cover": ["src/**"]` means each package's own src/. `compilerOptions` and `github` hold no
|
|
99
|
+
* paths. Add a new file-reference option here when it is added to `configKeys`.
|
|
100
|
+
*/
|
|
101
|
+
const pathFields = ['bundlerPlugins[]', 'e2e.server.cwd'];
|
|
102
|
+
/** `entry`, written relative to the directory `from`, as a path relative to `to`. A leading `!` and absolute paths stay. */
|
|
103
|
+
function rebase(entry, from, to) {
|
|
104
|
+
const negated = entry.startsWith('!');
|
|
105
|
+
const body = negated ? entry.slice(1) : entry;
|
|
106
|
+
const prefix = relative(to, from).replaceAll('\\', '/');
|
|
107
|
+
if (prefix === '' || isAbsolute(body))
|
|
108
|
+
return entry;
|
|
109
|
+
return `${negated ? '!' : ''}${posix.join(prefix, body)}`;
|
|
110
|
+
}
|
|
111
|
+
function rebaseFields(config, from, to) {
|
|
112
|
+
const out = { ...config };
|
|
113
|
+
for (const field of pathFields) {
|
|
114
|
+
const parts = field.split('.');
|
|
115
|
+
let node = out;
|
|
116
|
+
for (const [index, part] of parts.entries()) {
|
|
117
|
+
const list = part.endsWith('[]');
|
|
118
|
+
const key = list ? part.slice(0, -2) : part;
|
|
119
|
+
const value = node[key];
|
|
120
|
+
if (index === parts.length - 1) {
|
|
121
|
+
if (list && Array.isArray(value))
|
|
122
|
+
node[key] = value.map((entry) => (typeof entry === 'string' ? rebase(entry, from, to) : entry));
|
|
123
|
+
else if (!list && typeof value === 'string')
|
|
124
|
+
node[key] = rebase(value, from, to);
|
|
125
|
+
}
|
|
126
|
+
else if (isPlain(value)) {
|
|
127
|
+
node[key] = { ...value };
|
|
128
|
+
node = node[key];
|
|
129
|
+
}
|
|
130
|
+
else
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
function isPlain(value) {
|
|
137
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
62
138
|
}
|
|
139
|
+
/** Objects merge key by key; anything else, arrays included, is replaced. The child wins. */
|
|
140
|
+
function deepMerge(base, child) {
|
|
141
|
+
const out = { ...base };
|
|
142
|
+
for (const [key, value] of Object.entries(child)) {
|
|
143
|
+
if (key === '__proto__')
|
|
144
|
+
continue;
|
|
145
|
+
const inherited = out[key];
|
|
146
|
+
out[key] = isPlain(value) && isPlain(inherited) ? deepMerge(inherited, value) : value;
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Loads `file` and the files it `extends`, merged, with paths relative to the directory of `file`. `chain` holds the
|
|
152
|
+
* files being loaded, outermost first, so a cycle or a missing file is reported with the way it was reached; every
|
|
153
|
+
* file read is added to `loaded`.
|
|
154
|
+
*/
|
|
155
|
+
function loadMerged(file, cwd, chain, loaded) {
|
|
156
|
+
const shown = (path) => relative(cwd, path).replaceAll('\\', '/') || path;
|
|
157
|
+
const trail = [...chain, file];
|
|
158
|
+
let text;
|
|
159
|
+
try {
|
|
160
|
+
text = readFileSync(file, 'utf8');
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
throw new Error(`${shown(file)}: no such file (reached by extends: ${trail.map(shown).join(' -> ')})`);
|
|
164
|
+
}
|
|
165
|
+
loaded.push(file);
|
|
166
|
+
let json;
|
|
167
|
+
try {
|
|
168
|
+
json = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
throw new Error(`${shown(file)}: ${error.message}`);
|
|
172
|
+
}
|
|
173
|
+
const { extends: parent, ...own } = checkFile(json, shown(file));
|
|
174
|
+
if (parent === undefined)
|
|
175
|
+
return own;
|
|
176
|
+
const baseFile = resolve(dirname(file), parent);
|
|
177
|
+
if (trail.includes(baseFile))
|
|
178
|
+
throw new Error(`${shown(file)}: "extends" forms a cycle (${[...trail, baseFile].map(shown).join(' -> ')})`);
|
|
179
|
+
const base = rebaseFields(loadMerged(baseFile, cwd, trail, loaded), dirname(baseFile), dirname(file));
|
|
180
|
+
// `projects` lists directories under the file that wrote it, so it is never inherited.
|
|
181
|
+
delete base.projects;
|
|
182
|
+
return deepMerge(base, own);
|
|
183
|
+
}
|
|
184
|
+
/** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
|
|
63
185
|
export function readConfig(cwd) {
|
|
64
186
|
const path = join(cwd, 'tslaws.json');
|
|
65
187
|
if (!existsSync(path))
|
|
66
188
|
return {};
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
189
|
+
const loaded = [];
|
|
190
|
+
const merged = loadMerged(path, cwd, [], loaded);
|
|
191
|
+
let config;
|
|
192
|
+
try {
|
|
193
|
+
config = parseConfig(merged);
|
|
194
|
+
if (config.e2e !== undefined)
|
|
195
|
+
config.e2e = parseE2eConfig(config.e2e);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
if (loaded.length === 1)
|
|
199
|
+
throw error;
|
|
200
|
+
const files = loaded.map((file) => relative(cwd, file).replaceAll('\\', '/')).join(', ');
|
|
201
|
+
throw new Error(`${error.message} (merged from ${files})`);
|
|
202
|
+
}
|
|
70
203
|
return config;
|
|
71
204
|
}
|
|
205
|
+
/** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
|
|
206
|
+
export function lawEnv(cwd, surface) {
|
|
207
|
+
return importMetaEnvOf(readConfig(cwd).env, surface);
|
|
208
|
+
}
|
|
72
209
|
/** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
|
|
73
210
|
export function coverFiles(cwd, globs) {
|
|
74
211
|
// Plain JavaScript sources are covered only when the project compiles them (`allowJs`).
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface Project {
|
|
2
|
+
/** Absolute directory of the project. */
|
|
3
|
+
dir: string;
|
|
4
|
+
/** Directory relative to the repository root, with `/` separators; '' for the root itself. */
|
|
5
|
+
path: string;
|
|
6
|
+
}
|
|
7
|
+
export interface DiscoverOptions {
|
|
8
|
+
/** Keep projects whose `path` matches one of these globs (a leading `!` excludes). */
|
|
9
|
+
filter?: string[];
|
|
10
|
+
/** Keep only projects whose `path` is exactly one of these. */
|
|
11
|
+
only?: string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
|
|
15
|
+
* (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
|
|
16
|
+
*/
|
|
17
|
+
export declare function pnpmPackages(text: string): string[];
|
|
18
|
+
/**
|
|
19
|
+
* Every project under `root`, sorted by path. The root itself is one only when it has a tslaws.json and either that
|
|
20
|
+
* file has no `projects` key (a plain single project that happens to hold others) or the root carries laws of its
|
|
21
|
+
* own (see `rootHasLaws`); a root whose tslaws.json only lists projects is just the list.
|
|
22
|
+
*/
|
|
23
|
+
export declare function discoverProjects(root: string, opts?: DiscoverOptions): Project[];
|
|
24
|
+
/**
|
|
25
|
+
* Whether `cwd` is the root of a monorepo run: it has no tslaws.json but discovery finds projects below it, or its
|
|
26
|
+
* tslaws.json has a `projects` list.
|
|
27
|
+
*/
|
|
28
|
+
export declare function isMonorepoRoot(cwd: string): boolean;
|
package/dist/projects.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Project discovery for a monorepo: a project is a directory holding a tslaws.json. Which directories to look in comes
|
|
2
|
+
// from the first source that names any: `projects` in the root tslaws.json, `workspaces` in package.json (npm, yarn
|
|
3
|
+
// and bun alike), or `packages:` in pnpm-workspace.yaml.
|
|
4
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { projectsProblem, readConfig } from "./coverage.js";
|
|
7
|
+
import { globMatcher } from "./globs.js";
|
|
8
|
+
import { customLawFile } from "./lawFiles.js";
|
|
9
|
+
/** Directories never searched, for projects or for laws files. */
|
|
10
|
+
const skipped = new Set(['node_modules', '.git', 'dist', '.tslaws']);
|
|
11
|
+
/** `./packages/a/` as `packages/a`; `.` and `./` as ''. */
|
|
12
|
+
function normalise(path) {
|
|
13
|
+
return path
|
|
14
|
+
.replaceAll('\\', '/')
|
|
15
|
+
.replace(/^(\.\/)+/, '')
|
|
16
|
+
.replace(/\/+$/, '')
|
|
17
|
+
.replace(/^\.$/, '');
|
|
18
|
+
}
|
|
19
|
+
function readJson(file) {
|
|
20
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
21
|
+
}
|
|
22
|
+
/** The raw `projects` list of tslaws.json in `dir`, or undefined when there is no file or no such key. */
|
|
23
|
+
function projectsOf(dir) {
|
|
24
|
+
const file = join(dir, 'tslaws.json');
|
|
25
|
+
if (!existsSync(file))
|
|
26
|
+
return undefined;
|
|
27
|
+
const raw = readJson(file);
|
|
28
|
+
if (typeof raw !== 'object' || raw === null || raw.projects === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
const problem = projectsProblem(raw.projects);
|
|
31
|
+
if (problem !== undefined)
|
|
32
|
+
throw new Error(`tslaws.json: ${problem}`);
|
|
33
|
+
return raw.projects;
|
|
34
|
+
}
|
|
35
|
+
function workspacesOf(dir) {
|
|
36
|
+
const file = join(dir, 'package.json');
|
|
37
|
+
if (!existsSync(file))
|
|
38
|
+
return [];
|
|
39
|
+
let workspaces;
|
|
40
|
+
try {
|
|
41
|
+
workspaces = readJson(file)?.workspaces;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
const list = Array.isArray(workspaces) ? workspaces : workspaces?.packages;
|
|
47
|
+
return Array.isArray(list) ? list.filter((entry) => typeof entry === 'string') : [];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
|
|
51
|
+
* (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
|
|
52
|
+
*/
|
|
53
|
+
export function pnpmPackages(text) {
|
|
54
|
+
const found = [];
|
|
55
|
+
let inList = false;
|
|
56
|
+
for (const line of text.split(/\r?\n/)) {
|
|
57
|
+
if (/^\s*(#.*)?$/.test(line))
|
|
58
|
+
continue;
|
|
59
|
+
if (/^\S/.test(line)) {
|
|
60
|
+
const key = /^packages\s*:\s*(.*?)\s*(?:#.*)?$/.exec(line);
|
|
61
|
+
inList = key !== null;
|
|
62
|
+
if (key?.[1]?.startsWith('[') === true) {
|
|
63
|
+
for (const item of key[1].replace(/^\[|\]$/g, '').split(',')) {
|
|
64
|
+
const value = item.trim().replace(/^(['"])(.*)\1$/, '$2');
|
|
65
|
+
if (value !== '')
|
|
66
|
+
found.push(value);
|
|
67
|
+
}
|
|
68
|
+
inList = false;
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!inList)
|
|
73
|
+
continue;
|
|
74
|
+
const item = /^\s*-\s*(?:'([^']*)'|"([^"]*)"|([^#\s][^#]*?))\s*(?:#.*)?$/.exec(line);
|
|
75
|
+
const value = item?.[1] ?? item?.[2] ?? item?.[3];
|
|
76
|
+
if (value !== undefined && value !== '')
|
|
77
|
+
found.push(value);
|
|
78
|
+
}
|
|
79
|
+
return found;
|
|
80
|
+
}
|
|
81
|
+
function pnpmWorkspacesOf(dir) {
|
|
82
|
+
const file = join(dir, 'pnpm-workspace.yaml');
|
|
83
|
+
return existsSync(file) ? pnpmPackages(readFileSync(file, 'utf8')) : [];
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Whether the glob `pattern` could match `path` or something below it, from its fixed leading segments alone. It lets
|
|
87
|
+
* the search skip a whole `apps/` tree when the globs are `packages/*`.
|
|
88
|
+
*/
|
|
89
|
+
function reaches(pattern, path) {
|
|
90
|
+
const want = pattern.split('/');
|
|
91
|
+
const have = path.split('/');
|
|
92
|
+
for (const [index, segment] of have.entries()) {
|
|
93
|
+
const expected = want[index];
|
|
94
|
+
if (expected === undefined)
|
|
95
|
+
return want[want.length - 1] === '**';
|
|
96
|
+
if (/[*?]/.test(expected))
|
|
97
|
+
return true;
|
|
98
|
+
if (expected !== segment)
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
/** Directories (relative POSIX paths) under `root` that hold a tslaws.json and match `globs`. */
|
|
104
|
+
function matchingProjects(root, globs) {
|
|
105
|
+
const patterns = globs.map((glob) => {
|
|
106
|
+
const negated = glob.startsWith('!');
|
|
107
|
+
return `${negated ? '!' : ''}${normalise(negated ? glob.slice(1) : glob)}`;
|
|
108
|
+
});
|
|
109
|
+
const matches = globMatcher(patterns);
|
|
110
|
+
const includes = patterns.filter((glob) => !glob.startsWith('!'));
|
|
111
|
+
const found = [];
|
|
112
|
+
const walk = (path) => {
|
|
113
|
+
const dir = path === '' ? root : join(root, path);
|
|
114
|
+
if (path !== '' && matches(path) && existsSync(join(dir, 'tslaws.json')))
|
|
115
|
+
found.push(path);
|
|
116
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
117
|
+
if (!entry.isDirectory() || skipped.has(entry.name))
|
|
118
|
+
continue;
|
|
119
|
+
const next = path === '' ? entry.name : `${path}/${entry.name}`;
|
|
120
|
+
if (includes.some((glob) => reaches(glob, next)))
|
|
121
|
+
walk(next);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
walk('');
|
|
125
|
+
return found;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The cheap test for "the root has laws of its own": a tsc-laws.lock beside it, any `*.laws.ts` file outside the
|
|
129
|
+
* projects, or a file the root's `laws` globs pick that declares a law. It reads directory names, and the contents of
|
|
130
|
+
* only those files the `laws` globs match; it skips node_modules, .git, dist and each project, and stops at the first
|
|
131
|
+
* hit.
|
|
132
|
+
*/
|
|
133
|
+
function rootHasLaws(root, projects) {
|
|
134
|
+
if (existsSync(join(root, 'tsc-laws.lock')))
|
|
135
|
+
return true;
|
|
136
|
+
const inProject = new Set(projects);
|
|
137
|
+
const custom = customLawFile(root, readConfig(root).laws);
|
|
138
|
+
const walk = (path) => {
|
|
139
|
+
for (const entry of readdirSync(path === '' ? root : join(root, path), { withFileTypes: true })) {
|
|
140
|
+
if (entry.isFile() &&
|
|
141
|
+
(entry.name.endsWith('.laws.ts') || custom(path === '' ? entry.name : `${path}/${entry.name}`)))
|
|
142
|
+
return true;
|
|
143
|
+
if (!entry.isDirectory() || skipped.has(entry.name))
|
|
144
|
+
continue;
|
|
145
|
+
const next = path === '' ? entry.name : `${path}/${entry.name}`;
|
|
146
|
+
if (!inProject.has(next) && walk(next))
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
return false;
|
|
150
|
+
};
|
|
151
|
+
return walk('');
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Every project under `root`, sorted by path. The root itself is one only when it has a tslaws.json and either that
|
|
155
|
+
* file has no `projects` key (a plain single project that happens to hold others) or the root carries laws of its
|
|
156
|
+
* own (see `rootHasLaws`); a root whose tslaws.json only lists projects is just the list.
|
|
157
|
+
*/
|
|
158
|
+
export function discoverProjects(root, opts = {}) {
|
|
159
|
+
const dir = resolve(root);
|
|
160
|
+
const listed = projectsOf(dir);
|
|
161
|
+
const globs = listed ?? [workspacesOf(dir), pnpmWorkspacesOf(dir)].find((list) => list.length > 0) ?? [];
|
|
162
|
+
const paths = globs.length === 0 ? [] : matchingProjects(dir, globs);
|
|
163
|
+
if (existsSync(join(dir, 'tslaws.json')) && (listed === undefined || rootHasLaws(dir, paths)))
|
|
164
|
+
paths.push('');
|
|
165
|
+
let projects = paths.sort().map((path) => ({ dir: path === '' ? dir : join(dir, path), path }));
|
|
166
|
+
if (opts.only !== undefined && opts.only.length > 0) {
|
|
167
|
+
const only = new Set(opts.only.map(normalise));
|
|
168
|
+
projects = projects.filter((project) => only.has(project.path));
|
|
169
|
+
}
|
|
170
|
+
if (opts.filter !== undefined && opts.filter.length > 0) {
|
|
171
|
+
const matches = globMatcher(opts.filter.map((glob) => (glob.startsWith('!') ? `!${normalise(glob.slice(1))}` : normalise(glob))));
|
|
172
|
+
projects = projects.filter((project) => matches(project.path));
|
|
173
|
+
}
|
|
174
|
+
return projects;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Whether `cwd` is the root of a monorepo run: it has no tslaws.json but discovery finds projects below it, or its
|
|
178
|
+
* tslaws.json has a `projects` list.
|
|
179
|
+
*/
|
|
180
|
+
export function isMonorepoRoot(cwd) {
|
|
181
|
+
const dir = resolve(cwd);
|
|
182
|
+
if (!existsSync(join(dir, 'tslaws.json')))
|
|
183
|
+
return discoverProjects(dir).length > 0;
|
|
184
|
+
return projectsOf(dir) !== undefined;
|
|
185
|
+
}
|
package/dist/property.js
CHANGED
|
@@ -3,6 +3,7 @@ import { readdirSync, statSync } from 'node:fs';
|
|
|
3
3
|
import { join, resolve } from 'node:path';
|
|
4
4
|
import ts from 'typescript';
|
|
5
5
|
import { GeneratorFactory } from "./generators.js";
|
|
6
|
+
import { lawEnv } from "./coverage.js";
|
|
6
7
|
import { arbitraryOf, UnsupportedType } from "./plan.js";
|
|
7
8
|
import { WorkerPool } from "./pool.js";
|
|
8
9
|
export { isDiscard, jsPath, runLaw, runProperty, summarise } from "./propertyRun.js";
|
|
@@ -127,6 +128,12 @@ export async function runLawGuarded(outDir, law, options, plans) {
|
|
|
127
128
|
};
|
|
128
129
|
current.once('message', onMessage);
|
|
129
130
|
// Functions cannot cross to the worker; it needs only the numbers.
|
|
130
|
-
current.postMessage({
|
|
131
|
+
current.postMessage({
|
|
132
|
+
outDir,
|
|
133
|
+
law,
|
|
134
|
+
plans,
|
|
135
|
+
options: { ...options, onEvent: undefined },
|
|
136
|
+
env: lawEnv(options.cwd, 'node'),
|
|
137
|
+
});
|
|
131
138
|
});
|
|
132
139
|
}
|
package/dist/propertyWorker.js
CHANGED
|
@@ -2,12 +2,15 @@ import { createRequire } from 'node:module';
|
|
|
2
2
|
import { parentPort } from 'node:worker_threads';
|
|
3
3
|
import { arbitraryOf } from "./plan.js";
|
|
4
4
|
import { jsPath, runLaw, summarise } from "./propertyRun.js";
|
|
5
|
+
import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
|
|
5
6
|
// Property tests run here so that a law over code that never terminates costs a timeout, not the whole check.
|
|
6
7
|
// The main process read the types and sends the generators as plans, so a worker never loads the TypeScript compiler.
|
|
7
8
|
const require = createRequire(import.meta.url);
|
|
9
|
+
installLoaderHooks();
|
|
8
10
|
parentPort.on('message', async (request) => {
|
|
9
11
|
try {
|
|
10
|
-
const { outDir, law, plans, options } = request;
|
|
12
|
+
const { outDir, law, plans, options, env } = request;
|
|
13
|
+
setImportMetaEnv(env);
|
|
11
14
|
const generators = plans.map(arbitraryOf);
|
|
12
15
|
// The worker outlives a check, and the code may have been recompiled since the last one.
|
|
13
16
|
for (const loaded of Object.keys(require.cache))
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The global that `import.meta.env` is rewritten to, in compiled laws, bundles and natively loaded TypeScript. */
|
|
2
|
+
export declare const importMetaEnvGlobal = "__tslawsImportMetaEnv";
|
|
3
|
+
/** The value of `import.meta.env` in every place a law runs. */
|
|
4
|
+
export type ImportMetaEnv = Record<string, string | boolean>;
|
|
5
|
+
/** The `env` setting of tslaws.json: a name to a string (or a boolean, for `DEV`, `PROD` and `SSR`). */
|
|
6
|
+
export declare function parseEnvConfig(raw: unknown): Record<string, string | boolean>;
|
|
7
|
+
/**
|
|
8
|
+
* The environment of a law: every `process.env` entry, then `MODE` (`test`), `DEV` (true), `PROD` (false), `SSR` (true
|
|
9
|
+
* in Node, false in a page) and `BASE_URL` (`/`), then the `env` of tslaws.json, which overrides all of it. `MODE` and
|
|
10
|
+
* `BASE_URL` keep the value `process.env` gives them.
|
|
11
|
+
*/
|
|
12
|
+
export declare function importMetaEnvOf(configured: Record<string, string | boolean> | undefined, surface: 'node' | 'browser', processEnv?: NodeJS.ProcessEnv): ImportMetaEnv;
|
|
13
|
+
/** Sets `import.meta.env` for everything loaded afterwards in this thread. */
|
|
14
|
+
export declare function setImportMetaEnv(env: ImportMetaEnv): void;
|
|
15
|
+
/**
|
|
16
|
+
* Teaches Node's own loading of TypeScript two things a bundler does: a relative import without an extension
|
|
17
|
+
* (`export * from './database'`) finds the `.ts` file, and `import.meta.env` reads the environment of the laws. Both
|
|
18
|
+
* apply to project TypeScript only, never to anything under `node_modules`. Needs `module.registerHooks`
|
|
19
|
+
* (Node 22.15, 23.5 or later); on an older Node the hooks are skipped and such imports fail as they did before.
|
|
20
|
+
* Returns whether the hooks are in place. Registers once per thread.
|
|
21
|
+
*/
|
|
22
|
+
export declare function installLoaderHooks(): boolean;
|
|
23
|
+
/** Everything a law needs before its module loads: the hooks and the environment. */
|
|
24
|
+
export declare function prepareRuntime(env: ImportMetaEnv): void;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// What laws need at run time to load project code written for a bundler: `import.meta.env`, and relative imports without
|
|
2
|
+
// an extension in TypeScript files that Node loads itself. Nothing here loads the TypeScript compiler, so a property worker
|
|
3
|
+
// can import it.
|
|
4
|
+
import nodeModule from 'node:module';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
/** The global that `import.meta.env` is rewritten to, in compiled laws, bundles and natively loaded TypeScript. */
|
|
7
|
+
export const importMetaEnvGlobal = '__tslawsImportMetaEnv';
|
|
8
|
+
/** The `env` setting of tslaws.json: a name to a string (or a boolean, for `DEV`, `PROD` and `SSR`). */
|
|
9
|
+
export function parseEnvConfig(raw) {
|
|
10
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
11
|
+
throw new Error(`tslaws.json: "env" must be an object of names to strings, got ${JSON.stringify(raw)}`);
|
|
12
|
+
for (const [key, value] of Object.entries(raw))
|
|
13
|
+
if (typeof value !== 'string' && typeof value !== 'boolean')
|
|
14
|
+
throw new Error(`tslaws.json: "env.${key}" must be a string or a boolean, got ${JSON.stringify(value)}`);
|
|
15
|
+
return raw;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The environment of a law: every `process.env` entry, then `MODE` (`test`), `DEV` (true), `PROD` (false), `SSR` (true
|
|
19
|
+
* in Node, false in a page) and `BASE_URL` (`/`), then the `env` of tslaws.json, which overrides all of it. `MODE` and
|
|
20
|
+
* `BASE_URL` keep the value `process.env` gives them.
|
|
21
|
+
*/
|
|
22
|
+
export function importMetaEnvOf(configured, surface, processEnv = process.env) {
|
|
23
|
+
const env = {};
|
|
24
|
+
for (const [key, value] of Object.entries(processEnv))
|
|
25
|
+
if (value !== undefined)
|
|
26
|
+
env[key] = value;
|
|
27
|
+
return {
|
|
28
|
+
...env,
|
|
29
|
+
MODE: processEnv.MODE ?? 'test',
|
|
30
|
+
DEV: true,
|
|
31
|
+
PROD: false,
|
|
32
|
+
SSR: surface === 'node',
|
|
33
|
+
BASE_URL: processEnv.BASE_URL ?? '/',
|
|
34
|
+
...configured,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Sets `import.meta.env` for everything loaded afterwards in this thread. */
|
|
38
|
+
export function setImportMetaEnv(env) {
|
|
39
|
+
globalThis[importMetaEnvGlobal] = env;
|
|
40
|
+
}
|
|
41
|
+
const sourceFile = /\.[cm]?tsx?$/;
|
|
42
|
+
const unresolved = ['.ts', '.tsx', '.mts', '.js', '/index.ts', '/index.tsx'];
|
|
43
|
+
const javascriptEnding = /\.[cm]?jsx?$/;
|
|
44
|
+
const slash = (path) => path.replaceAll(String.fromCharCode(92), '/');
|
|
45
|
+
/** Whether `url` is project TypeScript: a TypeScript file that is not inside a dependency. */
|
|
46
|
+
function isProjectSource(url) {
|
|
47
|
+
if (url === undefined || !url.startsWith('file:'))
|
|
48
|
+
return false;
|
|
49
|
+
const path = slash(fileURLToPath(url));
|
|
50
|
+
return sourceFile.test(path) && !path.includes('/node_modules/');
|
|
51
|
+
}
|
|
52
|
+
let installed;
|
|
53
|
+
/**
|
|
54
|
+
* Teaches Node's own loading of TypeScript two things a bundler does: a relative import without an extension
|
|
55
|
+
* (`export * from './database'`) finds the `.ts` file, and `import.meta.env` reads the environment of the laws. Both
|
|
56
|
+
* apply to project TypeScript only, never to anything under `node_modules`. Needs `module.registerHooks`
|
|
57
|
+
* (Node 22.15, 23.5 or later); on an older Node the hooks are skipped and such imports fail as they did before.
|
|
58
|
+
* Returns whether the hooks are in place. Registers once per thread.
|
|
59
|
+
*/
|
|
60
|
+
export function installLoaderHooks() {
|
|
61
|
+
if (installed !== undefined)
|
|
62
|
+
return installed;
|
|
63
|
+
installed = false;
|
|
64
|
+
const { registerHooks } = nodeModule;
|
|
65
|
+
if (typeof registerHooks !== 'function')
|
|
66
|
+
return installed;
|
|
67
|
+
registerHooks({
|
|
68
|
+
resolve(specifier, context, nextResolve) {
|
|
69
|
+
try {
|
|
70
|
+
return nextResolve(specifier, context);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (!specifier.startsWith('.') || !isProjectSource(context.parentURL))
|
|
74
|
+
throw error;
|
|
75
|
+
const stem = specifier.replace(javascriptEnding, '');
|
|
76
|
+
const candidates = unresolved.map((ending) => `${specifier}${ending}`);
|
|
77
|
+
// `./a.js` names a `.ts` file in TypeScript, as `./a` does for a bundler.
|
|
78
|
+
if (stem !== specifier)
|
|
79
|
+
candidates.push(`${stem}.ts`, `${stem}.tsx`, `${stem}.mts`);
|
|
80
|
+
for (const candidate of candidates) {
|
|
81
|
+
try {
|
|
82
|
+
return nextResolve(candidate, context);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// The next candidate.
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
load(url, context, nextLoad) {
|
|
92
|
+
const loaded = nextLoad(url, context);
|
|
93
|
+
if (loaded.source === undefined || loaded.source === null || !isProjectSource(url))
|
|
94
|
+
return loaded;
|
|
95
|
+
const text = typeof loaded.source === 'string' ? loaded.source : new TextDecoder().decode(loaded.source);
|
|
96
|
+
if (!text.includes('import.meta.env'))
|
|
97
|
+
return loaded;
|
|
98
|
+
return { ...loaded, source: text.replace(/\bimport\.meta\.env\b/g, `globalThis.${importMetaEnvGlobal}`) };
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
installed = true;
|
|
102
|
+
return installed;
|
|
103
|
+
}
|
|
104
|
+
/** Everything a law needs before its module loads: the hooks and the environment. */
|
|
105
|
+
export function prepareRuntime(env) {
|
|
106
|
+
installLoaderHooks();
|
|
107
|
+
setImportMetaEnv(env);
|
|
108
|
+
}
|
package/env.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The type of `import.meta.env` in code that laws reach. tslaws adds this file to a build when the project declares no
|
|
2
|
+
// `ImportMeta.env` of its own (Vite's `vite/client` and rsbuild's types do). Reference it from the project to give an
|
|
3
|
+
// editor the same type: `/// <reference types="tslaws/env" />`.
|
|
4
|
+
interface ImportMetaEnv {
|
|
5
|
+
// Any, as in Vite's own declaration: a variable is usually a string, but the project knows which, and a narrower index
|
|
6
|
+
// type would turn every `import.meta.env.VITE_X` into a type error in code that compiles under a bundler.
|
|
7
|
+
readonly [key: string]: any;
|
|
8
|
+
readonly MODE: string;
|
|
9
|
+
readonly DEV: boolean;
|
|
10
|
+
readonly PROD: boolean;
|
|
11
|
+
readonly SSR: boolean;
|
|
12
|
+
readonly BASE_URL: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface ImportMeta {
|
|
16
|
+
readonly env: ImportMetaEnv;
|
|
17
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tslaws",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Runs and checks `law` declarations compiled by tsc-laws: property tests, SMT proofs, tamper lock.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"tslaws": "bin/tslaws.js"
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
"files": [
|
|
9
9
|
"bin",
|
|
10
10
|
"dist",
|
|
11
|
+
"env.d.ts",
|
|
11
12
|
"hooks",
|
|
12
13
|
"ui"
|
|
13
14
|
],
|
|
@@ -42,6 +43,9 @@
|
|
|
42
43
|
"types": "./dist/adapters/element.d.ts",
|
|
43
44
|
"default": "./dist/adapters/element.js"
|
|
44
45
|
},
|
|
46
|
+
"./env": {
|
|
47
|
+
"types": "./env.d.ts"
|
|
48
|
+
},
|
|
45
49
|
"./internal/*": "./dist/*.js",
|
|
46
50
|
"./package.json": "./package.json"
|
|
47
51
|
},
|
|
@@ -73,11 +77,11 @@
|
|
|
73
77
|
}
|
|
74
78
|
},
|
|
75
79
|
"optionalDependencies": {
|
|
76
|
-
"tslaws-compiler-darwin-arm64": "0.
|
|
77
|
-
"tslaws-compiler-darwin-x64": "0.
|
|
78
|
-
"tslaws-compiler-linux-arm64-gnu": "0.
|
|
79
|
-
"tslaws-compiler-linux-x64-gnu": "0.
|
|
80
|
-
"tslaws-compiler-win32-x64-msvc": "0.
|
|
80
|
+
"tslaws-compiler-darwin-arm64": "0.10.0",
|
|
81
|
+
"tslaws-compiler-darwin-x64": "0.10.0",
|
|
82
|
+
"tslaws-compiler-linux-arm64-gnu": "0.10.0",
|
|
83
|
+
"tslaws-compiler-linux-x64-gnu": "0.10.0",
|
|
84
|
+
"tslaws-compiler-win32-x64-msvc": "0.10.0"
|
|
81
85
|
},
|
|
82
86
|
"publishConfig": {
|
|
83
87
|
"access": "public"
|