tslaws 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +183 -187
  2. package/dist/api.d.ts +86 -0
  3. package/dist/api.js +78 -0
  4. package/dist/badge.d.ts +111 -0
  5. package/dist/badge.js +288 -0
  6. package/dist/browser.d.ts +5 -2
  7. package/dist/browser.js +403 -173
  8. package/dist/browserApi.d.ts +305 -0
  9. package/dist/browserApi.js +456 -0
  10. package/dist/browserServer.d.ts +13 -0
  11. package/dist/browserServer.js +406 -0
  12. package/dist/certificates.js +50 -28
  13. package/dist/chc.d.ts +13 -1
  14. package/dist/chc.js +40 -8
  15. package/dist/check.js +64 -36
  16. package/dist/cli.d.ts +16 -0
  17. package/dist/cli.js +78 -1
  18. package/dist/compile.js +46 -5
  19. package/dist/coverage.d.ts +17 -0
  20. package/dist/coverage.js +297 -24
  21. package/dist/derived.d.ts +2 -0
  22. package/dist/derived.js +9 -4
  23. package/dist/generators.d.ts +5 -1
  24. package/dist/generators.js +50 -4
  25. package/dist/githubCli.js +88 -15
  26. package/dist/isolate.d.ts +5 -0
  27. package/dist/isolate.js +1 -1
  28. package/dist/lawHost.d.ts +2 -0
  29. package/dist/lawHost.js +32 -21
  30. package/dist/lawRuntime.d.ts +6 -0
  31. package/dist/lawRuntime.js +86 -7
  32. package/dist/nativeZ3.d.ts +11 -0
  33. package/dist/nativeZ3.js +162 -0
  34. package/dist/plan.d.ts +7 -0
  35. package/dist/plan.js +11 -0
  36. package/dist/pluginHooks.d.ts +4 -0
  37. package/dist/pluginHooks.js +13 -4
  38. package/dist/proofCache.d.ts +24 -0
  39. package/dist/proofCache.js +135 -0
  40. package/dist/property.d.ts +2 -2
  41. package/dist/property.js +33 -8
  42. package/dist/propertyWorker.js +14 -8
  43. package/dist/sandbox.d.ts +1 -1
  44. package/dist/sandbox.js +48 -8
  45. package/dist/seal.js +47 -8
  46. package/dist/smt.d.ts +16 -2
  47. package/dist/smt.js +241 -31
  48. package/dist/symbolic.d.ts +38 -3
  49. package/dist/symbolic.js +504 -47
  50. package/dist/types.d.ts +9 -0
  51. package/package.json +7 -7
package/dist/githubCli.js CHANGED
@@ -25,9 +25,10 @@ import { execFileSync } from 'node:child_process';
25
25
  import { join } from 'node:path';
26
26
  import { exemptionsOf } from "./check.js";
27
27
  import { checkIsolated, readReport } from "./isolate.js";
28
+ import { useSandbox } from "./sandbox.js";
28
29
  import { extendsTarget, readConfig } from "./coverage.js";
29
30
  import { discoverFromFiles, discoverySignature } from "./projects.js";
30
- import { readManifest } from "./compile.js";
31
+ import { build, readManifest } from "./compile.js";
31
32
  import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, renderStickyAll, resolveNames, stickyMarkerFor, } from "./github.js";
32
33
  import { lockLevels } from "./lawKinds.js";
33
34
  import { acceptChanges, lawKey, lockChanges, readLock, writeLockValue } from "./lock.js";
@@ -204,8 +205,7 @@ function plan(ctx, units, dirOf) {
204
205
  return { active, all };
205
206
  }
206
207
  /** The laws a project has, as this process sees them: a compile that runs none of the project. A report is held to it. */
