architecture-harness 0.23.0 → 0.23.1

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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +18 -5
  3. package/src/cli/bash-command-guard.mjs +44 -5
  4. package/src/cli/bash-command-guard.test.mjs +35 -1
  5. package/src/cli/check-commands.mjs +82 -0
  6. package/src/cli/check-commands.test.mjs +190 -0
  7. package/src/cli/check.mjs +34 -13
  8. package/src/cli/ci-template.test.mjs +12 -0
  9. package/src/cli/cli.test.mjs +11 -0
  10. package/src/cli/commit-msg.mjs +5 -2
  11. package/src/cli/commit-msg.test.mjs +12 -0
  12. package/src/cli/generated-file-guard.mjs +10 -1
  13. package/src/cli/generated-file-guard.test.mjs +10 -0
  14. package/src/cli/post-edit-gate.test.mjs +9 -2
  15. package/src/cli/pr-check.mjs +15 -2
  16. package/src/cli/pr-check.test.mjs +19 -9
  17. package/src/cli/qc.mjs +15 -4
  18. package/src/cli/shell-command.mjs +3 -1
  19. package/src/cli/stop-gate.test.mjs +17 -0
  20. package/src/cli/work-order-guard.mjs +2 -2
  21. package/src/config.mjs +15 -0
  22. package/src/config.test.mjs +33 -1
  23. package/src/eslint/rules/no-raw-fetch.mjs +42 -2
  24. package/src/eslint/rules.test.mjs +15 -0
  25. package/src/gates/audit-append-only.mjs +18 -4
  26. package/src/gates/audit-append-only.test.mjs +19 -0
  27. package/src/gates/tenant-predicate.mjs +147 -7
  28. package/src/gates/tenant-predicate.test.mjs +55 -0
  29. package/src/gates/tenant-tables.mjs +5 -2
  30. package/src/gates/tenant-tables.test.mjs +8 -0
  31. package/src/gates/threshold-ratchet.mjs +12 -9
  32. package/src/gates/threshold-ratchet.test.mjs +16 -0
  33. package/src/plugin.test.mjs +28 -0
  34. package/src/screens/auth-run.test.mjs +20 -17
  35. package/src/screens/capture-idle.test.mjs +2 -1
  36. package/src/screens/catalog.test.mjs +3 -3
  37. package/src/screens/chrome.mjs +21 -0
  38. package/templates/github/workflows/ci.yml +13 -5
@@ -10,6 +10,8 @@ import { scriptPattern } from "../gates/english-source.mjs";
10
10
 
11
11
  export const INSTALL_HINT = "pnpm add -D @commitlint/lint @commitlint/config-conventional";
12
12
  const TRAILER = /^co-authored-by:\s*\S/im;
13
+ // `git commit -v` puts the diff under this line, after the comment character, and git drops it all.
14
+ const SCISSORS = /^\S -{24} >8 -{24}\s*$/;
13
15
 
14
16
  const importPath = async (file) => (await import(pathToFileURL(file).href)).default;
15
17
 
