tslaws 0.10.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 (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  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 +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -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 +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  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 +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  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/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
package/dist/coverage.js CHANGED
@@ -5,12 +5,14 @@
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
7
  import { parseGithubConfig } from "./github.js";
8
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
+ import { parseSecurityConfig } from "./security/deps/config.js";
9
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
9
10
  import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';
10
11
  import ts from 'typescript';
11
12
  import { parseE2eConfig } from "./e2e.js";
12
13
  import { globMatcher } from "./globs.js";
13
14
  import { customLawFile } from "./lawFiles.js";
15
+ import { certifyProblem } from "./certificates.js";
14
16
  import { importMetaEnvOf, parseEnvConfig } from "./runtimeEnv.js";
15
17
  import { solversProblem } from "./solvers.js";
16
18
  const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
@@ -19,15 +21,20 @@ const configKeys = [
19
21
  'laws',
20
22
  'levels',
21
23
  'solvers',
24
+ 'certify',
22
25
  'compilerOptions',
26
+ 'tsconfig',
23
27
  'e2e',
24
28
  'bundlerPlugins',
29
+ 'sandboxReads',
25
30
  'env',
26
31
  'github',
32
+ 'security',
33
+ 'jobs',
27
34
  ...settingKeys,
28
35
  ];
29
36
  /** Keys that steer inheritance and discovery rather than a run; `readConfig` acts on them and drops them. */
30
- const structuralKeys = ['extends', 'projects'];
37
+ const structuralKeys = ['extends', 'projects', 'standalone'];
31
38
  /** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
32
39
  export function projectsProblem(value) {
33
40
  if (!Array.isArray(value) ||
@@ -52,15 +59,24 @@ function checkFile(raw, source) {
52
59
  const projects = object.projects === undefined ? undefined : projectsProblem(object.projects);
53
60
  if (projects !== undefined)
54
61
  fail(projects);
55
- for (const key of settingKeys) {
62
+ if (object.standalone !== undefined && typeof object.standalone !== 'boolean')
63
+ fail(`"standalone" must be true or false, got ${JSON.stringify(object.standalone)}`);
64
+ for (const key of [...settingKeys, 'jobs']) {
56
65
  const value = object[key];
57
66
  if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value) || value < 1))
58
67
  fail(`"${key}" must be an integer of at least 1, got ${JSON.stringify(value)}`);
59
68
  }
69
+ const tsconfig = object.tsconfig;
70
+ if (tsconfig !== undefined && tsconfig !== false && (typeof tsconfig !== 'string' || tsconfig === ''))
71
+ fail(`"tsconfig" must be a path to a tsconfig file or false, got ${JSON.stringify(tsconfig)}`);
60
72
  const plugins = object.bundlerPlugins;
61
73
  if (plugins !== undefined &&
62
74
  (!Array.isArray(plugins) || plugins.some((entry) => typeof entry !== 'string' || entry === '')))
63
75
  fail(`"bundlerPlugins" must be an array of module paths, got ${JSON.stringify(plugins)}`);
76
+ const reads = object.sandboxReads;
77
+ if (reads !== undefined &&
78
+ (!Array.isArray(reads) || reads.some((entry) => typeof entry !== 'string' || entry === '')))
79
+ fail(`"sandboxReads" must be an array of directory paths, got ${JSON.stringify(reads)}`);
64
80
  if (object.env !== undefined)
65
81
  parseEnvConfig(object.env);
66
82
  const levels = object.levels;
@@ -69,11 +85,16 @@ function checkFile(raw, source) {
69
85
  const problem = object.solvers === undefined ? undefined : solversProblem(object.solvers);
70
86
  if (problem !== undefined)
71
87
  fail(problem);
88
+ const certifyIssue = object.certify === undefined ? undefined : certifyProblem(object.certify);
89
+ if (certifyIssue !== undefined)
90
+ fail(certifyIssue);
72
91
  const laws = object.laws;
73
92
  if (laws !== undefined &&
74
93
  (!Array.isArray(laws) ||
75
94
  laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
76
95
  fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
96
+ if (object.security !== undefined)
97
+ parseSecurityConfig(object.security);
77
98
  return object;
78
99
  }
79
100
  /**
@@ -95,10 +116,10 @@ export function parseConfig(raw, source = 'tslaws.json') {
95
116
  * relative to the file that declares it (as in tsconfig), so it is rebased to the extending file. `bundlerPlugins` are
96
117
  * module paths and `e2e.server.cwd` is the directory the dev server runs in. A trailing `[]` means every element of an
97
118
  * array. `cover` and `laws` are not here on purpose: they are globs relative to the project that uses the config, so a
98
- * shared base saying `"cover": ["src/**"]` means each package's own src/. `compilerOptions` and `github` hold no
119
+ * shared base saying `"cover": ["src/**"]` means each package's own src/. `compilerOptions`, `github` and `security` hold no
99
120
  * paths. Add a new file-reference option here when it is added to `configKeys`.
100
121
  */
101
- const pathFields = ['bundlerPlugins[]', 'e2e.server.cwd'];
122
+ const pathFields = ['bundlerPlugins[]', 'sandboxReads[]', 'e2e.server.cwd', 'tsconfig'];
102
123
  /** `entry`, written relative to the directory `from`, as a path relative to `to`. A leading `!` and absolute paths stay. */
103
124
  function rebase(entry, from, to) {
104
125
  const negated = entry.startsWith('!');
@@ -147,12 +168,59 @@ function deepMerge(base, child) {
147
168
  }
148
169
  return out;
149
170
  }
171
+ /**
172
+ * The text of an `extends` value if it is one this tool will follow: a non-empty relative path with forward slashes only.
173
+ * An absolute path, a drive or UNC path, a backslash, or a NUL is refused, so the on-disk loader and the GitHub checks
174
+ * that read the same files through the API resolve one target and never two.
175
+ */
176
+ export function checkExtendsValue(value) {
177
+ if (typeof value !== 'string' || value === '')
178
+ throw new Error(`"extends" must be a path to another tslaws.json, got ${JSON.stringify(value)}`);
179
+ // Letters, digits and . _ - / @ only: no `?`, `#`, `&` or `%` (which change an API URL's query), no backslash, NUL,
180
+ // space or drive colon.
181
+ if (!/^[A-Za-z0-9._\-/@]+$/.test(value) || value.startsWith('/'))
182
+ throw new Error(`"extends" must be a relative path of letters, digits and . _ - / @ with forward slashes, got ${JSON.stringify(value)}`);
183
+ return value;
184
+ }
185
+ /**
186
+ * Where `extends` points, as a repository path: `fromFile` is the repository path of the file that names it. Refuses
187
+ * what `checkExtendsValue` does, and a target that leaves the repository.
188
+ */
189
+ export function extendsTarget(fromFile, value) {
190
+ const target = posix.normalize(posix.join(posix.dirname(fromFile), checkExtendsValue(value)));
191
+ if (target === '..' || target.startsWith('../') || posix.isAbsolute(target))
192
+ throw new Error(`"extends" ${JSON.stringify(value)} in ${fromFile} leaves the repository`);
193
+ return target;
194
+ }
195
+ /**
196
+ * The directory no `extends` may leave: the nearest enclosing directory with a `.git`, else the highest enclosing one
197
+ * that carries a workspace file (`tslaws.json`, `package.json` or `pnpm-workspace.yaml`), else `cwd` itself.
198
+ */
199
+ export function extendsRoot(cwd) {
200
+ let top = resolve(cwd);
201
+ let dir = top;
202
+ for (;;) {
203
+ if (existsSync(join(dir, '.git')))
204
+ return dir;
205
+ if (['tslaws.json', 'package.json', 'pnpm-workspace.yaml'].some((f) => existsSync(join(dir, f))))
206
+ top = dir;
207
+ const parent = dirname(dir);
208
+ if (parent === dir)
209
+ return top;
210
+ dir = parent;
211
+ }
212
+ }
213
+ /** Whether `inner` is `outer` or inside it, by path alone. */
214
+ const within = (outer, inner) => {
215
+ const rel = relative(outer, inner);
216
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
217
+ };
150
218
  /**
151
219
  * Loads `file` and the files it `extends`, merged, with paths relative to the directory of `file`. `chain` holds the
152
220
  * files being loaded, outermost first, so a cycle or a missing file is reported with the way it was reached; every
153
221
  * file read is added to `loaded`.
154
222
  */
155
- function loadMerged(file, cwd, chain, loaded) {
223
+ function loadMerged(file, cwd, root, chain, loaded) {
156
224
  const shown = (path) => relative(cwd, path).replaceAll('\\', '/') || path;
157
225
  const trail = [...chain, file];
158
226
  let text;
@@ -162,23 +230,37 @@ function loadMerged(file, cwd, chain, loaded) {
162
230
  catch {
163
231
  throw new Error(`${shown(file)}: no such file (reached by extends: ${trail.map(shown).join(' -> ')})`);
164
232
  }
233
+ // A symlink is not followed: the GitHub checks read a repository file as a blob and refuse a link, so a link here
234
+ // would be a file only one side reads.
235
+ if (lstatSync(file).isSymbolicLink())
236
+ throw new Error(`${shown(file)}: a symlink, which tslaws does not follow (reached by extends: ${trail.map(shown).join(' -> ')})`);
165
237
  loaded.push(file);
166
238
  let json;
167
239
  try {
168
240
  json = JSON.parse(text);
169
241
  }
170
- catch (error) {
171
- throw new Error(`${shown(file)}: ${error.message}`);
242
+ catch {
243
+ // The parser's message quotes the file's text, which is not ours to echo into a log.
244
+ throw new Error(`${shown(file)}: not valid JSON`);
172
245
  }
173
246
  const { extends: parent, ...own } = checkFile(json, shown(file));
174
247
  if (parent === undefined)
175
248
  return own;
176
- const baseFile = resolve(dirname(file), parent);
249
+ const baseFile = resolve(dirname(file), checkExtendsValue(parent));
250
+ // The same containment as the GitHub checks (`extendsTarget`): by path, and by where a link or a linked directory
251
+ // really leads.
252
+ const outside = () => new Error(`${shown(file)}: "extends" ${JSON.stringify(parent)} leaves the repository (${shown(root)})`);
253
+ if (!within(root, baseFile))
254
+ throw outside();
255
+ if (existsSync(baseFile) && !within(realpathSync(root), realpathSync(baseFile)))
256
+ throw outside();
177
257
  if (trail.includes(baseFile))
178
258
  throw new Error(`${shown(file)}: "extends" forms a cycle (${[...trail, baseFile].map(shown).join(' -> ')})`);
179
- const base = rebaseFields(loadMerged(baseFile, cwd, trail, loaded), dirname(baseFile), dirname(file));
180
- // `projects` lists directories under the file that wrote it, so it is never inherited.
259
+ const base = rebaseFields(loadMerged(baseFile, cwd, root, trail, loaded), dirname(baseFile), dirname(file));
260
+ // `projects` lists directories under the file that wrote it, so it is never inherited; nor is `standalone`, which is
261
+ // about the one project whose file says it.
181
262
  delete base.projects;
263
+ delete base.standalone;
182
264
  return deepMerge(base, own);
183
265
  }
184
266
  /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
@@ -187,7 +269,7 @@ export function readConfig(cwd) {
187
269
  if (!existsSync(path))
188
270
  return {};
189
271
  const loaded = [];
190
- const merged = loadMerged(path, cwd, [], loaded);
272
+ const merged = loadMerged(path, cwd, extendsRoot(cwd), [], loaded);
191
273
  let config;
192
274
  try {
193
275
  config = parseConfig(merged);
package/dist/e2eApi.js CHANGED
@@ -4,7 +4,8 @@
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { createRequire } from 'node:module';
6
6
  import { join } from 'node:path';
7
- // The runner and the law may load this module through different paths (an ESM import and a CommonJS `require`), so
7
+ // The runner and the law may load this module through different paths (an ESM import and the CommonJS `require` of a
8
+ // compiled law), so
8
9
  // the storage lives on the global object and both see the same one.
9
10
  const key = Symbol.for('tslaws.e2e.state');
10
11
  function storage() {
@@ -63,6 +64,7 @@ export async function a11y(target, options = {}) {
63
64
  const used = target ?? state.page;
64
65
  let axePath;
65
66
  try {
67
+ // Resolution only, from the project's directory (`import.meta.resolve` starts from this file); no CommonJS is loaded.
66
68
  axePath = createRequire(join(state.cwd, 'package.json')).resolve('axe-core/axe.min.js');
67
69
  }
68
70
  catch {
@@ -1,7 +1,12 @@
1
1
  import ts from 'typescript';
2
2
  import { arbitraryRegistry } from "./api.js";
3
+ import { registerSecurityGenerators, securityTypeNames } from "./security/generators.js";
3
4
  import { arbitraryOf, UnsupportedType } from "./plan.js";
4
5
  export { toWire, UnsupportedType, wireKey } from "./plan.js";
6
+ /** Whether a type is declared in tslaws' own security module, not by a project that reuses the name. */
7
+ function declaredBySecurity(symbol) {
8
+ return (symbol.declarations ?? []).some((d) => /\/tslaws\/(dist|src)\/security\//.test(d.getSourceFile().fileName));
9
+ }
5
10
  export class GeneratorFactory {
6
11
  checker;
7
12
  active = new Set();
@@ -71,18 +76,23 @@ export class GeneratorFactory {
71
76
  if (symbol === undefined)
72
77
  return undefined;
73
78
  const name = symbol.getName();
79
+ // The payload types of tslaws/security have their generators even when the law has not been loaded yet.
80
+ const security = securityTypeNames.has(name) && declaredBySecurity(symbol);
81
+ if (security && !arbitraryRegistry().has(name))
82
+ registerSecurityGenerators();
74
83
  if (!arbitraryRegistry().has(name))
75
84
  return undefined;
76
85
  if (name === 'int')
77
86
  return { k: 'named', name };
87
+ const tag = security ? { security: true } : {};
78
88
  // What to generate if the registration is not there where the plan is used (a worker has only the built-in ones).
79
89
  // `int` and the like are intersections that have no useful structure, so a type that cannot be planned has none.
80
90
  try {
81
- return { k: 'named', name, fallback: this.structural(type, depth) };
91
+ return { k: 'named', name, fallback: this.structural(type, depth), ...tag };
82
92
  }
83
93
  catch (error) {
84
94
  if (error instanceof UnsupportedType)
85
- return { k: 'named', name };
95
+ return { k: 'named', name, ...tag };
86
96
  throw error;
87
97
  }
88
98
  }
package/dist/github.d.ts CHANGED
@@ -23,6 +23,18 @@ export interface GithubConfig {
23
23
  approvePullRequest: boolean;
24
24
  /** A proposal that fails (or is open) is never accepted, whatever was said. Default true. */
25
25
  requirePassing: boolean;
26
+ /**
27
+ * `shared` (default): the repository-wide flow that runs from the monorepo root covers this project. `own`: the
28
+ * project keeps these settings but runs its own workflow (`tslaws github <mode> --project <dir>`); the root's
29
+ * report, merge and command leave it out. The root's verify still watches its lock.
30
+ */
31
+ flow: 'shared' | 'own';
32
+ /**
33
+ * Whether a person may also change tsc-laws.lock directly: `tslaws accept` on their machine, or a pull request from
34
+ * someone with `admin` or `maintain` access. The workflow stays the way to accept on merge or on demand. Set false
35
+ * to make the workflow the only writer. Default true.
36
+ */
37
+ local: boolean;
26
38
  }
27
39
  export declare const githubDefaults: GithubConfig;
28
40
  /** Whether the bot is an account any workflow can act as, rather than a dedicated GitHub App. */
@@ -37,23 +49,35 @@ export interface Proposal {
37
49
  kind: LockChange['kind'];
38
50
  reason: LockChange['reason'];
39
51
  fingerprint: string;
52
+ /** The project's path in the repository ('' for the root). Absent means the root. */
53
+ project?: string;
40
54
  /** What the law did when it ran; undefined when the check did not report it (it did not run). */
41
55
  outcome?: ProposalOutcome;
42
56
  passes: boolean;
43
57
  }
44
58
  /** Joins the lock changes with what the check reported for each. */
45
- export declare function proposalsOf(changes: LockChange[], report: CheckReport | undefined): Proposal[];
59
+ export declare function proposalsOf(changes: LockChange[], report: CheckReport | undefined, project?: string): Proposal[];
46
60
  export type Command = {
47
61
  verb: 'accept' | 'reject';
48
62
  all: boolean;
49
63
  names: string[];
64
+ /** `--project <dir>` (repeatable): the command covers only proposals of these projects. */
65
+ projects?: string[];
66
+ /** Why the line cannot be followed (a `--project` with no directory). Nothing is recorded for a comment with one. */
67
+ error?: string;
50
68
  };
51
69
  /**
52
70
  * The `/tslaws accept ...` and `/tslaws reject ...` lines of a comment. Names are law names or `file::name` keys,
53
71
  * separated by spaces or commas; a name with spaces is written in backticks or quotes.
54
72
  */
55
73
  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. */
74
+ /** A proposal's key from the repository root: the project's path, then the project-relative `file::name`. */
75
+ export declare function repoKey(p: Proposal): string;
76
+ /**
77
+ * The proposals a command names. A name is a key from the repository root (`packages/a/src/x.laws.ts::name`), a
78
+ * project-relative `file::name` key, or a law name; the first form that matches decides, and a name that still matches
79
+ * more than one proposal (in several files or several projects) is ambiguous. `--project` limits the proposals first.
80
+ */
57
81
  export declare function resolveNames(proposals: Proposal[], command: Command): {
58
82
  matched: Proposal[];
59
83
  unknown: string[];
@@ -64,6 +88,11 @@ export interface ApprovalRecord {
64
88
  by: string;
65
89
  /** The head commit the person saw. */
66
90
  sha: string;
91
+ /**
92
+ * The project the record is about, as its path in the repository ('' for the root). A record counts only for that
93
+ * project. Absent (a record written before projects were told apart) means the root.
94
+ */
95
+ project?: string;
67
96
  /** key and fingerprint of each proposal the record covers. */
68
97
  items: {
69
98
  key: string;
@@ -93,10 +122,12 @@ export interface IssueComment {
93
122
  */
94
123
  export declare function readApprovals(comments: IssueComment[], bot: string): ApprovalRecord[];
95
124
  /**
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.
125
+ * The fingerprints accepted by the records for one project, latest word wins: a later reject withdraws an earlier
126
+ * accept of the same fingerprint. A fingerprint names one version of a law, so an edit after the accept leaves the new
127
+ * version unaccepted. Only records of `project` count (default the root, which also takes records with no project), so
128
+ * an accept of a law in one project never accepts the same-named or same-fingerprint law of another.
98
129
  */
99
- export declare function acceptedFingerprints(records: ApprovalRecord[]): Map<string, string>;
130
+ export declare function acceptedFingerprints(records: ApprovalRecord[], project?: string): Map<string, string>;
100
131
  export interface Decision {
101
132
  /** Fingerprints to write to the lock. */
102
133
  accept: Set<string>;
@@ -121,3 +152,16 @@ export declare const stickyMarker = "<!-- tslaws-proposals -->";
121
152
  export declare function stickyMarkerFor(project?: string): string;
122
153
  /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
123
154
  export declare function renderSticky(proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>, link: (p: Proposal) => string, project?: string): string;
155
+ export interface StickySection {
156
+ /** The project's path in the repository ('' for the root). */
157
+ project: string;
158
+ proposals: Proposal[];
159
+ config: GithubConfig;
160
+ approvals: Map<string, string>;
161
+ link: (p: Proposal) => string;
162
+ }
163
+ /**
164
+ * One sticky comment for a monorepo root run: a section per project that has proposals, and one line naming the rest.
165
+ * `marker` is the comment's own marker (the root's), so the per-project comments of single-project runs stay separate.
166
+ */
167
+ export declare function renderStickyAll(sections: StickySection[], marker: string): string;
package/dist/github.js CHANGED
@@ -5,6 +5,8 @@ export const githubDefaults = {
5
5
  approvers: ['author', 'reviewers'],
6
6
  approvePullRequest: false,
7
7
  requirePassing: true,
8
+ flow: 'shared',
9
+ local: true,
8
10
  };
9
11
  const approverKinds = ['author', 'reviewers', 'write', 'maintain', 'admin'];
10
12
  /** Logins any workflow can act as. */
@@ -21,7 +23,7 @@ export function parseGithubConfig(raw) {
21
23
  if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
22
24
  return fail('must be an object');
23
25
  const o = raw;
24
- const known = ['accept', 'branch', 'bot', 'approvers', 'approvePullRequest', 'requirePassing'];
26
+ const known = ['accept', 'branch', 'bot', 'approvers', 'approvePullRequest', 'requirePassing', 'flow', 'local'];
25
27
  for (const key of Object.keys(o))
26
28
  if (!known.includes(key))
27
29
  fail(`unknown option "${key}"; supported: ${known.join(', ')}`);
@@ -35,7 +37,9 @@ export function parseGithubConfig(raw) {
35
37
  o.approvers.length === 0 ||
36
38
  o.approvers.some((a) => !approverKinds.includes(a))))
37
39
  fail(`"approvers" must be a non-empty array of ${approverKinds.join(', ')}`);
38
- for (const key of ['approvePullRequest', 'requirePassing'])
40
+ if (o.flow !== undefined && o.flow !== 'shared' && o.flow !== 'own')
41
+ fail(`"flow" must be "shared" or "own", got ${JSON.stringify(o.flow)}`);
42
+ for (const key of ['approvePullRequest', 'requirePassing', 'local'])
39
43
  if (o[key] !== undefined && typeof o[key] !== 'boolean')
40
44
  fail(`"${key}" must be true or false`);
41
45
  const config = { ...githubDefaults, ...o };
@@ -45,7 +49,7 @@ export function parseGithubConfig(raw) {
45
49
  }
46
50
  const passingStatuses = new Set(['proved', 'bounded', 'tested']);
47
51
  /** Joins the lock changes with what the check reported for each. */
48
- export function proposalsOf(changes, report) {
52
+ export function proposalsOf(changes, report, project = '') {
49
53
  const results = new Map();
50
54
  for (const result of report?.results ?? [])
51
55
  results.set(`${result.file.replaceAll('\\', '/')}::${result.name}`, result);
@@ -67,11 +71,17 @@ export function proposalsOf(changes, report) {
67
71
  kind: change.kind,
68
72
  reason: change.reason,
69
73
  fingerprint: change.fingerprint,
74
+ project,
70
75
  ...(outcome === undefined ? {} : { outcome }),
71
76
  passes: outcome !== undefined && passingStatuses.has(outcome.status),
72
77
  };
73
78
  });
74
79
  }
80
+ const cleanProject = (dir) => dir
81
+ .replaceAll('\\', '/')
82
+ .replace(/^(\.\/)+/, '')
83
+ .replace(/\/+$/, '')
84
+ .replace(/^\.$/, '');
75
85
  /**
76
86
  * The `/tslaws accept ...` and `/tslaws reject ...` lines of a comment. Names are law names or `file::name` keys,
77
87
  * separated by spaces or commas; a name with spaces is written in backticks or quotes.
@@ -88,30 +98,78 @@ export function parseCommands(body) {
88
98
  const verb = match[1].toLowerCase();
89
99
  const rest = match[2].trim();
90
100
  const names = [];
101
+ const projects = [];
91
102
  const token = /`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s,]+)/g;
92
- for (let m = token.exec(rest); m !== null; m = token.exec(rest))
93
- names.push((m[1] ?? m[2] ?? m[3] ?? m[4]));
103
+ let wantsProject = false;
104
+ let error;
105
+ const noDirectory = '`--project` needs a directory, as in `--project packages/a`; nothing was recorded';
106
+ for (let m = token.exec(rest); m !== null; m = token.exec(rest)) {
107
+ const word = (m[1] ?? m[2] ?? m[3] ?? m[4]);
108
+ if (wantsProject) {
109
+ // `--project --other` is a flag where a directory belongs: refuse it rather than read it as a directory.
110
+ if (word.startsWith('-'))
111
+ error ??= noDirectory;
112
+ else
113
+ projects.push(cleanProject(word));
114
+ wantsProject = false;
115
+ }
116
+ else if (word === '--project')
117
+ wantsProject = true;
118
+ else if (word.startsWith('--project=')) {
119
+ const dir = cleanProject(word.slice('--project='.length));
120
+ if (word === '--project=')
121
+ error ??= noDirectory;
122
+ else
123
+ projects.push(dir);
124
+ }
125
+ else
126
+ names.push(word);
127
+ }
128
+ // A dangling `--project` must not widen the command to every project.
129
+ if (wantsProject)
130
+ error ??= noDirectory;
94
131
  const all = names.length === 0 || names.some((n) => n.toLowerCase() === 'all');
95
- commands.push({ verb, all, names: all ? [] : names });
132
+ commands.push({
133
+ verb,
134
+ all,
135
+ names: all ? [] : names,
136
+ ...(projects.length > 0 ? { projects } : {}),
137
+ ...(error === undefined ? {} : { error }),
138
+ });
96
139
  }
97
140
  return commands;
98
141
  }
99
- /** The proposals a command names: by `file::name` key, or by law name when that name is unambiguous. */
142
+ /** A proposal's key from the repository root: the project's path, then the project-relative `file::name`. */
143
+ export function repoKey(p) {
144
+ return p.project === undefined || p.project === '' ? p.key : `${p.project}/${p.key}`;
145
+ }
146
+ /**
147
+ * The proposals a command names. A name is a key from the repository root (`packages/a/src/x.laws.ts::name`), a
148
+ * project-relative `file::name` key, or a law name; the first form that matches decides, and a name that still matches
149
+ * more than one proposal (in several files or several projects) is ambiguous. `--project` limits the proposals first.
150
+ */
100
151
  export function resolveNames(proposals, command) {
152
+ const scope = command.projects;
153
+ const inScope = scope === undefined ? proposals : proposals.filter((p) => scope.includes(p.project ?? ''));
101
154
  if (command.all)
102
- return { matched: proposals, unknown: [], ambiguous: [] };
155
+ return { matched: inScope, unknown: [], ambiguous: [] };
156
+ // The same law text can be proposed by two projects with one fingerprint, so a proposal is told apart by project too.
103
157
  const matched = new Map();
104
158
  const unknown = [];
105
159
  const ambiguous = [];
106
160
  for (const name of command.names) {
107
- const byKey = proposals.filter((p) => p.key === name);
108
- const byName = byKey.length > 0 ? byKey : proposals.filter((p) => p.name === name);
109
- if (byName.length === 0)
161
+ const forms = [
162
+ inScope.filter((p) => repoKey(p) === name),
163
+ inScope.filter((p) => p.key === name),
164
+ inScope.filter((p) => p.name === name),
165
+ ];
166
+ const found = forms.find((list) => list.length > 0) ?? [];
167
+ if (found.length === 0)
110
168
  unknown.push(name);
111
- else if (byName.length > 1)
169
+ else if (found.length > 1)
112
170
  ambiguous.push(name);
113
171
  else
114
- matched.set(byName[0].fingerprint, byName[0]);
172
+ matched.set(`${found[0].project ?? ''}\0${found[0].fingerprint}`, found[0]);
115
173
  }
116
174
  return { matched: [...matched.values()], unknown, ambiguous };
117
175
  }
@@ -158,6 +216,7 @@ export function readApprovals(comments, bot) {
158
216
  const record = JSON.parse(json);
159
217
  if ((record.verb === 'accept' || record.verb === 'reject') &&
160
218
  typeof record.by === 'string' &&
219
+ (record.project === undefined || typeof record.project === 'string') &&
161
220
  Array.isArray(record.items) &&
162
221
  record.items.every((i) => typeof i?.key === 'string' && typeof i?.fingerprint === 'string'))
163
222
  found.push(record);
@@ -174,18 +233,23 @@ export function readApprovals(comments, bot) {
174
233
  return records;
175
234
  }
176
235
  /**
177
- * The fingerprints accepted by the records, latest word wins: a later reject withdraws an earlier accept of the same
178
- * fingerprint. A fingerprint names one version of a law, so an edit after the accept leaves the new version unaccepted.
236
+ * The fingerprints accepted by the records for one project, latest word wins: a later reject withdraws an earlier
237
+ * accept of the same fingerprint. A fingerprint names one version of a law, so an edit after the accept leaves the new
238
+ * version unaccepted. Only records of `project` count (default the root, which also takes records with no project), so
239
+ * an accept of a law in one project never accepts the same-named or same-fingerprint law of another.
179
240
  */
180
- export function acceptedFingerprints(records) {
241
+ export function acceptedFingerprints(records, project = '') {
181
242
  const accepted = new Map();
182
- for (const record of records)
243
+ for (const record of records) {
244
+ if ((record.project ?? '') !== project)
245
+ continue;
183
246
  for (const item of record.items) {
184
247
  if (record.verb === 'accept')
185
248
  accepted.set(item.fingerprint, record.by);
186
249
  else
187
250
  accepted.delete(item.fingerprint);
188
251
  }
252
+ }
189
253
  return accepted;
190
254
  }
191
255
  /** Which proposals the merge job accepts. */
@@ -253,12 +317,8 @@ function outcomeText(p) {
253
317
  return `${icon} ${p.outcome.status}${extra === '' ? '' : ` — ${extra}`}`;
254
318
  }
255
319
  const what = (p) => p.kind === 'exempt' ? `exemption ${p.reason}` : p.reason === 'level' ? 'level changed' : `law ${p.reason}`;
256
- /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
257
- export function renderSticky(proposals, config, approvals, link, project = '') {
258
- const title = project === '' ? '' : ` for \`${project.replace(/`/g, "'")}\``;
259
- const head = `${stickyMarkerFor(project)}\n### tslaws proposals${title}\n\n`;
260
- if (proposals.length === 0)
261
- return `${head}No law, level or coverage exemption differs from \`tsc-laws.lock\`.\n`;
320
+ /** The table of proposals and the sentence on how they are accepted. */
321
+ function renderTable(proposals, config, approvals, link) {
262
322
  const rows = proposals.map((p) => {
263
323
  const state = !p.passes && config.requirePassing
264
324
  ? '🚫 rejected while it fails'
@@ -272,5 +332,28 @@ export function renderSticky(proposals, config, approvals, link, project = '') {
272
332
  const how = config.accept === 'merge'
273
333
  ? `Proposals that pass are written to \`tsc-laws.lock\` by the tslaws workflow when this pull request merges into \`${config.branch}\`. Failing proposals are never accepted.`
274
334
  : `Reply \`/tslaws accept <law>\` (or \`/tslaws accept all\`) to accept, \`/tslaws reject <law>\` to withdraw. An accept covers the version shown here; a later edit needs a new accept. Accepted proposals are written to \`tsc-laws.lock\` when this pull request merges into \`${config.branch}\`.`;
275
- return `${head}| Law | Change | If accepted | State |\n| --- | --- | --- | --- |\n${rows.join('\n')}\n\n${how}\n`;
335
+ return `| Law | Change | If accepted | State |\n| --- | --- | --- | --- |\n${rows.join('\n')}\n\n${how}\n`;
336
+ }
337
+ /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
338
+ export function renderSticky(proposals, config, approvals, link, project = '') {
339
+ const title = project === '' ? '' : ` for \`${project.replace(/`/g, "'")}\``;
340
+ const head = `${stickyMarkerFor(project)}\n### tslaws proposals${title}\n\n`;
341
+ if (proposals.length === 0)
342
+ return `${head}No law, level or coverage exemption differs from \`tsc-laws.lock\`.\n`;
343
+ return `${head}${renderTable(proposals, config, approvals, link)}`;
344
+ }
345
+ /**
346
+ * One sticky comment for a monorepo root run: a section per project that has proposals, and one line naming the rest.
347
+ * `marker` is the comment's own marker (the root's), so the per-project comments of single-project runs stay separate.
348
+ */
349
+ export function renderStickyAll(sections, marker) {
350
+ const head = `${marker}\n### tslaws proposals\n\n`;
351
+ const proposed = sections.filter((s) => s.proposals.length > 0);
352
+ const quiet = sections
353
+ .filter((s) => s.proposals.length === 0)
354
+ .map((s) => `\`${(s.project || '.').replace(/`/g, "'")}\``);
355
+ if (proposed.length === 0)
356
+ return `${head}No law, level or coverage exemption differs from \`tsc-laws.lock\` in any of ${sections.length} project${sections.length === 1 ? '' : 's'}.\n`;
357
+ const parts = proposed.map((s) => `#### \`${(s.project || '.').replace(/`/g, "'")}\`\n\n${renderTable(s.proposals, s.config, s.approvals, s.link)}`);
358
+ return `${head}${parts.join('\n')}${quiet.length === 0 ? '' : `\nNo change in ${quiet.join(', ')}.\n`}`;
276
359
  }
@@ -16,7 +16,27 @@ export interface GithubContext {
16
16
  err: (text: string) => void;
17
17
  /** For tests: a stand-in for the GitHub REST API. */
18
18
  api?: Api;
19
+ /**
20
+ * Set when the run covers a monorepo root: every selected project, each with its own directory and options. `cwd`
21
+ * and `projectPath` then name the root, and `options` is unused.
22
+ */
23
+ projects?: Unit[];
24
+ /** Every project under the root, standalone ones included (project-relative paths, '' for the root itself). */
25
+ discovered?: string[];
26
+ /** The check options of a discovered project, or undefined when it is not one. */
27
+ optionsFor?: (rel: string) => CheckOptions | undefined;
28
+ }
29
+ /** One project of a run. */
30
+ export interface Unit {
31
+ cwd: string;
32
+ /** Relative to the monorepo root ('' for the root itself). */
33
+ rel: string;
34
+ /** From the repository root, with '/' separators ('' for the repository root). */
35
+ path: string;
36
+ options: CheckOptions;
19
37
  }
38
+ /** Two repo-relative paths joined; either may be ''. */
39
+ export declare function joinRepo(prefix: string, file: string): string;
20
40
  /** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
21
41
  export declare function projectPathOf(cwd: string, flag: string | true | undefined): string;
22
42
  export type Api = (method: string, path: string, body?: unknown) => Promise<unknown>;
@@ -33,10 +53,13 @@ interface PullRequest {
33
53
  ref: string;
34
54
  sha: string;
35
55
  };
56
+ /** How many files the pull request changes, as GitHub counts them (the files list is capped at 3000). */
57
+ changed_files?: number;
36
58
  requested_reviewers?: {
37
59
  login: string;
38
60
  }[];
39
61
  merged?: boolean;
62
+ merged_at?: string | null;
40
63
  }
41
64
  /** The `github` section of a tslaws.json text, with defaults. It must exist: it names the bot every check trusts. */
42
65
  export declare function githubConfigOf(text: string | undefined): GithubConfig;
@@ -47,6 +70,11 @@ interface ProjectState {
47
70
  lock: Lock | undefined;
48
71
  }
49
72
  export declare function projectState(options: CheckOptions): ProjectState;
73
+ /**
74
+ * Whether `login` has `admin` or `maintain` access: the people who may change tsc-laws.lock by hand or run the merge
75
+ * job on demand. A bot never counts, and neither does a login whose permission cannot be read.
76
+ */
77
+ export declare function maintains(api: Api, name: string, login: string, type?: string): Promise<boolean>;
50
78
  /** Why `login` may not accept on this pull request, or undefined when they may. */
51
79
  export declare function refusal(api: Api, name: string, pr: PullRequest, login: string, type: string, config: GithubConfig): Promise<string | undefined>;
52
80
  export declare function githubCommand(action: string | undefined, ctx: GithubContext): Promise<number>;