tslaws 0.6.4 → 0.8.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 (78) hide show
  1. package/README.md +16 -9
  2. package/dist/api.d.ts +10 -0
  3. package/dist/api.js +7 -0
  4. package/dist/browser.d.ts +2 -2
  5. package/dist/browser.js +2 -6
  6. package/dist/check.d.ts +2 -0
  7. package/dist/check.js +218 -56
  8. package/dist/cli.d.ts +18 -0
  9. package/dist/cli.js +189 -56
  10. package/dist/compile.d.ts +12 -0
  11. package/dist/compile.js +207 -6
  12. package/dist/coverage.d.ts +21 -1
  13. package/dist/coverage.js +33 -23
  14. package/dist/derived.d.ts +8 -0
  15. package/dist/derived.js +52 -0
  16. package/dist/e2e.d.ts +0 -9
  17. package/dist/e2e.js +0 -20
  18. package/dist/generators.d.ts +8 -8
  19. package/dist/generators.js +59 -99
  20. package/dist/github.d.ts +121 -0
  21. package/dist/github.js +266 -0
  22. package/dist/githubCli.d.ts +46 -0
  23. package/dist/githubCli.js +502 -0
  24. package/dist/globs.d.ts +3 -0
  25. package/dist/globs.js +24 -0
  26. package/dist/init.js +5 -5
  27. package/dist/lawFiles.d.ts +21 -0
  28. package/dist/lawFiles.js +95 -0
  29. package/dist/lawKinds.d.ts +38 -0
  30. package/dist/lawKinds.js +210 -0
  31. package/dist/lawNames.d.ts +6 -0
  32. package/dist/lawNames.js +22 -0
  33. package/dist/list.d.ts +22 -0
  34. package/dist/list.js +36 -0
  35. package/dist/lock.d.ts +39 -3
  36. package/dist/lock.js +107 -4
  37. package/dist/lower.d.ts +10 -0
  38. package/dist/lower.js +178 -0
  39. package/dist/mcp.d.ts +2 -8
  40. package/dist/mcp.js +40 -61
  41. package/dist/migrate/arbitraries.d.ts +23 -0
  42. package/dist/migrate/arbitraries.js +202 -0
  43. package/dist/migrate/convert.d.ts +20 -0
  44. package/dist/migrate/convert.js +915 -0
  45. package/dist/migrate/framework.d.ts +48 -0
  46. package/dist/migrate/framework.js +249 -0
  47. package/dist/migrate/index.d.ts +16 -0
  48. package/dist/migrate/index.js +155 -0
  49. package/dist/migrate/report.d.ts +35 -0
  50. package/dist/migrate/report.js +40 -0
  51. package/dist/migrate/source.d.ts +42 -0
  52. package/dist/migrate/source.js +163 -0
  53. package/dist/migrate/tests.d.ts +44 -0
  54. package/dist/migrate/tests.js +184 -0
  55. package/dist/plan.d.ts +50 -0
  56. package/dist/plan.js +118 -0
  57. package/dist/pool.d.ts +21 -0
  58. package/dist/pool.js +54 -0
  59. package/dist/promote.d.ts +30 -2
  60. package/dist/promote.js +133 -7
  61. package/dist/property.d.ts +12 -26
  62. package/dist/property.js +33 -74
  63. package/dist/propertyRun.d.ts +35 -0
  64. package/dist/propertyRun.js +79 -0
  65. package/dist/propertyWorker.js +7 -9
  66. package/dist/proposals.d.ts +43 -0
  67. package/dist/proposals.js +192 -0
  68. package/dist/regressions.js +23 -2
  69. package/dist/reporters.d.ts +3 -0
  70. package/dist/reporters.js +17 -0
  71. package/dist/smt.d.ts +16 -0
  72. package/dist/smt.js +52 -9
  73. package/dist/solvers.d.ts +31 -0
  74. package/dist/solvers.js +121 -0
  75. package/dist/symbolic.js +2 -2
  76. package/dist/types.d.ts +19 -0
  77. package/hooks/AGENTS.snippet.md +2 -2
  78. package/package.json +9 -7
@@ -1,11 +1,27 @@
1
1
  import ts from 'typescript';
2
2
  import { type E2eConfig } from './e2e.ts';