207
- function expectedOf(unit) {
208
- const state = projectState(unit.options);
208
+ function expectedOf(state) {
209
209
  return {
210
210
  laws: new Set(state.laws.map((law) => lawKey(law.file, law.name))),
211
211
  lock: new Set(Object.keys(state.lock?.laws ?? {})),
@@ -238,20 +238,67 @@ function resultsOf(ctx, file, mode, sha) {
238
238
  * The report of one project's laws: from the results file when `--results` names one, else from a run in a child with no
239
239
  * credentials. Either way it is validated as data before anything acts on it.
240
240
  */
241
- async function runLaws(ctx, unit, mode, sha) {
241
+ async function runLaws(ctx, unit, mode, sha, state, only) {
242
242
  const file = ctx.flags.get('results');
243
243
  if (typeof file !== 'string')
244
- return checkIsolated(unit.options, true, expectedOf(unit));
245
- const entry = Object.hasOwn(resultsOf(ctx, file, mode, sha).projects, unit.path)
246
- ? resultsOf(ctx, file, mode, sha).projects[unit.path]
247
- : undefined;
244
+ return runIsolated(unit, state, only);
245
+ return readReport(resultEntry(ctx, file, unit, mode, sha).report, expectedFor(state, only));
246
+ }
247
+ /**
248
+ * The merge job's report for the laws it has to prove. With a results file, a project the laws job reported nothing for
249
+ * has no report (undefined), and a report may lack a law: the caller holds every law without a result, so a results file
250
+ * that falls short fails closed per law instead of failing the whole run. Anything else wrong with it still throws.
251
+ */
252
+ async function mergeLaws(ctx, unit, sha, state, only) {
253
+ const file = ctx.flags.get('results');
254
+ if (typeof file !== 'string')
255
+ return runIsolated(unit, state, only);
256
+ const entry = resultEntry(ctx, file, unit, 'merge', sha);
257
+ if (entry.report === undefined)
258
+ return undefined;
259
+ return readReport(entry.report, { ...expectedFor(state), required: new Set() });
260
+ }
261
+ /** One project's entry of the results file, once it is known to come from this commit and this lock. */
262
+ function resultEntry(ctx, file, unit, mode, sha) {
263
+ const results = resultsOf(ctx, file, mode, sha);
264
+ const entry = Object.hasOwn(results.projects, unit.path) ? results.projects[unit.path] : undefined;
248
265
  if (entry === undefined)
249
266
  throw new Error(`${file} has no results for ${label(unit)}`);
250
267
  if (typeof entry.error === 'string')
251
268
  throw new Error(entry.error);
252
269
  if (entry.lockSha !== lockShaOf(unit))
253
270
  throw new Error(`${label(unit)}'s lock is not the one its laws were run against`);
254
- return readReport(entry.report, expectedOf(unit));
271
+ return entry;
272
+ }
273
+ /** What a report must hold: every law, or just the ones a partial run was asked for. */
274
+ const expectedFor = (state, only) => ({
275
+ ...expectedOf(state),
276
+ ...(only === undefined ? {} : { required: new Set(only) }),
277
+ });
278
+ /** The laws of a project run in a child with no credentials: all of them, or only the laws with these keys. */
279
+ function runIsolated(unit, state, only) {
280
+ const options = only === undefined ? unit.options : { ...unit.options, onlyKeys: [...only] };
281
+ return checkIsolated(options, true, expectedFor(state, only));
282
+ }
283
+ /**
284
+ * What a run that proves nothing still has to find out, as the run of every law used to: that the project builds, and
285
+ * that the sandbox can be enforced here. A failure is thrown, so the run fails as it did when every law ran.
286
+ */
287
+ function assertRunnable(unit, state) {
288
+ if (state.laws.length === 0)
289
+ return;
290
+ useSandbox(unit.options);
291
+ const built = build(unit.options.compiler, unit.options.files, unit.options.cwd);
292
+ if (!built.ok)
293
+ throw new Error(`the project does not compile:
294
+ ${built.diagnostics}`);
295
+ }
296
+ /**
297
+ * The laws a merge has to run in a project: the ones the lock does not record as they are. A removal or an exemption runs
298
+ * nothing, and a law the lock records is neither proposed nor accepted by a merge, so proving it again would change nothing.
299
+ */
300
+ function lawsToProve(changes) {
301
+ return changes.filter((c) => c.kind === 'law' && c.reason !== 'removed').map((c) => c.key);
255
302
  }
256
303
  /** `--results-out <file>`: run the laws of every project and write the reports, doing nothing else. Needs no token. */
257
304
  async function collect(ctx, mode, file) {
@@ -262,7 +309,17 @@ async function collect(ctx, mode, file) {
262
309
  for (const { unit } of active) {
263
310
  const entry = { lockSha: lockShaOf(unit) };
264
311
  try {
265
- entry.report = await checkIsolated(unit.options, true, expectedOf(unit));
312
+ const state = projectState(unit.options);
313
+ if (mode === 'report')
314
+ entry.report = await runIsolated(unit, state);
315
+ else {
316
+ // A merge acts only on what the lock does not record, which it works out again from the same lock and files.
317
+ const only = lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels));
318
+ if (only.length > 0)
319
+ entry.report = await runIsolated(unit, state, only);
320
+ else
321
+ assertRunnable(unit, state);
322
+ }
266
323
  }
267
324
  catch (error) {
268
325
  entry.error = error instanceof Error ? error.message : String(error);
@@ -284,8 +341,8 @@ async function report(ctx) {
284
341
  const ran = [];
285
342
  for (const a of active) {
286
343
  try {
287
- const checked = await runLaws(ctx, a.unit, 'report', sha);
288
344
  const state = projectState(a.unit.options);
345
+ const checked = await runLaws(ctx, a.unit, 'report', sha, state);
289
346
  ran.push({
290
347
  active: a,
291
348
  checked,
@@ -1010,11 +1067,20 @@ async function merge(ctx) {
1010
1067
  }
1011
1068
  writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
1012
1069
  }
1070
+ // What the lock does not record yet is all a merge acts on, and the files alone tell what that is. A project the
1071
+ // lock already records runs nothing, and otherwise only the laws that changed run: a law the lock records is
1072
+ // neither proposed nor accepted here, so proving it again would change nothing.
1013
1073
  let checked;
1014
1074
  let state;
1075
+ let changes;
1015
1076
  try {
1016
- checked = await runLaws(ctx, unit, 'merge', sha);
1017
1077
  state = projectState(unit.options);
1078
+ changes = lockChanges(state.lock, state.laws, state.exempt, state.levels);
1079
+ const toRun = lawsToProve(changes);
1080
+ if (toRun.length > 0)
1081
+ checked = await mergeLaws(ctx, unit, sha, state, toRun);
1082
+ else
1083
+ assertRunnable(unit, state);
1018
1084
  }
1019
1085
  catch (error) {
1020
1086
  if (!monorepo)
@@ -1022,9 +1088,9 @@ async function merge(ctx) {
1022
1088
  stop(`tslaws: ${label(unit)} could not be checked: ${error instanceof Error ? error.message : String(error)}`);
1023
1089
  continue;
1024
1090
  }
1025
- const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked, unit.path);
1091
+ const proposals = proposalsOf(changes, checked, unit.path);
1026
1092
  if (proposals.length === 0) {
1027
- ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law\n`);
1093
+ ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law; no law ran\n`);
1028
1094
  continue;
1029
1095
  }
1030
1096
  // Each record's author is checked again now, against this project's own approvers: someone who lost write access,
@@ -1047,7 +1113,14 @@ async function merge(ctx) {
1047
1113
  const approvals = dispatched
1048
1114
  ? new Map(proposals.map((p) => [p.fingerprint, actor]))
1049
1115
  : acceptedFingerprints(records, unit.path);
1050
- const decision = decide(proposals, config, approvals);
1116
+ // A law that had to run and has no result (the laws job reported nothing for it) is held whatever `requirePassing` says.
1117
+ const unproven = (p) => p.outcome === undefined && p.kind === 'law' && p.reason !== 'removed';
1118
+ const decision = decide(proposals.filter((p) => !unproven(p)), config, approvals);
1119
+ for (const proposal of proposals.filter(unproven))
1120
+ decision.held.push({
1121
+ proposal,
1122
+ why: 'changed after the laws job ran, or has no result there; run the workflow again',
1123
+ });
1051
1124
  const wins = proposals.filter((p) => decision.accept.has(p.fingerprint));
1052
1125
  if (wins.length > 0) {
1053
1126
  const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
package/dist/isolate.d.ts CHANGED
@@ -10,6 +10,11 @@ export interface Expected {
10
10
  laws: ReadonlySet<string>;
11
11
  lock: ReadonlySet<string>;
12
12
  exempt: ReadonlySet<string>;
13
+ /**
14
+ * The laws the report must name, when it covers only some of them (a partial run, see `onlyKeys`). Default: every law.
15
+ * It may still name any other law of the project.
16
+ */
17
+ required?: ReadonlySet<string>;
13
18
  }
14
19
  /**
15
20
  * A report as plain data, or an error. A child (or a results file) is untrusted, so each result is rebuilt from the fields
package/dist/isolate.js CHANGED
@@ -200,7 +200,7 @@ export function readReport(value, expected) {
200
200
  results.push(result);
201
201
  }
202
202
  const got = new Set(results.filter((r) => r.status !== 'uncovered').map((r) => lawKey(r.file, r.name)));
203
- for (const key of expected.laws)
203
+ for (const key of expected.required ?? expected.laws)
204
204
  if (!got.has(key))
205
205
  return fail(`${key} has no result`);
206
206
  const compileOk = report.compileOk;
package/dist/lawHost.d.ts CHANGED
@@ -26,6 +26,8 @@ export type HostRequest = {
26
26
  plans: Plan[];
27
27
  options: CheckOptions;
28
28
  env: ImportMetaEnv;
29
+ /** Identifies the build; unchanged keys reuse already-loaded compiled modules instead of evicting require.cache per law. */
30
+ buildKey?: string;
29
31
  } | {
30
32
  type: 'holds';
31
33
  token: string;
package/dist/lawHost.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { readFileSync } from 'node:fs';
6
6
  import { createRequire } from 'node:module';
7
7
  import { join } from 'node:path';
8
- import { installLawRuntime, loadResolver, runtimeFile, useTransforms } from "./lawRuntime.js";
8
+ import { evictLoaded, installLawRuntime, loadResolver, runtimeFile, useTransforms, } from "./lawRuntime.js";
9
9
  import { arbitraryOf } from "./plan.js";
10
10
  import { isDiscard, jsPath, runLaw, summarise } from "./propertyRun.js";
11
11
  import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
@@ -16,6 +16,7 @@ const guard = new Guard();
16
16
  let secret;
17
17
  const transformed = new Map();
18
18
  const loaded = new Map();
19
+ const loadedBuildKeys = new Map();
19
20
  let guarded = false;
20
21
  // The channel is the only way out. Keep it, and take it from the code that runs here so it cannot answer for the host.
21
22
  // `process.send` calls `this._send`, which lockDown hides, so the inner function is kept as well.
@@ -114,30 +115,40 @@ function lookup(kind, file) {
114
115
  throw new Error(prepared.error);
115
116
  return prepared.code;
116
117
  }
117
- function load(outDir, law, env, fresh) {
118
+ function load(outDir, law, env, fresh, buildKey) {
118
119
  const key = `${outDir}\0${law.file}\0${law.symbol ?? law.name}`;
120
+ const sameBuild = buildKey !== undefined && loadedBuildKeys.get(outDir) === buildKey;
119
121
  const known = loaded.get(key);
120
- if (!fresh && known !== undefined)
122
+ if ((!fresh || sameBuild) && known !== undefined) {
123
+ setImportMetaEnv(env);
121
124
  return known;
125
+ }
122
126
  setImportMetaEnv(env);
123
- installLoaderHooks();
124
- useTransforms({
125
- source: (file) => lookup('ts', file),
126
- plugin: (file, _cwd, _plugins, format) => lookup(format, file),
127
- });
128
- installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
129
- // Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
130
- loadResolver();
131
- // From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
132
- if (!guarded) {
133
- guarded = true;
134
- installGuard(guard);
135
- lockDown();
127
+ if (!sameBuild) {
128
+ installLoaderHooks();
129
+ useTransforms({
130
+ source: (file) => lookup('ts', file),
131
+ plugin: (file, _cwd, _plugins, format) => lookup(format, file),
132
+ });
133
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
134
+ // Before the guard: the resolver loads TypeScript, which needs Node modules that no law may load.
135
+ loadResolver();
136
+ // From here on only reviewed files load. Installed after the runtime's own hooks, so it sees what they resolve.
137
+ if (!guarded) {
138
+ guarded = true;
139
+ installGuard(guard);
140
+ lockDown();
141
+ }
142
+ // The process outlives a check, and the code may have been recompiled since the last one.
143
+ evictLoaded(require.cache, outDir);
144
+ for (const k of loaded.keys())
145
+ if (k.startsWith(`${outDir}\0`))
146
+ loaded.delete(k);
147
+ if (buildKey !== undefined)
148
+ loadedBuildKeys.set(outDir, buildKey);
149
+ else
150
+ loadedBuildKeys.delete(outDir);
136
151
  }
137
- // The process outlives a check, and the code may have been recompiled since the last one.
138
- for (const file of Object.keys(require.cache))
139
- if (file.startsWith(outDir))
140
- delete require.cache[file];
141
152
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
142
153
  if (typeof fn !== 'function')
143
154
  throw new Error('compiled module does not export the law');
@@ -171,7 +182,7 @@ process.on('message', async (request) => {
171
182
  const { id } = request;
172
183
  let fn;
173
184
  try {
174
- fn = load(request.outDir, request.law, request.env, request.type === 'run');
185
+ fn = load(request.outDir, request.law, request.env, request.type === 'run', request.type === 'run' ? request.buildKey : undefined);
175
186
  }
176
187
  catch (error) {
177
188
  send({ id, error: message(error), phase: 'load' });
@@ -25,6 +25,12 @@ export interface Transforms {
25
25
  export declare function transformSource(file: string, extension: string): string;
26
26
  /** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
27
27
  export declare function useTransforms(next: Transforms): void;
28
+ /**
29
+ * Drops from `cache` what a run must load again: every file under `outDir` (the build may have recompiled it) and every
30
+ * file the plugin hooks loaded. A template keeps the modules it imported; left cached it would share them with no one
31
+ * once the law's own copies are fresh.
32
+ */
33
+ export declare function evictLoaded(cache: Record<string, unknown>, outDir: string): void;
28
34
  /** The runtime a project registered, as the last build left it. */
29
35
  export declare function runtimeOf(cwd: string): LawRuntime | undefined;
30
36
  /** Loads what the resolver needs, while no law is running. A law process calls it once its project is installed. */
@@ -30,11 +30,34 @@ export function transformSource(file, extension) {
30
30
  define: importMetaDefines(file),
31
31
  }).code;
32
32
  }
33
- let transforms = { source: transformSource, plugin: transformPluginFile };
33
+ let transforms = {
34
+ source: transformSource,
35
+ plugin: transformPluginFile,
36
+ };
34
37
  /** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
35
38
  export function useTransforms(next) {
36
39
  transforms = next;
37
40
  }
41
+ /** The project files a `bundlerPlugins` hook loaded in this thread: they sit outside the output directory. */
42
+ const pluginLoaded = new Set();
43
+ /** Runs the plugin transform and remembers the file, so the next run can drop it from the module cache. */
44
+ function transformPlugin(...args) {
45
+ pluginLoaded.add(args[0]);
46
+ return transforms.plugin(...args);
47
+ }
48
+ /**
49
+ * Drops from `cache` what a run must load again: every file under `outDir` (the build may have recompiled it) and every
50
+ * file the plugin hooks loaded. A template keeps the modules it imported; left cached it would share them with no one
51
+ * once the law's own copies are fresh.
52
+ */
53
+ export function evictLoaded(cache, outDir) {
54
+ for (const file of Object.keys(cache))
55
+ if (file.startsWith(outDir))
56
+ delete cache[file];
57
+ for (const file of pluginLoaded)
58
+ delete cache[file];
59
+ pluginLoaded.clear();
60
+ }
38
61
  /** The runtime a project registered, as the last build left it. */
39
62
  export function runtimeOf(cwd) {
40
63
  return projects.get(outDirOf(cwd));
@@ -75,7 +98,13 @@ export function installLawRuntime(runtime) {
75
98
  if (hooked)
76
99
  return;
77
100
  hooked = true;
78
- installPluginHooks({ ownerOf, beside, transform: (...args) => transforms.plugin(...args) });
101
+ installPluginHooks({
102
+ ownerOf,
103
+ beside,
104
+ twin: twinOf,
105
+ twinOfSpecifier,
106
+ transform: transformPlugin,
107
+ });
79
108
  const internals = Module;
80
109
  const original = internals._resolveFilename;
81
110
  internals._resolveFilename = function (request, parent, ...rest) {
@@ -84,15 +113,19 @@ export function installLawRuntime(runtime) {
84
113
  const mapped = bare && namedInPaths(request, parent) ? resolveThroughTypeScript(request, parent) : undefined;
85
114
  if (mapped !== undefined)
86
115
  return mapped;
116
+ let found;
87
117
  try {
88
- return original.call(this, request, parent, ...rest);
118
+ found = original.call(this, request, parent, ...rest);
89
119
  }
90
120
  catch (error) {
91
- const found = bare ? resolveThroughTypeScript(request, parent) : beside(request, parent);
92
- if (found === undefined)
121
+ const other = bare
122
+ ? resolveThroughTypeScript(request, parent)
123
+ : (beside(request, parent) ?? twinOfSpecifier(request, parent?.filename));
124
+ if (other === undefined)
93
125
  throw error;
94
- return found;
126
+ found = other;
95
127
  }
128
+ return twinOf(found, parent?.filename) ?? found;
96
129
  };
97
130
  // Node loads an unknown extension as JavaScript. A project format (`.tsrx`) goes through its `bundlerPlugins` instead.
98
131
  const plain = internals._extensions['.js'];
@@ -101,7 +134,7 @@ export function installLawRuntime(runtime) {
101
134
  if (!pluginExtensionNeeded(extension))
102
135
  return plain.call(this, module, file);
103
136
  const owner = ownerOf(file);
104
- module._compile(transforms.plugin(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], 'cjs'), file);
137
+ module._compile(transformPlugin(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], 'cjs'), file);
105
138
  };
106
139
  for (const extension of ['.ts', '.tsx', '.mts', '.cts'])
107
140
  internals._extensions[extension] = (module, file) => {
@@ -114,6 +147,52 @@ function ownerOf(file) {
114
147
  const holding = all.filter((p) => file.startsWith(p.cwd + sep)).sort((a, b) => b.cwd.length - a.cwd.length);
115
148
  return holding[0] ?? all.at(-1);
116
149
  }
150
+ /**
151
+ * The compiled copy of a project `.ts` file that a file in a project format (`.tsrx`) imports. The plugin's output keeps
152
+ * its imports as written, so `../i18n` finds the source, which the sandbox does not serve and which would be a second
153
+ * instance beside the one the law gets. The build's copy is the same module the law's own imports reach, and it is
154
+ * already in the reviewed set (the build's tree). Nothing else is remapped: undefined when `importer` is not such a
155
+ * file, `file` is not a source the build compiled, or no copy exists.
156
+ */
157
+ function twinOf(file, importer) {
158
+ if (importer === undefined || !pluginExtensionNeeded(extname(importer)))
159
+ return undefined;
160
+ if (!/\.[cm]?tsx?$/.test(file) || /\.d\.[cm]?ts$/.test(file))
161
+ return undefined;
162
+ const owner = ownerOf(importer);
163
+ if (owner === undefined || !file.startsWith(owner.cwd + sep))
164
+ return undefined;
165
+ const root = compiledRoot(owner);
166
+ if (file.startsWith(root + sep))
167
+ return undefined;
168
+ const twin = resolve(root, relative(owner.cwd, file)).replace(/\.[cm]?tsx?$/, '.js');
169
+ return existsSync(twin) ? twin : undefined;
170
+ }
171
+ const jsToTs = {
172
+ '.js': ['.ts', '.tsx'],
173
+ '.jsx': ['.tsx'],
174
+ '.mjs': ['.mts'],
175
+ '.cjs': ['.cts'],
176
+ };
177
+ /**
178
+ * The twin for a NodeNext-style specifier a plugin's output keeps (`./i18n.js` for `i18n.ts`): Node finds no `.js` file
179
+ * beside the source, so the specifier names the source it stands for, and that source's compiled copy is used.
180
+ */
181
+ function twinOfSpecifier(request, importer) {
182
+ if (importer === undefined || !request.startsWith('.'))
183
+ return undefined;
184
+ const named = resolve(dirname(importer), request);
185
+ const extension = extname(named);
186
+ for (const replacement of jsToTs[extension] ?? []) {
187
+ const source = named.slice(0, -extension.length) + replacement;
188
+ if (!existsSync(source))
189
+ continue;
190
+ const twin = twinOf(source, importer);
191
+ if (twin !== undefined)
192
+ return twin;
193
+ }
194
+ return undefined;
195
+ }
117
196
  /**
118
197
  * A relative import of a file the compiler does not write out (a template, a stylesheet) names the file beside the
119
198
  * source, not beside the compiled output.
@@ -0,0 +1,11 @@
1
+ /** Resolves the native `z3` binary path if installed and enabled, else undefined. */
2
+ export declare function nativeZ3Path(env?: NodeJS.ProcessEnv): string | undefined;
3
+ /** Fingerprint of the active Z3 backend for proof cache keys. */
4
+ export declare function z3Fingerprint(env?: NodeJS.ProcessEnv): string;
5
+ /** Terminates idle native Z3 processes (e.g. after a solver crash). */
6
+ export declare function closeNativeZ3(): void;
7
+ /** Runs one SMT-LIB query against a pooled native Z3 process; rejects with `Unsupported` on timeout. */
8
+ export declare function solveNative(binary: string, query: string, values: string, timeoutMs: number, onTimeout: () => Error): Promise<{
9
+ out: string;
10
+ vals: string;
11
+ }>;
@@ -0,0 +1,162 @@
1
+ // Optional native Z3 backend: uses a persistent pooled `z3 -in -smt2` process with `(reset)` between queries when a
2
+ // native `z3` binary is available (`TSLAWS_Z3` or `z3` on PATH). Faster and far less memory-hungry than the
3
+ // WebAssembly build in `smtWorker.ts`, lifting the 4-worker RAM cap. Falls back seamlessly to WASM when absent or
4
+ // when `TSLAWS_Z3=wasm`.
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { statSync } from 'node:fs';
7
+ import { SolverCrash } from "./chc.js";
8
+ import { jobs, lowerPriority, WorkerPool } from "./pool.js";
9
+ const sentinel = '__TSLAWS_Z3_DONE__';
10
+ const modelSentinel = '__TSLAWS_Z3_VALS__';
11
+ let detectedPath;
12
+ let detectedEnv;
13
+ /** Resolves the native `z3` binary path if installed and enabled, else undefined. */
14
+ export function nativeZ3Path(env = process.env) {
15
+ const configured = env.TSLAWS_Z3?.trim();
16
+ if (configured === 'wasm' || configured === '0' || configured === 'false')
17
+ return undefined;
18
+ if (detectedPath !== undefined && detectedEnv === configured)
19
+ return detectedPath ?? undefined;
20
+ detectedEnv = configured;
21
+ const candidate = configured !== undefined && configured !== '' ? configured : 'z3';
22
+ try {
23
+ const probe = spawnSync(candidate, ['--version'], {
24
+ encoding: 'utf8',
25
+ timeout: 3000,
26
+ windowsHide: true,
27
+ });
28
+ if (probe.error === undefined && probe.status === 0 && /Z3 version/i.test(probe.stdout ?? '')) {
29
+ detectedPath = candidate;
30
+ return candidate;
31
+ }
32
+ }
33
+ catch {
34
+ // Native Z3 is not available; fall back to WebAssembly.
35
+ }
36
+ detectedPath = null;
37
+ return undefined;
38
+ }
39
+ /** Fingerprint of the active Z3 backend for proof cache keys. */
40
+ export function z3Fingerprint(env = process.env) {
41
+ const bin = nativeZ3Path(env);
42
+ if (bin === undefined)
43
+ return 'z3-wasm';
44
+ try {
45
+ const st = statSync(bin);
46
+ return `z3-native:${bin}:${st.size}:${st.mtimeMs}`;
47
+ }
48
+ catch {
49
+ return `z3-native:${bin}`;
50
+ }
51
+ }
52
+ class NativeZ3Process {
53
+ child;
54
+ buffer = '';
55
+ alive = true;
56
+ waiter;
57
+ constructor(binary) {
58
+ this.child = spawn(binary, ['-in', '-smt2'], {
59
+ stdio: ['pipe', 'pipe', 'pipe'],
60
+ windowsHide: true,
61
+ });
62
+ lowerPriority(this.child.pid);
63
+ this.child.unref();
64
+ let stderr = '';
65
+ this.child.stderr?.setEncoding('utf8').on('data', (chunk) => {
66
+ stderr = (stderr + chunk).slice(-2000);
67
+ });
68
+ this.child.stdout?.setEncoding('utf8').on('data', (chunk) => {
69
+ this.buffer += chunk;
70
+ this.drain();
71
+ });
72
+ const fail = (why) => {
73
+ this.alive = false;
74
+ const pending = this.waiter;
75
+ this.waiter = undefined;
76
+ pending?.reject(new SolverCrash(`the native Z3 solver crashed: ${why}${stderr ? ` (${stderr.trim()})` : ''}`));
77
+ };
78
+ this.child.on('error', (error) => fail(error.message));
79
+ this.child.on('exit', (code, signal) => fail(`exited with ${signal ?? `code ${code}`}`));
80
+ this.child.stdin?.on('error', () => undefined);
81
+ }
82
+ drain() {
83
+ if (this.waiter === undefined)
84
+ return;
85
+ const token = `"${this.waiter.marker}"`;
86
+ const idx = this.buffer.indexOf(token);
87
+ if (idx < 0)
88
+ return;
89
+ const before = this.buffer.slice(0, idx).trim();
90
+ const afterNl = this.buffer.indexOf('\n', idx + token.length);
91
+ this.buffer = afterNl < 0 ? '' : this.buffer.slice(afterNl + 1);
92
+ const { resolve } = this.waiter;
93
+ this.waiter = undefined;
94
+ resolve(before);
95
+ }
96
+ sendAndWait(script, marker) {
97
+ if (!this.alive || this.child.stdin === null)
98
+ return Promise.reject(new SolverCrash('native Z3 process closed'));
99
+ return new Promise((resolve, reject) => {
100
+ this.waiter = { marker, resolve, reject };
101
+ this.child.stdin.write(`${script}\n(echo "${marker}")\n`);
102
+ this.drain();
103
+ });
104
+ }
105
+ async solve(query, values) {
106
+ const out = await this.sendAndWait(`(reset)\n${query}`, sentinel);
107
+ const vals = out.startsWith('sat') && values !== '' ? await this.sendAndWait(values, modelSentinel) : '';
108
+ return { out, vals };
109
+ }
110
+ terminate() {
111
+ this.alive = false;
112
+ try {
113
+ this.child.kill('SIGKILL');
114
+ }
115
+ catch {
116
+ // Already exited.
117
+ }
118
+ }
119
+ }
120
+ let poolBinary;
121
+ let pool;
122
+ function poolFor(binary) {
123
+ if (pool !== undefined && poolBinary === binary)
124
+ return pool;
125
+ pool?.close();
126
+ poolBinary = binary;
127
+ pool = new WorkerPool(() => new NativeZ3Process(binary), jobs, 10000);
128
+ return pool;
129
+ }
130
+ /** Terminates idle native Z3 processes (e.g. after a solver crash). */
131
+ export function closeNativeZ3() {
132
+ pool?.close();
133
+ }
134
+ /** Runs one SMT-LIB query against a pooled native Z3 process; rejects with `Unsupported` on timeout. */
135
+ export async function solveNative(binary, query, values, timeoutMs, onTimeout) {
136
+ const activePool = poolFor(binary);
137
+ const proc = await activePool.acquire();
138
+ let timer;
139
+ let timedOut = false;
140
+ try {
141
+ const timeout = new Promise((_resolve, reject) => {
142
+ timer = setTimeout(() => {
143
+ timedOut = true;
144
+ activePool.discard(proc);
145
+ reject(onTimeout());
146
+ }, timeoutMs + 3000);
147
+ });
148
+ const reply = await Promise.race([proc.solve(query, values), timeout]);
149
+ if (!timedOut)
150
+ activePool.release(proc);
151
+ return reply;
152
+ }
153
+ catch (error) {
154
+ if (!timedOut)
155
+ activePool.discard(proc);
156
+ throw error;
157
+ }
158
+ finally {
159
+ if (timer !== undefined)
160
+ clearTimeout(timer);
161
+ }
162
+ }
package/dist/plan.d.ts CHANGED
@@ -25,9 +25,16 @@ export type Plan = {
25
25
  name: string;
26
26
  fallback?: Plan;
27
27
  security?: true;
28
+ } | {
29
+ k: 'intRange';
30
+ min: number;
31
+ max: number;
28
32
  } | {
29
33
  k: 'array';
30
34
  of: Plan;
35
+ } | {
36
+ k: 'nonEmpty';
37
+ of: Plan;
31
38
  } | {
32
39
  k: 'tuple';
33
40
  required: Plan[];
package/dist/plan.js CHANGED
@@ -10,6 +10,13 @@ export class UnsupportedType extends Error {
10
10
  const numbers = fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer() }, { weight: 2, arbitrary: fc.double({ noNaN: true, noDefaultInfinity: true }) });
11
11
  // `int` from 'tslaws': whole numbers, biased to small ones.
12
12
  arbitraryRegistry().set('int', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER }) }));
13
+ // Built-in refinement types from 'tslaws'.
14
+ arbitraryRegistry().set('nat', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 0, max: 16 }) }, { weight: 3, arbitrary: fc.integer({ min: 0, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }) }));
15
+ arbitraryRegistry().set('posInt', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 1, max: 16 }) }, { weight: 3, arbitrary: fc.integer({ min: 1, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: 1, max: Number.MAX_SAFE_INTEGER }) }));
16
+ arbitraryRegistry().set('nonZeroInt', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: 1, max: 16 }) }, { weight: 4, arbitrary: fc.integer({ min: -16, max: -1 }) }, { weight: 2, arbitrary: fc.integer({ min: 1, max: 1000 }) }, { weight: 2, arbitrary: fc.integer({ min: -1000, max: -1 }) }, { weight: 1, arbitrary: fc.integer({ min: 1, max: Number.MAX_SAFE_INTEGER }) }, { weight: 1, arbitrary: fc.integer({ min: -Number.MAX_SAFE_INTEGER, max: -1 }) }));
17
+ arbitraryRegistry().set('asciiString', fc.string({ maxLength: 24 }));
18
+ arbitraryRegistry().set('nonEmptyString', fc.string({ minLength: 1, maxLength: 24 }));
19
+ arbitraryRegistry().set('finite', fc.double({ noNaN: true, noDefaultInfinity: true }));
13
20
  /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
14
21
  export const wireKey = '$tslawsFn';
15
22
  function pick(samples, args) {
@@ -97,8 +104,12 @@ export function arbitraryOf(plan) {
97
104
  throw new UnsupportedType(`no generator registered for ${plan.name}`);
98
105
  return arbitraryOf(plan.fallback);
99
106
  }
107
+ case 'intRange':
108
+ return fc.integer({ min: Math.ceil(plan.min), max: Math.floor(plan.max) });
100
109
  case 'array':
101
110
  return sequence(arbitraryOf(plan.of), { maxLength: 8 });
111
+ case 'nonEmpty':
112
+ return sequence(arbitraryOf(plan.of), { minLength: 1, maxLength: 8 });
102
113
  case 'tuple': {
103
114
  const required = plan.required.map(arbitraryOf);
104
115
  const optional = plan.optional.map(arbitraryOf);