tslaws 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +8 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +36 -7
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +215 -28
  14. package/dist/cli.d.ts +4 -0
  15. package/dist/cli.js +324 -41
  16. package/dist/compile.d.ts +17 -1
  17. package/dist/compile.js +244 -25
  18. package/dist/coverage.d.ts +55 -3
  19. package/dist/coverage.js +231 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +70 -0
  54. package/dist/projects.js +457 -0
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +13 -2
  58. package/dist/propertyWorker.js +11 -1
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +32 -0
  63. package/dist/runtimeEnv.js +146 -0
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/env.d.ts +17 -0
  122. package/hooks/claude-hook.mjs +2 -0
  123. package/package.json +22 -6
package/dist/compile.js CHANGED
@@ -1,11 +1,16 @@
1
1
  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
- import { dirname, join, resolve } from 'node:path';
4
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } 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 { installLawRuntime, runtimeFile } from "./lawRuntime.js";
11
+ import { commonRoot, readResolution, resolutionCompilerOptions } from "./tsconfigResolve.js";
12
+ import { importMetaEnvGlobal } from "./runtimeEnv.js";
13
+ import { sealLaws } from "./seal.js";
9
14
  /**
10
15
  * Runs the compiler, trying again when the system could not start it. On Windows a freshly built executable can be
11
16
  * briefly unavailable (a scanner holds it, the machine is out of handles), which surfaces as ENOENT or UNKNOWN.
@@ -99,9 +104,7 @@ function assertOneSyntax(files, cwd) {
99
104
  }
100
105
  export function readManifest(compiler, files, cwd) {
101
106
  if (usesBuiltin(compiler, files, cwd))
102
- return files
103
- .filter((f) => isLawFile(f, cwd))
104
- .flatMap((f) => (existsSync(join(cwd, f)) ? lowerFile(f, cwd).laws : []));
107
+ return sealLaws(cwd, files.filter((f) => isLawFile(f, cwd)).flatMap((f) => (existsSync(join(cwd, f)) ? lowerFile(f, cwd).laws : [])));
105
108
  assertOneSyntax(files, cwd);
106
109
  const run = launch(compiler, ['--laws-manifest', ...files], {
107
110
  cwd,
@@ -114,7 +117,7 @@ export function readManifest(compiler, files, cwd) {
114
117
  const text = (run.stdout ?? '').trim();
115
118
  if (text === '')
116
119
  throw new Error(`${compiler} --laws-manifest printed nothing: ${run.stderr ?? ''}`);
117
- return JSON.parse(text).laws;
120
+ return sealLaws(cwd, JSON.parse(text).laws);
118
121
  }
119
122
  const stringOptions = ['jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource'];
120
123
  const booleanOptions = [
@@ -162,12 +165,164 @@ export function compilerFlags(options) {
162
165
  }
163
166
  return flags;
164
167
  }
165
- /** Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. */
168
+ /** Turns emitted ES modules (with `import.meta` already rewritten) into CommonJS. */
169
+ function lowerModule(text, sourcefile) {
170
+ return transformSync(text, { format: 'cjs', target: 'es2022', sourcefile, logLevel: 'silent' }).code;
171
+ }
172
+ /** Where a compiled file came from: the source it mirrors under `root`, which is what `import.meta` should name. */
173
+ function sourceOfOutput(file, outDir, root) {
174
+ const mirrored = join(root, relative(outDir, file));
175
+ const endings = file.endsWith('.mjs')
176
+ ? ['.mts', '.mjs']
177
+ : file.endsWith('.cjs')
178
+ ? ['.cts', '.cjs']
179
+ : ['.ts', '.tsx', '.js', '.jsx'];
180
+ const stem = mirrored.replace(/\.[cm]?js$/, '');
181
+ return endings.map((ending) => `${stem}${ending}`).find((candidate) => existsSync(candidate)) ?? mirrored;
182
+ }
183
+ /** The first top-level `await` of a module (an `await` expression or `for await` outside every function), if any. */
184
+ function topLevelAwait(source) {
185
+ let found;
186
+ const visit = (node) => {
187
+ if (found !== undefined || ts.isFunctionLike(node) || ts.isClassLike(node))
188
+ return;
189
+ if (ts.isAwaitExpression(node) || (ts.isForOfStatement(node) && node.awaitModifier !== undefined))
190
+ found = node;
191
+ else
192
+ ts.forEachChild(node, visit);
193
+ };
194
+ visit(source);
195
+ return found;
196
+ }
197
+ /**
198
+ * Laws and the modules they load run as CommonJS (see `build`), where a module cannot wait at its top level. Said once,
199
+ * in terms of the way out, instead of as the loader's syntax error.
200
+ */
201
+ const awaitAdvice = 'top-level await is not supported in a law or in a module a law imports, because laws load as CommonJS; move the ' +
202
+ 'await into an async function (or into the law body, which may be async)';
203
+ const awaitProblem = (file) => `${file}: error: ${awaitAdvice}`;
204
+ /** What replaces such a module in the output, so the law that loads it fails with the reason and not a syntax error. */
205
+ const awaitStub = (file) => `throw new Error(${JSON.stringify(`${file}: ${awaitAdvice}`)});\n`;
206
+ /**
207
+ * `import.meta` for a module that is not run as written: `env` is the global the runner sets before any law loads (see
208
+ * runtimeEnv.ts), `url`, `filename` and `dirname` name the source file (not the copy in `.tslaws/out`), and any other
209
+ * use of `import.meta` is an object holding those four. Found as syntax so that a string or comment that says the same
210
+ * words is left alone. Returns the new text and whether the module waits at its top level.
211
+ */
212
+ function rewriteImportMeta(text, file, source) {
213
+ const parsed = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, false, ts.ScriptKind.JS);
214
+ const edits = [];
215
+ const env = `globalThis.${importMetaEnvGlobal}`;
216
+ const known = {
217
+ url: JSON.stringify(pathToFileURL(source).href),
218
+ filename: JSON.stringify(source),
219
+ dirname: JSON.stringify(dirname(source)),
220
+ env,
221
+ };
222
+ const isMeta = (node) => ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword && node.name.text === 'meta';
223
+ const visit = (node) => {
224
+ if (ts.isPropertyAccessExpression(node) && isMeta(node.expression) && node.name.text in known)
225
+ edits.push({ start: node.getStart(parsed), end: node.end, text: known[node.name.text] });
226
+ else if (isMeta(node)) {
227
+ const members = Object.entries(known).map(([key, value]) => `${key}: ${value}`);
228
+ edits.push({ start: node.getStart(parsed), end: node.end, text: `({ ${members.join(', ')} })` });
229
+ }
230
+ else
231
+ ts.forEachChild(node, visit);
232
+ };
233
+ visit(parsed);
234
+ const rewritten = edits.reduceRight((out, e) => out.slice(0, e.start) + e.text + out.slice(e.end), text);
235
+ return { text: rewritten, awaits: topLevelAwait(parsed) !== undefined };
236
+ }
237
+ /**
238
+ * CommonJS for ES module text, with `import.meta` rewritten as above. TypeScript does the lowering, not esbuild, so the
239
+ * comments stay: the coverage analysis reads `@tslaws-exempt` from this output.
240
+ */
241
+ function lowerToCommonJs(text, file) {
242
+ return ts.transpileModule(text, {
243
+ fileName: file,
244
+ compilerOptions: {
245
+ module: ts.ModuleKind.CommonJS,
246
+ target: ts.ScriptTarget.ES2022,
247
+ esModuleInterop: true,
248
+ allowJs: true,
249
+ },
250
+ }).outputText;
251
+ }
252
+ /**
253
+ * Lowers what the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed: `.js` becomes
254
+ * CommonJS and the `import.meta` of a `.mjs` (from a `.mts`, kept as an ES module Node can load) is rewritten in place.
255
+ * `outDir` and `root` say where `dir` sits and what it mirrors, so `import.meta` can name the source. Returns one line
256
+ * per module that cannot be lowered.
257
+ */
258
+ export function lowerEmittedModules(dir, where = {}) {
259
+ const problems = [];
260
+ const outDir = where.outDir ?? dir;
261
+ const root = where.root ?? dir;
262
+ const lowerIn = (current) => {
263
+ if (!existsSync(current))
264
+ return;
265
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
266
+ const path = join(current, entry.name);
267
+ if (entry.isDirectory())
268
+ lowerIn(path);
269
+ else if (/\.m?js$/.test(entry.name)) {
270
+ try {
271
+ const { text, awaits } = rewriteImportMeta(readFileSync(path, 'utf8'), path, sourceOfOutput(path, outDir, root));
272
+ if (awaits) {
273
+ problems.push(awaitProblem(slash(relative(outDir, path))));
274
+ writeFileSync(path, awaitStub(slash(relative(outDir, path))));
275
+ }
276
+ else
277
+ writeFileSync(path, entry.name.endsWith('.mjs') ? text : lowerToCommonJs(text, path));
278
+ }
279
+ catch {
280
+ // Output that does not parse (JSX kept because the project sets no `jsx`): the compiler's diagnostics say why.
281
+ }
282
+ }
283
+ }
284
+ };
285
+ lowerIn(dir);
286
+ return problems;
287
+ }
288
+ /** The ambient `ImportMeta.env` declaration that ships with tslaws; also importable as `tslaws/env`. */
289
+ const envTypes = fileURLToPath(new URL('../env.d.ts', import.meta.url));
290
+ /** Whether `text` (compiler output) says `import.meta.env` has no declaration. */
291
+ const lacksEnvTypes = (text) => /TS2339.*'ImportMeta'/.test(text);
292
+ /** Whether `text` (compiler output) says a module waits at its top level while the output is CommonJS (TS1378). */
293
+ const hasTopLevelAwaitError = (text) => /TS1378/.test(text);
294
+ /** Whether `text` (compiler output) says the project uses `import.meta`, which CommonJS output does not allow. */
295
+ const usesImportMeta = (text) => /TS1343/.test(text);
296
+ /**
297
+ * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves.
298
+ * Module resolution follows the project's tsconfig (see tsconfigResolve.ts), for the compiler and, through the runtime
299
+ * hooks, for Node when it loads the output. The built-in compiler always reads the project as ES modules and lowers the
300
+ * output. The native compiler does so only for a project that uses `import.meta` (it reports TS1343 as CommonJS), so
301
+ * every other project builds exactly as before.
302
+ */
166
303
  export function build(compiler, files, cwd) {
304
+ const resolution = readResolution(cwd);
305
+ const result = compile(compiler, files, cwd, resolution);
306
+ const bundlerPlugins = (readConfig(cwd).bundlerPlugins ?? []).map((path) => resolve(cwd, path));
307
+ const runtime = { cwd, options: resolution?.options, outDir: result.outDir, bundlerPlugins };
308
+ installLawRuntime(runtime);
309
+ try {
310
+ writeFileSync(join(result.outDir, runtimeFile), JSON.stringify(runtime));
311
+ }
312
+ catch {
313
+ // A worker then loads the output without the aliases; the error it reports names the import.
314
+ }
315
+ return result;
316
+ }
317
+ function compile(compiler, files, cwd, resolution) {
167
318
  const outDir = join(cwd, '.tslaws', 'out');
319
+ const builtin = usesBuiltin(compiler, files, cwd);
320
+ // The compiler wants every source file under one root, and `paths` can lead out of the project (a sibling package),
321
+ // so the root is the common ancestor and the output mirrors the tree from there. The built-in path writes only what
322
+ // is inside the project, so it keeps the project as the root.
323
+ const root = builtin ? cwd : commonRoot(cwd, resolution?.options);
168
324
  const extra = compilerFlags(readConfig(cwd).compilerOptions);
169
- const args = [
170
- '--ignoreConfig',
325
+ const flags = [
171
326
  '--target',
172
327
  'es2022',
173
328
  '--module',
@@ -179,14 +334,15 @@ export function build(compiler, files, cwd) {
179
334
  '--esModuleInterop',
180
335
  '--declaration',
181
336
  '--rootDir',
182
- cwd,
337
+ root,
183
338
  '--outDir',
184
339
  outDir,
185
340
  ...extra,
186
- ...files,
187
341
  ];
188
- const builtin = usesBuiltin(compiler, files, cwd);
189
- const reused = builtin ? cachedBuild(args, files, cwd, outDir) : undefined;
342
+ const args = ['--ignoreConfig', ...flags, ...files];
343
+ // What the options say is part of what was built.
344
+ const keyArgs = [...args, JSON.stringify(resolution?.options ?? null)];
345
+ const reused = builtin ? cachedBuild(keyArgs, files, cwd, outDir) : undefined;
190
346
  if (reused !== undefined)
191
347
  return reused;
192
348
  rmSync(outDir, { recursive: true, force: true });
@@ -194,17 +350,59 @@ export function build(compiler, files, cwd) {
194
350
  // The output is CommonJS whatever the project's own package.json says.
195
351
  writeFileSync(join(outDir, 'package.json'), JSON.stringify({ type: 'commonjs' }));
196
352
  if (builtin)
197
- return buildBuiltin(args, files, cwd, outDir);
198
- let run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
353
+ return buildBuiltin(args, keyArgs, files, cwd, outDir, resolution);
354
+ // `paths` is not a command line option, so the compiler gets the resolution options in a generated tsconfig that names
355
+ // the files; everything else stays a flag, and flags win over the file. Without any, the flags alone do as before.
356
+ const project = join(cwd, '.tslaws', 'resolution.tsconfig.json');
357
+ const argsFor = (flagList, more = []) => {
358
+ if (resolution === undefined)
359
+ return ['--ignoreConfig', ...flagList, ...files, ...more];
360
+ writeFileSync(project, JSON.stringify({
361
+ compilerOptions: { ...resolution.options, rootDir: root },
362
+ files: [...files, ...more].map((f) => resolve(cwd, f)),
363
+ }));
364
+ return ['-p', project, ...flagList];
365
+ };
366
+ const given = argsFor(flags);
367
+ let run = launch(compiler, given, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
199
368
  // A compiler that dies without a word (out of memory on a busy machine) is run again; a type error always says so.
200
369
  for (let attempt = 0; attempt < 2 &&
201
370
  run.error === undefined &&
202
371
  run.status !== 0 &&
203
372
  `${run.stdout ?? ''}${run.stderr ?? ''}`.trim() === ''; attempt += 1)
204
- run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
373
+ run = launch(compiler, given, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
205
374
  if (run.error !== undefined)
206
375
  throw new Error(cannotRun(compiler, run.error));
207
- return { outDir, diagnostics: `${run.stdout ?? ''}${run.stderr ?? ''}`.trim(), ok: run.status === 0 };
376
+ const output = () => `${run.stdout ?? ''}${run.stderr ?? ''}`;
377
+ const again = (next) => {
378
+ const rerun = launch(compiler, next, {
379
+ cwd,
380
+ encoding: 'utf8',
381
+ maxBuffer: 64 << 20,
382
+ env: compilerEnv(cwd, compiler),
383
+ });
384
+ if (rerun.error === undefined)
385
+ run = rerun;
386
+ };
387
+ // CommonJS output does not allow `import.meta` or a top-level await: read the project as ES modules instead, and lower
388
+ // the output below, where a module that waits at its top level is replaced by a stub that says so.
389
+ let lowering = false;
390
+ let used = flags;
391
+ if (usesImportMeta(output()) || hasTopLevelAwaitError(output())) {
392
+ used = flags.map((flag, i) => (flags[i - 1] === '--module' ? 'preserve' : flag));
393
+ lowering = true;
394
+ again(argsFor(used));
395
+ }
396
+ // A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, and the build runs again.
397
+ if (lacksEnvTypes(output()))
398
+ again(argsFor(used, [envTypes]));
399
+ const problems = lowering ? lowerEmittedModules(outDir, { outDir, root }) : [];
400
+ // The project's own files sit where they do under the root, so its output is that deep in `outDir`.
401
+ return {
402
+ outDir: join(outDir, relative(root, cwd)),
403
+ diagnostics: [output().trim(), ...problems].filter((part) => part !== '').join('\n'),
404
+ ok: run.status === 0 && problems.length === 0,
405
+ };
208
406
  }
209
407
  /** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
210
408
  function typeRootsOf(cwd) {
@@ -218,11 +416,13 @@ function typeRootsOf(cwd) {
218
416
  }
219
417
  }
220
418
  /** Compiles in-process with stock TypeScript: law files are lowered in memory, nothing is written next to them. */
221
- function buildBuiltin(args, files, cwd, outDir) {
419
+ function buildBuiltin(args, keyArgs, files, cwd, outDir, resolution) {
222
420
  const at = args.indexOf('--moduleResolution');
223
421
  const parsed = ts.parseCommandLine(at < 0 ? args : [...args.slice(0, at), ...args.slice(at + 2)]);
224
422
  // Types resolve the bundler way, so package `exports` (tslaws/browser) work; the ES output is made CommonJS below.
225
423
  const options = {
424
+ // The tsconfig's resolution first, so the project's own compilerOptions win over it.
425
+ ...resolutionCompilerOptions(resolution?.options),
226
426
  ...parsed.options,
227
427
  module: ts.ModuleKind.ESNext,
228
428
  moduleResolution: ts.ModuleResolutionKind.Bundler,
@@ -248,6 +448,7 @@ function buildBuiltin(args, files, cwd, outDir) {
248
448
  : ts.createSourceFile(name, text, languageVersion, true);
249
449
  };
250
450
  const roots = parsed.fileNames.map((f) => resolve(cwd, f));
451
+ let used = options;
251
452
  let program = ts.createProgram(roots, options, host);
252
453
  let diagnostics = ts.getPreEmitDiagnostics(program);
253
454
  // An error may only be a global the narrow setup left out (`process`, `document`, a test runner's types): check again
@@ -257,16 +458,34 @@ function buildBuiltin(args, files, cwd, outDir) {
257
458
  // `@types` is looked up from the project, not from wherever the process happens to be (the compiler remembers the first directory it saw).
258
459
  const typeRoots = parsed.options.typeRoots ?? typeRootsOf(cwd);
259
460
  const full = { ...options, types: parsed.options.types, lib: parsed.options.lib, typeRoots };
461
+ used = full;
260
462
  program = ts.createProgram(roots, full, host);
261
463
  diagnostics = ts.getPreEmitDiagnostics(program);
262
464
  }
465
+ // A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, checked the same way.
466
+ if (diagnostics.some((d) => d.code === 2339 && ts.flattenDiagnosticMessageText(d.messageText, ' ').includes("'ImportMeta'"))) {
467
+ program = ts.createProgram([...roots, envTypes], used, host);
468
+ diagnostics = ts.getPreEmitDiagnostics(program);
469
+ }
470
+ const problems = [];
263
471
  program.emit(undefined, (name, text) => {
472
+ // A source file outside the project (reached through `paths`) is checked and loaded in place, never written here.
473
+ const under = relative(outDir, name);
474
+ if (under.startsWith('..') || isAbsolute(under))
475
+ return;
264
476
  mkdirSync(dirname(name), { recursive: true });
265
- const code = name.endsWith('.js')
266
- ? transformSync(text, { format: 'cjs', target: 'es2022', sourcefile: name }).code
267
- : text;
268
- writeFileSync(name, code);
477
+ if (!/\.m?js$/.test(name))
478
+ return void writeFileSync(name, text);
479
+ const rewritten = rewriteImportMeta(text, name, sourceOfOutput(name, outDir, cwd));
480
+ if (rewritten.awaits) {
481
+ problems.push(awaitProblem(slash(under)));
482
+ writeFileSync(name, awaitStub(slash(under)));
483
+ }
484
+ else
485
+ writeFileSync(name, name.endsWith('.mjs') ? rewritten.text : lowerModule(rewritten.text, name));
269
486
  });
487
+ // Such a file is outside the root directory by design (TS6059).
488
+ diagnostics = diagnostics.filter((d) => d.code !== 6059);
270
489
  const text = ts.formatDiagnostics(diagnostics, {
271
490
  getCanonicalFileName: (f) => f,
272
491
  getCurrentDirectory: () => cwd,
@@ -274,11 +493,11 @@ function buildBuiltin(args, files, cwd, outDir) {
274
493
  });
275
494
  const result = {
276
495
  outDir,
277
- diagnostics: text.trim(),
278
- ok: diagnostics.every((d) => d.category !== ts.DiagnosticCategory.Error),
496
+ diagnostics: [text.trim(), ...problems].filter((part) => part !== '').join('\n'),
497
+ ok: problems.length === 0 && diagnostics.every((d) => d.category !== ts.DiagnosticCategory.Error),
279
498
  };
280
499
  Object.defineProperty(result, 'program', { value: program, enumerable: false });
281
- saveBuildCache(args, files, cwd, result, program
500
+ saveBuildCache(keyArgs, files, cwd, result, program
282
501
  .getSourceFiles()
283
502
  .map((f) => f.fileName)
284
503
  .filter((f) => !overrides.has(slash(resolve(f)))));
@@ -287,7 +506,7 @@ function buildBuiltin(args, files, cwd, outDir) {
287
506
  const buildCachePath = (cwd) => join(cwd, '.tslaws', 'build-cache.json');
288
507
  function buildKey(args, files, cwd) {
289
508
  const hash = createHash('sha256');
290
- hash.update(JSON.stringify([args, ts.version, toolStamp]));
509
+ hash.update(JSON.stringify([args, ts.version, toolStamp, importMetaEnvGlobal, envTypes]));
291
510
  for (const file of files)
292
511
  if (isLawFile(file, cwd) && existsSync(join(cwd, file)))
293
512
  hash.update(`
@@ -1,10 +1,17 @@
1
1
  import ts from 'typescript';
2
2
  import { type E2eConfig } from './e2e.ts';
3
+ import { type CertifyMode } from './certificates.ts';
4
+ import { type ImportMetaEnv } from './runtimeEnv.ts';
3
5
  import { type SolverName } from './solvers.ts';
4
6
  export interface CoverageConfig {
5
7
  cover?: string[];
6
8
  /** Compiler options the runner passes to tsc; see `compilerFlags` in compile.ts for the supported keys. */
7
9
  compilerOptions?: Record<string, unknown>;
10
+ /**
11
+ * Where laws take their module resolution (`paths`, `baseUrl`, project references) from: a tsconfig path relative to
12
+ * tslaws.json, or `false` for none. Default: the nearest tsconfig.json above the project. See tsconfigResolve.ts.
13
+ */
14
+ tsconfig?: string | false;
8
15
  /** End-to-end laws: the app to drive; see `parseE2eConfig`. */
9
16
  e2e?: E2eConfig;
10
17
  /**
@@ -22,15 +29,35 @@ export interface CoverageConfig {
22
29
  * must also answer `unsat` or the law is `bounded`. Z3 is required. See solvers.ts.
23
30
  */
24
31
  solvers?: SolverName[];
32
+ /**
33
+ * Check every proof Z3 finds with cvc5 (an Alethe proof) and Carcara, and record the law as `certified` or
34
+ * `uncertified`. `"require"` makes anything short of `certified` an error. Default off. See certificates.ts.
35
+ */
36
+ certify?: CertifyMode;
25
37
  /** esbuild plugin modules (paths relative to tslaws.json) that teach the browser bundler new source formats. */
26
38
  bundlerPlugins?: string[];
39
+ /**
40
+ * Directories outside the project (paths relative to tslaws.json) whose reviewed files the law sandbox may read, besides
41
+ * the workspace packages and the `paths` and `references` targets of the tsconfig. Dotfiles and the home directory are
42
+ * refused whatever is named. See sandbox.ts.
43
+ */
44
+ sandboxReads?: string[];
45
+ /**
46
+ * `import.meta.env` for code laws reach, on top of `process.env` and the defaults (`MODE` `test`, `DEV`, `PROD`, `SSR`,
47
+ * `BASE_URL`); its entries override both. See runtimeEnv.ts.
48
+ */
49
+ env?: Record<string, string | boolean>;
27
50
  /** Run settings; a command line flag beats them and they beat the built-in default. */
28
51
  runs?: number;
29
52
  propertyTimeoutMs?: number;
30
53
  proofTimeoutMs?: number;
31
54
  bound?: number;
32
- /** Accepting laws on GitHub: see github.ts. When present, `tslaws accept` refuses to run outside that workflow. */
55
+ /** The most laws, proofs and solvers that run at once (the CPU budget); `--jobs` and `TSLAWS_JOBS` beat it. Not sealed: it is the machine's, not the project's. */
56
+ jobs?: number;
57
+ /** Accepting laws on GitHub: see github.ts. When present, `tslaws accept` refuses to run unless `github.local` is true (the default). */
33
58
  github?: unknown;
59
+ /** `tslaws security deps`: the severity that fails the check, offline mode, the cache; see security/deps/config.ts. */
60
+ security?: unknown;
34
61
  }
35
62
  export interface Uncovered {
36
63
  file: string;
@@ -43,9 +70,34 @@ export interface CoverageReport {
43
70
  /** The source files the check covers, for the compiler to emit. */
44
71
  files: string[];
45
72
  }
46
- /** Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. */
47
- export declare function parseConfig(raw: unknown): CoverageConfig;
73
+ /** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
74
+ export declare function projectsProblem(value: unknown): string | undefined;
75
+ /**
76
+ * Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. `extends`
77
+ * and `projects` are accepted (a string, and a list of globs) but are not part of the result: `readConfig` has
78
+ * already acted on `extends`, and discovery reads `projects` from the file itself.
79
+ */
80
+ export declare function parseConfig(raw: unknown, source?: string): CoverageConfig;
81
+ /**
82
+ * The text of an `extends` value if it is one this tool will follow: a non-empty relative path with forward slashes only.
83
+ * An absolute path, a drive or UNC path, a backslash, or a NUL is refused, so the on-disk loader and the GitHub checks
84
+ * that read the same files through the API resolve one target and never two.
85
+ */
86
+ export declare function checkExtendsValue(value: unknown): string;
87
+ /**
88
+ * Where `extends` points, as a repository path: `fromFile` is the repository path of the file that names it. Refuses
89
+ * what `checkExtendsValue` does, and a target that leaves the repository.
90
+ */
91
+ export declare function extendsTarget(fromFile: string, value: unknown): string;
92
+ /**
93
+ * The directory no `extends` may leave: the nearest enclosing directory with a `.git`, else the highest enclosing one
94
+ * that carries a workspace file (`tslaws.json`, `package.json` or `pnpm-workspace.yaml`), else `cwd` itself.
95
+ */
96
+ export declare function extendsRoot(cwd: string): string;
97
+ /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
48
98
  export declare function readConfig(cwd: string): CoverageConfig;
99
+ /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
100
+ export declare function lawEnv(cwd: string, surface: 'node' | 'browser'): ImportMetaEnv;
49
101
  /** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
50
102
  export declare function coverFiles(cwd: string, globs: string[]): string[];
51
103
  export interface CoverageInput {