3
+ import { type SolverName } from './solvers.ts';
3
4
  export interface CoverageConfig {
4
5
  cover?: string[];
5
6
  /** Compiler options the runner passes to tsc; see `compilerFlags` in compile.ts for the supported keys. */
6
7
  compilerOptions?: Record<string, unknown>;
7
8
  /** End-to-end laws: the app to drive; see `parseE2eConfig`. */
8
9
  e2e?: E2eConfig;
10
+ /**
11
+ * Extra globs for laws files with other names: any file they match that declares a top-level `export law` is a laws
12
+ * file, besides every file named `*.laws.ts`. A leading `!` excludes. Default: none.
13
+ */
14
+ laws?: string[];
15
+ /**
16
+ * Where a laws file's level (Node, browser, end to end) comes from. `names` (the default): the file name
17
+ * (`*.browser.laws.ts`, `*.e2e.laws.ts`). `imports`: the file's import graph; names are still recognised as hints.
18
+ */
19
+ levels?: 'names' | 'imports';
20
+ /**
21
+ * The SMT solvers that must agree before a law is `proved`: `["z3"]` (the default) or `["z3", "cvc5"]`, where cvc5
22
+ * must also answer `unsat` or the law is `bounded`. Z3 is required. See solvers.ts.
23
+ */
24
+ solvers?: SolverName[];
9
25
  /** esbuild plugin modules (paths relative to tslaws.json) that teach the browser bundler new source formats. */
10
26
  bundlerPlugins?: string[];
11
27
  /** Run settings; a command line flag beats them and they beat the built-in default. */
@@ -13,6 +29,8 @@ export interface CoverageConfig {
13
29
  propertyTimeoutMs?: number;
14
30
  proofTimeoutMs?: number;
15
31
  bound?: number;
32
+ /** Accepting laws on GitHub: see github.ts. When present, `tslaws accept` refuses to run outside that workflow. */
33
+ github?: unknown;
16
34
  }
17
35
  export interface Uncovered {
18
36
  file: string;
@@ -36,7 +54,9 @@ export interface CoverageInput {
36
54
  lawFiles: string[];
37
55
  /** Files named by the `cover` globs; empty means every module the laws reach. */
38
56
  coverFiles: string[];
39
- /** Declarations the compiler emitted for the program. */
57
+ /** Declarations the compiler emitted for the program, or the program that compiled the code (then `moduleOf` is given). */
40
58
  program: ts.Program;
59
+ /** Where a module's exports are read from, by its path relative to `cwd`; the emitted declaration when absent. */
60
+ moduleOf?: (file: string) => string;
41
61
  }
42
62
  export declare function analyzeCoverage(input: CoverageInput): CoverageReport;
package/dist/coverage.js CHANGED
@@ -4,12 +4,26 @@
4
4
  // Covered modules are the `cover` globs of tslaws.json, or, without that file, every module the laws import
5
5
  // (directly or through other project modules). A function carrying `@tslaws-exempt` in its doc comment is exempt,
6
6
  // but only once the exemption is in tsc-laws.lock, so an agent cannot exempt its own code.
7
+ import { parseGithubConfig } from "./github.js";
7
8
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
9
  import { dirname, join, relative, resolve } from 'node:path';
9
10
  import ts from 'typescript';
10
11
  import { parseE2eConfig } from "./e2e.js";
12
+ import { globMatcher } from "./globs.js";
13
+ import { customLawFile } from "./lawFiles.js";
14
+ import { solversProblem } from "./solvers.js";
11
15
  const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
12
- const configKeys = ['cover', 'compilerOptions', 'e2e', 'bundlerPlugins', ...settingKeys];
16
+ const configKeys = [
17
+ 'cover',
18
+ 'laws',
19
+ 'levels',
20
+ 'solvers',
21
+ 'compilerOptions',
22
+ 'e2e',
23
+ 'bundlerPlugins',
24
+ 'github',
25
+ ...settingKeys,
26
+ ];
13
27
  /** Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. */
14
28
  export function parseConfig(raw) {
15
29
  const fail = (message) => {
@@ -31,6 +45,19 @@ export function parseConfig(raw) {
31
45
  if (plugins !== undefined &&
32
46
  (!Array.isArray(plugins) || plugins.some((entry) => typeof entry !== 'string' || entry === '')))
33
47
  fail(`"bundlerPlugins" must be an array of module paths, got ${JSON.stringify(plugins)}`);
48
+ const levels = object.levels;
49
+ if (levels !== undefined && levels !== 'names' && levels !== 'imports')
50
+ fail(`"levels" must be "names" or "imports", got ${JSON.stringify(levels)}`);
51
+ const problem = object.solvers === undefined ? undefined : solversProblem(object.solvers);
52
+ if (problem !== undefined)
53
+ fail(problem);
54
+ const laws = object.laws;
55
+ if (laws !== undefined &&
56
+ (!Array.isArray(laws) ||
57
+ laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
58
+ fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
59
+ if (object.github !== undefined)
60
+ parseGithubConfig(object.github);
34
61
  return object;
35
62
  }
36
63
  export function readConfig(cwd) {
@@ -42,29 +69,12 @@ export function readConfig(cwd) {
42
69
  config.e2e = parseE2eConfig(config.e2e);
43
70
  return config;
44
71
  }
45
- function globToRegExp(glob) {
46
- let out = '';
47
- for (let i = 0; i < glob.length; i += 1) {
48
- const ch = glob[i];
49
- if (ch === '*' && glob[i + 1] === '*') {
50
- out += '.*';
51
- i += glob[i + 2] === '/' ? 2 : 1;
52
- }
53
- else if (ch === '*')
54
- out += '[^/]*';
55
- else if (ch === '?')
56
- out += '[^/]';
57
- else
58
- out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
59
- }
60
- return new RegExp(`^${out}$`);
61
- }
62
72
  /** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
63
73
  export function coverFiles(cwd, globs) {
64
74
  // Plain JavaScript sources are covered only when the project compiles them (`allowJs`).
65
75
  const js = readConfig(cwd).compilerOptions?.allowJs === true;
66
- const include = globs.filter((g) => !g.startsWith('!')).map(globToRegExp);
67
- const exclude = globs.filter((g) => g.startsWith('!')).map((g) => globToRegExp(g.slice(1)));
76
+ const covered = globMatcher(globs);
77
+ const isLaws = customLawFile(cwd);
68
78
  const found = [];
69
79
  const walk = (dir) => {
70
80
  for (const entry of readdirSync(dir)) {
@@ -77,9 +87,9 @@ export function coverFiles(cwd, globs) {
77
87
  const file = relative(cwd, full).replaceAll('\\', '/');
78
88
  if (!(js ? /\.(ts|tsx|mts|cts|js)$/ : /\.(ts|tsx|mts|cts)$/).test(file))
79
89
  continue;
80
- if (/\.d\.(ts|mts|cts)$/.test(file) || /\.laws\.ts$/.test(file))
90
+ if (/\.d\.(ts|mts|cts)$/.test(file) || file.endsWith('.laws.ts'))
81
91
  continue;
82
- if (include.some((r) => r.test(file)) && !exclude.some((r) => r.test(file)))
92
+ if (covered(file) && !isLaws(file))
83
93
  found.push(file);
84
94
  }
85
95
  }
@@ -225,7 +235,7 @@ export function analyzeCoverage(input) {
225
235
  if (module === undefined)
226
236
  continue;
227
237
  const file = sourceOf(input.outDir, input.cwd, js);
228
- for (const name of exportedFunctions(input.program, dtsOf(input.outDir, file))) {
238
+ for (const name of exportedFunctions(input.program, input.moduleOf?.(file) ?? dtsOf(input.outDir, file))) {
229
239
  const node = module.nodes.get(name);
230
240
  if (node?.exempt === true)
231
241
  exempt.push(`${file}::${name}`);
@@ -0,0 +1,8 @@
1
+ import type { CoverageReport } from './coverage.ts';
2
+ import type { LawTypes } from './property.ts';
3
+ import type { ManifestLaw } from './types.ts';
4
+ export interface DerivedStore {
5
+ law(law: ManifestLaw, compute: () => LawTypes): LawTypes;
6
+ coverage(compute: () => CoverageReport): CoverageReport;
7
+ }
8
+ export declare function derivedStore(cwd: string, key: string | undefined): DerivedStore;
@@ -0,0 +1,52 @@
1
+ // What the type checker works out from a build (each law's generator plans and shapes, the coverage report) depends
2
+ // on nothing but that build, so it is kept next to it: an unchanged project never starts the checker.
3
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { arbitraryOf } from "./plan.js";
6
+ export function derivedStore(cwd, key) {
7
+ if (key === undefined)
8
+ return { law: (_law, compute) => compute(), coverage: (compute) => compute() };
9
+ const path = join(cwd, '.tslaws', 'derived.json');
10
+ let stored = { key, laws: {} };
11
+ try {
12
+ const read = JSON.parse(readFileSync(path, 'utf8'));
13
+ if (read.key === key)
14
+ stored = read;
15
+ }
16
+ catch {
17
+ // Nothing kept yet.
18
+ }
19
+ const save = () => {
20
+ try {
21
+ mkdirSync(join(cwd, '.tslaws'), { recursive: true });
22
+ writeFileSync(path, JSON.stringify(stored));
23
+ }
24
+ catch {
25
+ // Not keeping it is only slower.
26
+ }
27
+ };
28
+ return {
29
+ law(law, compute) {
30
+ const id = `${law.file}::${law.symbol ?? law.name}`;
31
+ const kept = stored.laws[id];
32
+ if (kept !== undefined)
33
+ return {
34
+ generators: kept.plans.map(arbitraryOf),
35
+ plans: kept.plans,
36
+ shapes: kept.shapes.map((shape) => shape ?? undefined),
37
+ };
38
+ const types = compute();
39
+ stored.laws[id] = { plans: types.plans, shapes: types.shapes.map((shape) => shape ?? null) };
40
+ save();
41
+ return types;
42
+ },
43
+ coverage(compute) {
44
+ if (stored.coverage !== undefined)
45
+ return stored.coverage;
46
+ const report = compute();
47
+ stored.coverage = report;
48
+ save();
49
+ return report;
50
+ },
51
+ };
52
+ }
package/dist/e2e.d.ts CHANGED
@@ -1,15 +1,6 @@
1
1
  import type * as fc from 'fast-check';
2
2
  import { type PropertyOutcome } from './property.ts';
3
3
  import type { CheckOptions } from './types.ts';
4
- /** `a.e2e.laws.ts` is an accepted alias: it always drives a running app. */
5
- export declare function isE2eLawFile(file: string): boolean;
6
- /** Whether a law file imports both helper sets, which would put one file at two levels. */
7
- export declare function importsBoth(text: string): boolean;
8
- /**
9
- * The level a law file runs at. `*.browser.laws.ts` is a component law (in a page) unless it imports from
10
- * `tslaws/e2e`, which makes it an end-to-end law (in Node, driving a running app); `*.e2e.laws.ts` is always e2e.
11
- */
12
- export declare function lawMode(file: string, text: string): 'node' | 'component' | 'e2e';
13
4
  export interface E2eServerConfig {
14
5
  /** Shell command that starts the app. It runs from your project, like a package script. */
15
6
  command: string;
package/dist/e2e.js CHANGED
@@ -7,26 +7,6 @@ import { join, resolve } from 'node:path';
7
7
  import { launch, resolveEngine } from "./browser.js";
8
8
  import { withE2e } from "./e2eApi.js";
9
9
  import { runProperty, summarise } from "./property.js";
10
- /** `a.e2e.laws.ts` is an accepted alias: it always drives a running app. */
11
- export function isE2eLawFile(file) {
12
- return /\.e2e\.laws\.[cm]?ts$/.test(file);
13
- }
14
- const importsOf = (module) => new RegExp(`(?:from|import)\\s*['"]${module}['"]`);
15
- /** Whether a law file imports both helper sets, which would put one file at two levels. */
16
- export function importsBoth(text) {
17
- return importsOf('tslaws/e2e').test(text) && importsOf('tslaws/browser').test(text);
18
- }
19
- /**
20
- * The level a law file runs at. `*.browser.laws.ts` is a component law (in a page) unless it imports from
21
- * `tslaws/e2e`, which makes it an end-to-end law (in Node, driving a running app); `*.e2e.laws.ts` is always e2e.
22
- */
23
- export function lawMode(file, text) {
24
- if (isE2eLawFile(file))
25
- return 'e2e';
26
- if (!/\.browser\.laws\.[cm]?ts$/.test(file))
27
- return 'node';
28
- return importsOf('tslaws/e2e').test(text) ? 'e2e' : 'component';
29
- }
30
10
  const topKeys = ['baseURL', 'server', 'runs', 'timeoutMs'];
31
11
  const serverKeys = ['command', 'url', 'timeoutMs', 'reuseExisting', 'cwd'];
32
12
  /** Checks the `e2e` section of tslaws.json; unknown keys and wrong types are errors that say where. */
@@ -1,16 +1,16 @@
1
- import * as fc from 'fast-check';
1
+ import type * as fc from 'fast-check';
2
2
  import ts from 'typescript';
3
- export declare class UnsupportedType extends Error {
4
- }
5
- /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
6
- export declare const wireKey = "$tslawsFn";
7
- /** Replaces generated functions inside arguments with a structured-clone-safe marker `{ $tslawsFn: samples }`. */
8
- export declare function toWire(value: unknown): unknown;
3
+ import { type Plan } from './plan.ts';
4
+ export { toWire, UnsupportedType, wireKey } from './plan.ts';
9
5
  export declare class GeneratorFactory {
10
6
  private readonly checker;
11
7
  private readonly active;
12
8
  constructor(checker: ts.TypeChecker);
13
- of(type: ts.Type, depth?: number): fc.Arbitrary<unknown>;
9
+ /** The arbitrary for `type`, built in this process. */
10
+ of(type: ts.Type): fc.Arbitrary<unknown>;
11
+ plan(type: ts.Type, depth?: number): Plan;
12
+ private structural;
13
+ /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
14
14
  private registered;
15
15
  private union;
16
16
  private template;
@@ -1,104 +1,59 @@
1
- // Derives fast-check generators from the declared parameter types of laws, read from the declaration
2
- // files the compiler emitted. Full TypeScript types map: primitives, literals, unions, enums, arrays,
3
- // tuples, object types, index signatures, type parameters (via their constraint) and registered names.
4
- import * as fc from 'fast-check';
5
1
  import ts from 'typescript';
6
2
  import { arbitraryRegistry } from "./api.js";
7
- import { sequence } from "./sequence.js";
8
- export class UnsupportedType extends Error {
9
- }
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
- // `int` from 'tslaws': whole numbers, biased to small ones.
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
- /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
14
- export const wireKey = '$tslawsFn';
15
- function pick(samples, args) {
16
- let key = '';
17
- try {
18
- key = JSON.stringify(args) ?? '';
19
- }
20
- catch {
21
- // Arguments that are not JSON (a node, a cycle) all share the first sample.
22
- }
23
- let h = 5381;
24
- for (let i = 0; i < key.length; i++)
25
- h = (Math.imul(h, 33) + key.charCodeAt(i)) | 0;
26
- return samples[(h >>> 0) % samples.length];
27
- }
28
- /**
29
- * A function of a type with one call signature: it returns one of a few values generated from the return type,
30
- * chosen by its arguments (like `fc.func`: the same arguments give the same result, `void` gives `undefined`).
31
- * `samples` rides along so a browser law can rebuild the function in the page.
32
- */
33
- function generatedFunction(samples) {
34
- const fn = (...args) => pick(samples, args);
35
- Object.defineProperty(fn, wireKey, { value: samples, enumerable: false });
36
- Object.defineProperty(fn, 'toString', { value: () => `[generated function]`, enumerable: false });
37
- return fn;
38
- }
39
- /** Replaces generated functions inside arguments with a structured-clone-safe marker `{ $tslawsFn: samples }`. */
40
- export function toWire(value) {
41
- if (typeof value === 'function') {
42
- const samples = value[wireKey];
43
- return { [wireKey]: Array.isArray(samples) ? samples : [undefined] };
44
- }
45
- if (Array.isArray(value))
46
- return value.map(toWire);
47
- if (value !== null && typeof value === 'object') {
48
- const proto = Object.getPrototypeOf(value);
49
- if (proto === Object.prototype || proto === null)
50
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toWire(v)]));
51
- }
52
- return value;
53
- }
3
+ import { arbitraryOf, UnsupportedType } from "./plan.js";
4
+ export { toWire, UnsupportedType, wireKey } from "./plan.js";
54
5
  export class GeneratorFactory {
55
6
  checker;
56
7
  active = new Set();
57
8
  constructor(checker) {
58
9
  this.checker = checker;
59
10
  }
60
- of(type, depth = 0) {
61
- const named = this.registered(type);
62
- if (named !== undefined)
63
- return named;
11
+ /** The arbitrary for `type`, built in this process. */
12
+ of(type) {
13
+ return arbitraryOf(this.plan(type));
14
+ }
15
+ plan(type, depth = 0) {
16
+ return this.registered(type, depth) ?? this.structural(type, depth);
17
+ }
18
+ structural(type, depth) {
64
19
  const f = type.flags;
65
20
  if (f & ts.TypeFlags.Any || f & ts.TypeFlags.Unknown)
66
- return fc.anything();
21
+ return { k: 'anything' };
67
22
  if (f & ts.TypeFlags.Never)
68
23
  throw new UnsupportedType('type never has no values');
69
24
  if (f & ts.TypeFlags.Void || f & ts.TypeFlags.Undefined)
70
- return fc.constant(undefined);
25
+ return { k: 'const', v: undefined };
71
26
  if (f & ts.TypeFlags.Null)
72
- return fc.constant(null);
27
+ return { k: 'const', v: null };
73
28
  if (f & ts.TypeFlags.BooleanLiteral)
74
- return fc.constant(this.checker.typeToString(type) === 'true');
29
+ return { k: 'const', v: this.checker.typeToString(type) === 'true' };
75
30
  if (f & ts.TypeFlags.Boolean)
76
- return fc.boolean();
31
+ return { k: 'boolean' };
77
32
  if (f & ts.TypeFlags.NumberLiteral)
78
- return fc.constant(type.value);
33
+ return { k: 'const', v: type.value };
79
34
  if (f & ts.TypeFlags.StringLiteral)
80
- return fc.constant(type.value);
35
+ return { k: 'const', v: type.value };
81
36
  if (f & ts.TypeFlags.BigIntLiteral) {
82
37
  const v = type.value;
83
- return fc.constant(BigInt(`${v.negative ? '-' : ''}${v.base10Value}`));
38
+ return { k: 'bigconst', v: `${v.negative ? '-' : ''}${v.base10Value}` };
84
39
  }
85
40
  if (f & ts.TypeFlags.EnumLiteral && f & ts.TypeFlags.Union)
86
41
  return this.union(type, depth);
87
42
  if (f & ts.TypeFlags.Number)
88
- return numbers;
43
+ return { k: 'number' };
89
44
  if (f & ts.TypeFlags.String)
90
- return fc.string({ maxLength: 24 });
45
+ return { k: 'string' };
91
46
  if (f & ts.TypeFlags.BigInt)
92
- return fc.bigInt();
47
+ return { k: 'bigint' };
93
48
  if (f & ts.TypeFlags.ESSymbol)
94
- return fc.string().map((s) => Symbol(s));
49
+ return { k: 'symbol' };
95
50
  if (f & ts.TypeFlags.TemplateLiteral)
96
51
  return this.template(type, depth);
97
52
  if (f & ts.TypeFlags.TypeParameter) {
98
53
  const constraint = this.checker.getBaseConstraintOfType(type);
99
54
  if (constraint === undefined || constraint === type)
100
- return fc.anything();
101
- return this.of(constraint, depth);
55
+ return { k: 'anything' };
56
+ return this.plan(constraint, depth);
102
57
  }
103
58
  if (f & ts.TypeFlags.Union)
104
59
  return this.union(type, depth);
@@ -107,59 +62,66 @@ export class GeneratorFactory {
107
62
  if (f & ts.TypeFlags.Object)
108
63
  return this.object(type, depth);
109
64
  if (f & ts.TypeFlags.NonPrimitive)
110
- return fc.object();
65
+ return { k: 'object' };
111
66
  throw new UnsupportedType(`no generator for type ${this.checker.typeToString(type)}`);
112
67
  }
113
- registered(type) {
68
+ /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
69
+ registered(type, depth) {
114
70
  const symbol = type.aliasSymbol ?? type.getSymbol();
115
71
  if (symbol === undefined)
116
72
  return undefined;
117
- return arbitraryRegistry().get(symbol.getName());
73
+ const name = symbol.getName();
74
+ if (!arbitraryRegistry().has(name))
75
+ return undefined;
76
+ if (name === 'int')
77
+ return { k: 'named', name };
78
+ // What to generate if the registration is not there where the plan is used (a worker has only the built-in ones).
79
+ // `int` and the like are intersections that have no useful structure, so a type that cannot be planned has none.
80
+ try {
81
+ return { k: 'named', name, fallback: this.structural(type, depth) };
82
+ }
83
+ catch (error) {
84
+ if (error instanceof UnsupportedType)
85
+ return { k: 'named', name };
86
+ throw error;
87
+ }
118
88
  }
119
89
  union(type, depth) {
120
90
  const members = type.types.filter((t) => !(t.flags & ts.TypeFlags.Never));
121
- return fc.oneof(...members.map((member) => this.of(member, depth)));
91
+ return { k: 'union', of: members.map((member) => this.plan(member, depth)) };
122
92
  }
123
93
  template(type, depth) {
124
- const parts = [fc.constant(type.texts[0] ?? '')];
125
- type.types.forEach((t, i) => {
126
- parts.push(this.of(t, depth).map(String));
127
- parts.push(fc.constant(type.texts[i + 1] ?? ''));
128
- });
129
- return fc.tuple(...parts).map((p) => p.join(''));
94
+ return { k: 'template', texts: [...type.texts], parts: type.types.map((t) => this.plan(t, depth)) };
130
95
  }
131
96
  object(type, depth) {
132
97
  const checker = this.checker;
133
98
  if (this.active.has(type) || depth > 4)
134
- return fc.constant(undefined);
99
+ return { k: 'const', v: undefined };
135
100
  const name = type.getSymbol()?.getName();
136
101
  if (name === 'Date')
137
- return fc.date({ noInvalidDate: true });
102
+ return { k: 'date' };
138
103
  if (name === 'RegExp')
139
- return fc.constant(/x/);
104
+ return { k: 'regexp' };
140
105
  if (checker.isArrayType(type)) {
141
106
  const element = checker.getTypeArguments(type)[0];
142
- return sequence(this.of(element, depth + 1), { maxLength: 8 });
107
+ return { k: 'array', of: this.plan(element, depth + 1) };
143
108
  }
144
109
  if (checker.isTupleType(type)) {
145
110
  const target = type.target;
146
111
  const args = checker.getTypeArguments(type);
147
- const required = args.slice(0, target.minLength).map((t) => this.of(t, depth + 1));
148
- const optional = args.slice(target.minLength).map((t) => this.of(t, depth + 1));
149
- return fc.tuple(...required).chain((head) => {
150
- if (optional.length === 0)
151
- return fc.constant(head);
152
- return fc.tuple(...optional).map((tail) => [...head, ...tail]);
153
- });
112
+ return {
113
+ k: 'tuple',
114
+ required: args.slice(0, target.minLength).map((t) => this.plan(t, depth + 1)),
115
+ optional: args.slice(target.minLength).map((t) => this.plan(t, depth + 1)),
116
+ };
154
117
  }
155
118
  if (type.getCallSignatures().length > 0) {
156
119
  const signature = type.getCallSignatures()[0];
157
- const returns = this.of(checker.getReturnTypeOfSignature(signature), depth + 1);
158
- return fc.array(returns, { minLength: 1, maxLength: 4 }).map(generatedFunction);
120
+ return { k: 'fn', returns: this.plan(checker.getReturnTypeOfSignature(signature), depth + 1) };
159
121
  }
160
122
  this.active.add(type);
161
123
  try {
162
- const model = {};
124
+ const fields = {};
163
125
  const required = [];
164
126
  for (const property of checker.getPropertiesOfType(type)) {
165
127
  const declaration = property.valueDeclaration ?? property.declarations?.[0];
@@ -167,16 +129,14 @@ export class GeneratorFactory {
167
129
  continue;
168
130
  const propertyType = checker.getTypeOfSymbolAtLocation(property, declaration);
169
131
  const optional = (property.flags & ts.SymbolFlags.Optional) !== 0;
170
- const generator = this.of(optional ? checker.getNonNullableType(propertyType) : propertyType, depth + 1);
171
- model[property.getName()] = generator;
132
+ fields[property.getName()] = this.plan(optional ? checker.getNonNullableType(propertyType) : propertyType, depth + 1);
172
133
  if (!optional)
173
134
  required.push(property.getName());
174
135
  }
175
136
  const index = checker.getIndexInfosOfType(type)[0];
176
- if (index !== undefined && Object.keys(model).length === 0) {
177
- return fc.dictionary(fc.string({ maxLength: 6 }), this.of(index.type, depth + 1), { maxKeys: 6 });
178
- }
179
- return fc.record(model, { requiredKeys: required });
137
+ if (index !== undefined && Object.keys(fields).length === 0)
138
+ return { k: 'dict', of: this.plan(index.type, depth + 1) };
139
+ return { k: 'record', fields, required };
180
140
  }
181
141
  finally {
182
142
  this.active.delete(type);
@@ -0,0 +1,121 @@
1
+ import type { CheckReport } from './check.ts';
2
+ import type { LockChange } from './lock.ts';
3
+ import type { ProposalOutcome } from './types.ts';
4
+ export interface GithubConfig {
5
+ /** When proposals become accepted laws: on merge (default), or on merge once someone with authority said accept. */
6
+ accept: 'merge' | 'comment';
7
+ /** The branch whose merges write the lock. Default `master`. */
8
+ branch: string;
9
+ /**
10
+ * The login that alone writes tsc-laws.lock and the approval records. Default `github-actions[bot]`, allowed only
11
+ * with `accept: "merge"`: every workflow's token acts as that account, including jobs that run a pull request's
12
+ * code, so it could forge approval records, and only a ruleset on the branch keeps it from writing the lock. A
13
+ * dedicated GitHub App (`<app-slug>[bot]`) is required for `accept: "comment"` and is the stronger choice for both.
14
+ */
15
+ bot: string;
16
+ /**
17
+ * Who may accept in comment mode: `author` (the pull request's author, when a person), `reviewers` (anyone asked to
18
+ * review or who has reviewed), and/or a minimum repository permission (`write`, `maintain`, `admin`). Every login also
19
+ * needs write access to the repository. Default `["author", "reviewers"]`.
20
+ */
21
+ approvers: ('author' | 'reviewers' | 'write' | 'maintain' | 'admin')[];
22
+ /** Comment mode: approve the pull request once every proposal is accepted. Default false. */
23
+ approvePullRequest: boolean;
24
+ /** A proposal that fails (or is open) is never accepted, whatever was said. Default true. */
25
+ requirePassing: boolean;
26
+ }
27
+ export declare const githubDefaults: GithubConfig;
28
+ /** Whether the bot is an account any workflow can act as, rather than a dedicated GitHub App. */
29
+ export declare function isSharedBot(config: GithubConfig): boolean;
30
+ /** Validates the `github` section of tslaws.json and fills in the defaults. */
31
+ export declare function parseGithubConfig(raw: unknown): GithubConfig;
32
+ export interface Proposal {
33
+ key: string;
34
+ file: string;
35
+ name: string;
36
+ line: number;
37
+ kind: LockChange['kind'];
38
+ reason: LockChange['reason'];
39
+ fingerprint: string;
40
+ /** What the law did when it ran; undefined when the check did not report it (it did not run). */
41
+ outcome?: ProposalOutcome;
42
+ passes: boolean;
43
+ }
44
+ /** Joins the lock changes with what the check reported for each. */
45
+ export declare function proposalsOf(changes: LockChange[], report: CheckReport | undefined): Proposal[];
46
+ export type Command = {
47
+ verb: 'accept' | 'reject';
48
+ all: boolean;
49
+ names: string[];
50
+ };
51
+ /**
52
+ * The `/tslaws accept ...` and `/tslaws reject ...` lines of a comment. Names are law names or `file::name` keys,
53
+ * separated by spaces or commas; a name with spaces is written in backticks or quotes.
54
+ */
55
+ export declare function parseCommands(body: string): Command[];
56
+ /** The proposals a command names: by `file::name` key, or by law name when that name is unambiguous. */
57
+ export declare function resolveNames(proposals: Proposal[], command: Command): {
58
+ matched: Proposal[];
59
+ unknown: string[];
60
+ ambiguous: string[];
61
+ };
62
+ export interface ApprovalRecord {
63
+ verb: 'accept' | 'reject';
64
+ by: string;
65
+ /** The head commit the person saw. */
66
+ sha: string;
67
+ /** key and fingerprint of each proposal the record covers. */
68
+ items: {
69
+ key: string;
70
+ fingerprint: string;
71
+ }[];
72
+ }
73
+ /** The first line of a record comment. A record counts only in a bot comment made of this line and markers alone. */
74
+ export declare const recordHeader = "<!-- tslaws-records -->";
75
+ export declare function approvalMarker(record: ApprovalRecord): string;
76
+ /** The body of a record comment: the header line, then one marker per line. Nothing from the pull request appears raw. */
77
+ export declare function recordComment(records: ApprovalRecord[]): string;
78
+ /** Text from a pull request (law names, file paths, unknown words), made inert in a markdown comment. */
79
+ export declare function inert(text: string): string;
80
+ export interface IssueComment {
81
+ id: number;
82
+ body: string;
83
+ user: {
84
+ login: string;
85
+ type?: string;
86
+ };
87
+ created_at: string;
88
+ }
89
+ /**
90
+ * The approval records in record comments the bot wrote, oldest first. A comment counts only if it is the header line
91
+ * followed by markers and nothing else. Records in anyone else's comment, or in a bot comment that also holds other
92
+ * text (such as text a pull request put there), are ignored.
93
+ */
94
+ export declare function readApprovals(comments: IssueComment[], bot: string): ApprovalRecord[];
95
+ /**
96
+ * The fingerprints accepted by the records, latest word wins: a later reject withdraws an earlier accept of the same
97
+ * fingerprint. A fingerprint names one version of a law, so an edit after the accept leaves the new version unaccepted.
98
+ */
99
+ export declare function acceptedFingerprints(records: ApprovalRecord[]): Map<string, string>;
100
+ export interface Decision {
101
+ /** Fingerprints to write to the lock. */
102
+ accept: Set<string>;
103
+ /** Proposals left as they are, with the reason. */
104
+ held: {
105
+ proposal: Proposal;
106
+ why: string;
107
+ }[];
108
+ }
109
+ /** Which proposals the merge job accepts. */
110
+ export declare function decide(proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>): Decision;
111
+ /**
112
+ * The pull request's verdict: it fails when a law that is already accepted fails, when a proposal fails (a failing
113
+ * proposal is rejected outright), or in comment mode while a proposal waits for an accept.
114
+ */
115
+ export declare function pullRequestVerdict(report: CheckReport, proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>): {
116
+ ok: boolean;
117
+ problems: string[];
118
+ };
119
+ export declare const stickyMarker = "<!-- tslaws-proposals -->";
120
+ /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
121
+ export declare function renderSticky(proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>, link: (p: Proposal) => string): string;