@@ -58,8 +60,9 @@ export async function loadCommitlint(root) {
58
60
  * @returns {Promise<{rule: string, detail: string}[]>}
59
61
  */
60
62
  export async function checkCommitMessage(raw, options, commitlint) {
61
- const message = raw
62
- .split(/\r?\n/)
63
+ const lines = raw.split(/\r?\n/);
64
+ const cut = lines.findIndex((line) => SCISSORS.test(line));
65
+ const message = (cut === -1 ? lines : lines.slice(0, cut))
63
66
  .filter((line) => !line.startsWith("#"))
64
67
  .join("\n")
65
68
  .trim();
@@ -31,6 +31,18 @@ test("a message that is not English fails, whatever commitlint says", async () =
31
31
  assert.deepEqual(problems.map((problem) => problem.rule), ["english"]);
32
32
  });
33
33
 
34
+ test("the diff that git commit -v puts under the scissors line is not part of the message", async () => {
35
+ const commitlint = await loadCommitlint(HARNESS);
36
+ const raw = [
37
+ "fix(ui): save the photo",
38
+ "# ------------------------ >8 ------------------------",
39
+ "# Do not modify or remove the line above.",
40
+ "diff --git a/x.ts b/x.ts",
41
+ `+const label = "写真を保存する"; ${"x".repeat(120)}`,
42
+ ].join("\n");
43
+ assert.deepEqual(await checkCommitMessage(raw, {}, commitlint), []);
44
+ });
45
+
34
46
  test("with no commitlint installed, the check fails with the install command, unless conventional is off", async (t) => {
35
47
  const commitlint = await loadCommitlint(emptyDir(t));
36
48
  assert.equal(commitlint, null);
@@ -36,6 +36,14 @@ function editsRegion(file, input) {
36
36
  return edits.some((one) => typeof one?.old_string === "string" && one.old_string !== "" && touchesRegion(text, lf(one.old_string), regions));
37
37
  }
38
38
 
39
+ /** True when a Write of the Markdown file changes or drops a generated region. Text outside them is free. */
40
+ function writesRegion(file, content) {
41
+ if (!existsSync(file) || typeof content !== "string") return false;
42
+ const regionsOf = (text) => generatedRegions(text).map(([start, end]) => text.slice(start, end));
43
+ const after = regionsOf(lf(content));
44
+ return regionsOf(lf(readFileSync(file, "utf8"))).some((region) => !after.includes(region));
45
+ }
46
+
39
47
  /** The verdict on one edit. @returns the hook output, or null to let the call run with no message. */
40
48
  export function decide(call) {
41
49
  const input = call.tool_input ?? {};
@@ -56,7 +64,8 @@ export function decide(call) {
56
64
  if (globMatcher(generated.globs)(rel)) {
57
65
  return deny(`Generated-file guard: ${rel} is generated. ${rerun}`);
58
66
  }
59
- if (call.tool_name !== "Write" && MARKDOWN.test(rel) && editsRegion(file, input)) {
67
+ const changesRegion = call.tool_name === "Write" ? writesRegion(file, input.content) : editsRegion(file, input);
68
+ if (MARKDOWN.test(rel) && changesRegion) {
60
69
  return deny(`Generated-file guard: the edit changes the generated region of ${rel}. ${rerun}`);
61
70
  }
62
71
  return null;
@@ -85,6 +85,16 @@ test("an edit whose old_string lies in or across a generated region is denied",
85
85
  assert.ok(reasonOf(decide({ ...edit(doc, ""), ...multi })));
86
86
  });
87
87
 
88
+ test("a Write of the whole doc that changes or drops its generated region is denied, and one that keeps it passes", (t) => {
89
+ const ws = workspace(t);
90
+ const doc = ws.at("docs/enforcement.md");
91
+ const writeOf = (content) => ({ ...write(doc), tool_input: { file_path: doc, content } });
92
+ assert.ok(reasonOf(decide(writeOf(ENFORCEMENT.replace("qc/comment-style", "qc/other")))));
93
+ assert.ok(reasonOf(decide(writeOf("# Enforcement\n"))));
94
+ assert.equal(decide(writeOf(ENFORCEMENT.replace("Hand-written intro.", "A new intro."))), null);
95
+ assert.equal(decide(writeOf(`${ENFORCEMENT}\n<!-- generated: more. pnpm codegen. -->\n<!-- /generated -->\n`)), null);
96
+ });
97
+
88
98
  test("an edit outside the generated region passes", (t) => {
89
99
  const ws = workspace(t);
90
100
  assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written judgement calls.")), null);
@@ -35,8 +35,8 @@ function workspace() {
35
35
  return { project, linked, plain, outside, pluginRoot: path.join(base, "plugin"), ranIn, cleanup: () => rmSync(base, { recursive: true, force: true }) };
36
36
  }
37
37
 
38
- function runHook(ws, file) {
39
- const featureFile = path.join(file, "features", "tasks", "index.ts");
38
+ function runHook(ws, file, featureDir = "features") {
39
+ const featureFile = path.join(file, featureDir, "tasks", "index.ts");
40
40
  mkdirSync(path.dirname(featureFile), { recursive: true });
41
41
  writeFileSync(featureFile, "export {};\n");
42
42
  return spawnSync("bash", [HOOK], {
@@ -74,6 +74,13 @@ test("a feature file in the session's own project is checked from the project",
74
74
  assert.deepEqual(ws.ranIn(), [ws.project]);
75
75
  });
76
76
 
77
+ test("a file under a layout with no features folder is checked too, since featureDir is the repository's own", (t) => {
78
+ const ws = workspace();
79
+ t.after(ws.cleanup);
80
+ assert.equal(runHook(ws, path.join(ws.project, "src"), "modules"), 2);
81
+ assert.deepEqual(ws.ranIn(), [ws.project]);
82
+ });
83
+
77
84
  test("a checkout with its own installed harness is checked by that copy, not the plugin's", (t) => {
78
85
  const ws = workspace();
79
86
  t.after(ws.cleanup);
@@ -46,17 +46,26 @@ export async function checkPullRequest(event, { gh = runGh, hasToken, ci = false
46
46
  notes: [],
47
47
  };
48
48
  }
49
- if (!hasToken) return { problems: [], notes: ["no GH_TOKEN, so the issues were not looked up"] };
49
+ // The CI template sets GH_TOKEN, so a CI run without one had it removed, and would pass unread.
50
+ if (!hasToken) {
51
+ return ci
52
+ ? { problems: ["no GH_TOKEN, so the issues cannot be looked up. Set GH_TOKEN for this step."], notes: [] }
53
+ : { problems: [], notes: ["no GH_TOKEN, so the issues were not looked up"] };
54
+ }
50
55
 
51
56
  const problems = [];
52
57
  const notes = [];
58
+ let unseen = 0;
53
59
  for (const { repo, number } of references) {
54
60
  const name = `${repo}#${number}`;
55
61
  const result = await gh(["issue", "view", String(number), "-R", repo, "--json", "createdAt"]);
56
62
  if (!result.ok) {
57
63
  const stderr = result.stderr ?? "";
58
64
  if (NO_ISSUE.test(stderr)) problems.push(`${name} does not exist. Open the issue, then reference it.`);
59
- else if (NO_REPOSITORY.test(stderr)) notes.push(`the token cannot see ${repo}, so ${name} was not looked up`);
65
+ else if (NO_REPOSITORY.test(stderr)) {
66
+ unseen++;
67
+ notes.push(`the token cannot see ${repo}, so ${name} was not looked up`);
68
+ }
60
69
  else if (ci && result.missing) problems.push(`gh is not installed, so ${name} cannot be checked`);
61
70
  else {
62
71
  const message = `could not reach GitHub for ${name}: ${stderr.trim().split("\n")[0]}`;
@@ -69,6 +78,10 @@ export async function checkPullRequest(event, { gh = runGh, hasToken, ci = false
69
78
  problems.push(`${name} was opened after the pull request. Register the work before it starts.`);
70
79
  }
71
80
  }
81
+ // A reference the token cannot read proves nothing, so a body of only those names no issue.
82
+ if (unseen === references.length) {
83
+ problems.push(`pull request #${pr.number} names only issues the token cannot see. Also name an issue in ${event.repository?.full_name}.`);
84
+ }
72
85
  return { problems, notes };
73
86
  }
74
87
 
@@ -74,19 +74,30 @@ test("in CI a failed call to GitHub fails and quotes the first stderr line", asy
74
74
  assert.deepEqual(result.notes, []);
75
75
  });
76
76
 
77
- test("in CI with no token the check is still a note", async () => {
77
+ test("in CI with no token the check fails and names GH_TOKEN", async () => {
78
78
  const result = await checkPullRequest(event("Fixes #12"), { gh: missingGh, hasToken: false, ci: true });
79
- assert.deepEqual(result.problems, []);
80
- assert.match(result.notes.join(), /no GH_TOKEN/);
79
+ assert.match(result.problems.join(), /no GH_TOKEN/);
81
80
  });
82
81
 
83
- test("in CI a repository the token cannot see is still a note", async () => {
84
- const gh = async () => ({ ok: false, stderr: "GraphQL: Could not resolve to a Repository with the name 'acme/private'. (repository)" });
85
- const result = await checkPullRequest(event("Refs acme/private#5"), { gh, hasToken: true, ci: true });
82
+ /** Knows acme/app#12, and cannot see acme/private at all. */
83
+ const ghWithPrivate = async (args) =>
84
+ args.includes("acme/private")
85
+ ? { ok: false, stderr: "GraphQL: Could not resolve to a Repository with the name 'acme/private'. (repository)" }
86
+ : ghKnowing({ "acme/app#12": "2026-05-01T00:00:00Z" })(args);
87
+
88
+ test("in CI a repository the token cannot see is a note beside an issue it can see", async () => {
89
+ const result = await checkPullRequest(event("Fixes #12. Refs acme/private#5"), { gh: ghWithPrivate, hasToken: true, ci: true });
86
90
  assert.deepEqual(result.problems, []);
87
91
  assert.match(result.notes.join(), /the token cannot see acme.private/);
88
92
  });
89
93
 
94
+ test("a body that names only issues the token cannot see fails, in CI and outside it", async () => {
95
+ for (const ci of [true, false]) {
96
+ const result = await checkPullRequest(event("Refs acme/private#5"), { gh: ghWithPrivate, hasToken: true, ci });
97
+ assert.match(result.problems.join(), /names only issues the token cannot see\. Also name an issue in acme\/app/);
98
+ }
99
+ });
100
+
90
101
  test("CI=false is not CI", () => {
91
102
  assert.equal(isCi({ CI: "true" }), true);
92
103
  assert.equal(isCi({ CI: "1" }), true);
@@ -97,9 +108,8 @@ test("CI=false is not CI", () => {
97
108
  });
98
109
 
99
110
  test("a repository the token cannot see is a note, never a missing issue", async () => {
100
- const gh = async () => ({ ok: false, stderr: "GraphQL: Could not resolve to a Repository with the name 'acme/private'. (repository)" });
101
- const result = await checkPullRequest(event("Refs acme/private#5"), { gh, hasToken: true });
102
- assert.deepEqual(result.problems, []);
111
+ const result = await checkPullRequest(event("Fixes #12. Refs acme/private#5"), { gh: ghWithPrivate, hasToken: true });
112
+ assert.doesNotMatch(result.problems.join(), /does not exist/);
103
113
  assert.match(result.notes.join(), /the token cannot see acme.private/);
104
114
  });
105
115
 
package/src/cli/qc.mjs CHANGED
@@ -64,8 +64,16 @@ async function main() {
64
64
  process.exit(await runStack(rest));
65
65
  }
66
66
  if (command === "screens") {
67
- const { runScreens } = await import("./screens.mjs");
68
- process.exit(await runScreens(rest));
67
+ // The screen packages are optional peers: only this command needs them, so a repository installs them for it.
68
+ try {
69
+ const { runScreens } = await import("./screens.mjs");
70
+ process.exit(await runScreens(rest));
71
+ } catch (error) {
72
+ const missing = /Cannot find package '(playwright|pixelmatch|pngjs)'/.exec(error?.message ?? "");
73
+ if (error?.code !== "ERR_MODULE_NOT_FOUND" || !missing) throw error;
74
+ console.error(`qc screens needs the ${missing[1]} package. Install the screen packages: pnpm add -D playwright pixelmatch pngjs`);
75
+ process.exit(2);
76
+ }
69
77
  }
70
78
  // A broken qc.config.json must not keep a lease in place, so the lease runs before the load.
71
79
  if (command === "lease") {
@@ -93,8 +101,9 @@ async function main() {
93
101
  case "check": {
94
102
  const { files, listed } = await checkFiles(rest);
95
103
  // An empty list means nothing staged to check, not the full check.
96
- if (listed && files.length === 0) return;
97
- const { problems, lines } = await runCheck(config, files);
104
+ const { problems, lines } = listed && files.length === 0
105
+ ? { problems: [], lines: [] }
106
+ : await runCheck(config, files);
98
107
  if (problems.length > 0) {
99
108
  for (const problem of problems) {
100
109
  console.error(`FAIL ${problem.feature ?? problem.path} ${problem.rule}: ${problem.detail}`);
@@ -103,6 +112,8 @@ async function main() {
103
112
  process.exit(1);
104
113
  }
105
114
  for (const line of lines) console.log(line);
115
+ const { runCheckCommands } = await import("./check-commands.mjs");
116
+ process.exitCode = await runCheckCommands(config);
106
117
  return;
107
118
  }
108
119
  case "init": {
@@ -253,7 +253,9 @@ export function gitCall(segment) {
253
253
  explicitDir = true;
254
254
  i++;
255
255
  } else if (/^--(git-dir|work-tree)=/.test(word)) explicitDir = true;
256
- else if (word === "-c") configs.push(words[++i]);
256
+ else if (word === "-c" || word === "--config-env") configs.push(words[++i]);
257
+ // `--config-env=name=VAR` sets `name` from a variable, so it is a `-c` whose value hides in the environment.
258
+ else if (word.startsWith("--config-env=")) configs.push(word.slice("--config-env=".length));
257
259
  else if (!word.startsWith("-")) return { sub: word, dirs, explicitDir, configs, args: words.slice(i + 1) };
258
260
  }
259
261
  return { sub: null, dirs, explicitDir, configs, args: [] };
@@ -441,6 +441,23 @@ test("a new commit makes the next stop run the full gate", (t) => {
441
441
  assert.equal(ws.ran().length, 2);
442
442
  });
443
443
 
444
+ test("a new installed harness on an unchanged checkout makes the next stop run the full gate", (t) => {
445
+ const ws = gitWorkspace(t);
446
+ ws.run();
447
+ writeFileSync(path.join(ws.repo, "node_modules", "architecture-harness", "package.json"), '{"version":"9.9.9"}');
448
+ ws.run();
449
+ assert.equal(ws.ran().length, 2);
450
+ ws.run();
451
+ assert.equal(ws.ran().length, 2);
452
+ });
453
+
454
+ test("a new extra stop step on an unchanged checkout makes the next stop run the full gate", (t) => {
455
+ const ws = gitWorkspace(t);
456
+ ws.run();
457
+ ws.run({}, { QC_STOP_EXTRA: "true" });
458
+ assert.equal(ws.ran().length, 2);
459
+ });
460
+
444
461
  test("a red first run stores nothing, so the next stop runs the full gate again", (t) => {
445
462
  const ws = gitWorkspace(t, { codes: { check: 1 }, withDoctor: false });
446
463
  assert.equal(ws.run().status, 2);
@@ -175,9 +175,9 @@ export async function run(root) {
175
175
  return decide(call, root);
176
176
  }
177
177
 
178
- /** The verdict on one Write or Edit call. @returns a deny payload, or null to allow it. */
178
+ /** The verdict on one Write, Edit, MultiEdit or NotebookEdit call. @returns a deny payload, or null to allow it. */
179
179
  export async function decide(call, root) {
180
- const file = call.tool_input?.file_path;
180
+ const file = call.tool_input?.file_path ?? call.tool_input?.notebook_path;
181
181
  if (!file) return null;
182
182
  const absolute = path.resolve(root, file);
183
183
  const rel = path.relative(root, absolute).split(path.sep).join("/");
package/src/config.mjs CHANGED
@@ -283,6 +283,15 @@ export const defaults = {
283
283
  required: { "pre-commit": ["qc work-order-check"], "commit-msg": ["qc commit-msg"], "pre-push": ["qc check"] },
284
284
  },
285
285
 
286
+ check: {
287
+ // The kit appends changed paths; for example, "pnpm exec vitest related --run". Null keeps this off.
288
+ related: null,
289
+ // Commands receive no extra arguments; for example, ["node script/check-comments.mjs --base origin/dev"].
290
+ commands: [],
291
+ // The merge base with this ref selects committed and staged changes.
292
+ base: "origin/main",
293
+ },
294
+
286
295
  // `conventional` runs commitlint's conventional rules, an optional peer dependency the repository
287
296
  // installs. `attribution` requires a Co-Authored-By trailer. The English rule always runs.
288
297
  commitMessage: { conventional: true, attribution: false },
@@ -631,6 +640,12 @@ export function load(root = process.cwd()) {
631
640
  const file = path.join(root, CONFIG_FILE);
632
641
  const user = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
633
642
  const config = merge(defaults, user);
643
+ if (!isPlainObject(config.check)) throw new TypeError("check must be an object");
644
+ const { related, commands, base } = config.check;
645
+ const command = (value) => typeof value === "string" && value.trim().length > 0;
646
+ if (related !== null && !command(related)) throw new TypeError("check.related must be a non-empty string or null");
647
+ if (!Array.isArray(commands) || !commands.every(command)) throw new TypeError("check.commands must be an array of non-empty strings");
648
+ if (!command(base)) throw new TypeError("check.base must be a non-empty string");
634
649
  config.root = root;
635
650
  return config;
636
651
  }
@@ -1,7 +1,8 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { readdirSync } from "node:fs";
3
+ import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { readFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
5
6
  import path from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { defaults, load, merge, requiredHooks } from "./config.mjs";
@@ -9,6 +10,37 @@ import { rules } from "./eslint/index.mjs";
9
10
 
10
11
  const here = path.dirname(fileURLToPath(import.meta.url));
11
12
 
13
+ test("check defaults leave repository commands off", () => {
14
+ assert.deepEqual(load(here).check, { related: null, commands: [], base: "origin/main" });
15
+ });
16
+
17
+ test("check configuration accepts commands and preserves omitted defaults", (t) => {
18
+ const root = mkdtempSync(path.join(tmpdir(), "qc-check-config-"));
19
+ t.after(() => rmSync(root, { recursive: true, force: true }));
20
+ const check = { related: "pnpm exec vitest related --run", commands: ["node script/check-comments.mjs --base origin/dev"] };
21
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check }));
22
+ assert.deepEqual(load(root).check, { ...check, base: "origin/main" });
23
+ });
24
+
25
+ test("check configuration rejects invalid types and empty commands or refs", (t) => {
26
+ const root = mkdtempSync(path.join(tmpdir(), "qc-check-config-"));
27
+ t.after(() => rmSync(root, { recursive: true, force: true }));
28
+ for (const check of [null, [], false, "command"]) {
29
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check }));
30
+ assert.throws(() => load(root), /check must be an object/);
31
+ }
32
+ for (const [key, values] of Object.entries({
33
+ related: [false, 1, [], {}, "", " "],
34
+ commands: [null, false, "node", [1], [null], [""], [" "]],
35
+ base: [null, false, 1, [], "", " "],
36
+ })) {
37
+ for (const value of values) {
38
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check: { [key]: value } }));
39
+ assert.throws(() => load(root), new RegExp(`check\\.${key}`));
40
+ }
41
+ }
42
+ });
43
+
12
44
  // A switch naming a rule that no longer exists silently stops switching anything.
13
45
  // This is the test that catches the next rename, not the last one.
14
46
  test("every lint rule has a switch, and every switch names a rule", () => {
@@ -3,6 +3,27 @@
3
3
  import { filenameOf, optionsOf, pathSuffix, schemaOf } from "../options.mjs";
4
4
 
5
5
  const DEFAULT_CLIENT = "platform/api-client.ts";
6
+ // The names of the global object, so `window.fetch` and `globalThis["fetch"]` are the same fetch.
7
+ const GLOBAL_OBJECTS = new Set(["window", "globalThis", "self", "global"]);
8
+
9
+ /** The property a member or a destructured key names, when the code spells it literally. */
10
+ function keyName(node, computed) {
11
+ if (!computed && node.type === "Identifier") return node.name;
12
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
13
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
14
+ return null;
15
+ }
16
+
17
+ /** True when the name resolves to no declaration in the code: an undeclared global, or one the config declares. */
18
+ function isGlobalName(sourceCode, identifier) {
19
+ for (let scope = sourceCode.getScope(identifier); scope; scope = scope.upper) {
20
+ const variable = scope.set.get(identifier.name);
21
+ if (variable) return variable.defs.length === 0;
22
+ }
23
+ return true;
24
+ }
25
+
26
+ const isGlobalObject = (sourceCode, node) => node?.type === "Identifier" && GLOBAL_OBJECTS.has(node.name) && isGlobalName(sourceCode, node);
6
27
 
7
28
  export default {
8
29
  meta: {
@@ -16,8 +37,27 @@ export default {
16
37
  if (pathSuffix(client).test(filenameOf(context))) return {};
17
38
  const report = (node) => context.report({ node, messageId: "raw", data: { client } });
18
39
  return {
19
- CallExpression(node) {
20
- if (node.callee.type === "Identifier" && node.callee.name === "fetch") report(node);
40
+ // Every use of the global fetch, not only a call: `const f = fetch` hands the same function on.
41
+ // A local binding named fetch is not the global, and a `typeof fetch` type reads no value.
42
+ // A global the config declares, as browser globals declare fetch, holds its references itself
43
+ // and leaves `through`, so both lists are read.
44
+ "Program:exit"() {
45
+ const { globalScope } = context.sourceCode.scopeManager;
46
+ const declared = globalScope.set.get("fetch");
47
+ const references = [...globalScope.through, ...(declared?.defs.length === 0 ? declared.references : [])];
48
+ for (const { identifier } of references) {
49
+ if (identifier.name !== "fetch" || identifier.parent?.type === "TSTypeQuery") continue;
50
+ report(identifier);
51
+ }
52
+ },
53
+ MemberExpression(node) {
54
+ if (isGlobalObject(context.sourceCode, node.object) && keyName(node.property, node.computed) === "fetch") report(node);
55
+ },
56
+ VariableDeclarator(node) {
57
+ if (node.id.type !== "ObjectPattern" || !isGlobalObject(context.sourceCode, node.init)) return;
58
+ for (const property of node.id.properties) {
59
+ if (property.type === "Property" && keyName(property.key, property.computed) === "fetch") report(property);
60
+ }
21
61
  },
22
62
  NewExpression(node) {
23
63
  if (node.callee.type === "Identifier" && node.callee.name === "URL") report(node);
@@ -103,10 +103,25 @@ tester.run("no-raw-fetch", rules["no-raw-fetch"], {
103
103
  valid: [
104
104
  { code: "await fetch(url);", filename: "/a/platform/api-client.ts" },
105
105
  { code: "await client.get(path);", filename: "/a/features/pins/index.ts" },
106
+ { code: "function load(fetch) { return fetch(url); }", filename: "/a/features/pins/index.ts" },
107
+ { code: "await client.fetch(url);", filename: "/a/features/pins/index.ts" },
108
+ { code: "const options = { fetch: true };", filename: "/a/features/pins/index.ts" },
109
+ { code: "const self = { fetch() {} }; self.fetch();", filename: "/a/features/pins/index.ts" },
110
+ { code: "function load(window) { return window.fetch(url); }", filename: "/a/features/pins/index.ts" },
106
111
  ],
107
112
  invalid: [
108
113
  { code: "await fetch(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
114
+ {
115
+ code: "await fetch(url); await window.fetch(url);",
116
+ filename: "/a/features/pins/index.ts",
117
+ languageOptions: { globals: { fetch: "readonly", window: "readonly" } },
118
+ errors: [{ messageId: "raw" }, { messageId: "raw" }],
119
+ },
109
120
  { code: "new URL(path);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
121
+ { code: "await window.fetch(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
122
+ { code: "await globalThis['fetch'](url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
123
+ { code: "const f = fetch; f(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
124
+ { code: "const { fetch: f } = globalThis;", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
110
125
  ],
111
126
  });
112
127
 
@@ -14,18 +14,32 @@ const DEFAULT_TABLE = "audit_log";
14
14
  */
15
15
  export function checkAuditAppendOnly(resources, options = {}) {
16
16
  const table = options.table ?? DEFAULT_TABLE;
17
- const name = escape(table);
18
- // The table in a mutating position. An insert naming it is the whole point.
19
- const mutation = new RegExp(`\\b(?:update\\s+${name}\\b|delete\\s+from\\s+${name}\\b|truncate\\s+(?:table\\s+)?${name}\\b)`, "i");
17
+ // The table as SQL can name it: quoted or not, under a schema or not, after `only` or not.
18
+ const name = table.split(".").map((part) => `"?${escape(part)}"?`).join("\\s*\\.\\s*");
19
+ const ref = `(?:only\\s+)?(?:(?:"[^"]+"|\\w+)\\s*\\.\\s*)?${name}(?![\\w$"])`;
20
+ // The table in a mutating position. An insert naming it is the whole point, but an upsert rewrites a row.
21
+ const mutation = new RegExp(
22
+ [
23
+ `update\\s+${ref}`,
24
+ `delete\\s+from\\s+${ref}`,
25
+ `truncate\\s+(?:table\\s+)?(?:only\\s+)?(?:[\\w."]+\\s*,\\s*)*${ref}`,
26
+ `merge\\s+into\\s+${ref}`,
27
+ `insert\\s+into\\s+${ref}[^;]*?\\bon\\s+conflict\\b[^;]*?\\bdo\\s+update\\b`,
28
+ ]
29
+ .map((form) => `\\b${form}`)
30
+ .join("|"),
31
+ "i",
32
+ );
20
33
  const problems = [];
21
34
  for (const { path, statements } of resources) {
22
35
  for (const { sql } of statements) {
23
36
  const found = mutation.exec(sql);
24
37
  if (found !== null) {
38
+ const quoted = found[0].replace(/\s+/g, " ").trim();
25
39
  problems.push({
26
40
  path,
27
41
  rule: "audit-mutated",
28
- detail: `'${found[0].trim()}' — ${table} is append-only, so no repository may hold an update or delete path for it`,
42
+ detail: `'${quoted.length > 60 ? `${quoted.slice(0, 57)}...` : quoted}' — ${table} is append-only, so no repository may hold an update or delete path for it`,
29
43
  });
30
44
  }
31
45
  }
@@ -28,6 +28,25 @@ test("a truncate fails", () => {
28
28
 
29
29
  test("another table of a similar name is not the audit log", () => {
30
30
  assert.deepEqual(checkAuditAppendOnly(resource("delete from audit_log_archive where id = $1")), []);
31
+ assert.deepEqual(checkAuditAppendOnly(resource('update "audit_logs" set actor = $1')), []);
32
+ });
33
+
34
+ test("a quoted, schema-qualified or only name, a list truncate, a merge and an upsert fail", () => {
35
+ for (const sql of [
36
+ "update public.audit_log set actor = $1",
37
+ 'delete from "audit_log" where id = $1',
38
+ 'update "public"."audit_log" set actor = $1',
39
+ "update only audit_log set actor = $1",
40
+ "truncate sessions, audit_log",
41
+ "merge into audit_log using x on true when matched then update set actor = x.actor",
42
+ "insert into audit_log (id, actor) values ($1, $2) on conflict (id) do update set actor = excluded.actor",
43
+ ]) {
44
+ assert.equal(checkAuditAppendOnly(resource(sql)).length, 1, sql);
45
+ }
46
+ });
47
+
48
+ test("an insert that does nothing on conflict changes no row, and passes", () => {
49
+ assert.deepEqual(checkAuditAppendOnly(resource("insert into audit_log (id) values ($1) on conflict (id) do nothing")), []);
31
50
  });
32
51
 
33
52
  test("the table name comes from options", () => {