@maniumek/suwgate 0.3.0 → 0.5.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 (53) hide show
  1. package/README.md +112 -20
  2. package/dist/cli.js +38 -3
  3. package/dist/dev/db.d.ts +1 -1
  4. package/dist/dev/db.js +25 -0
  5. package/dist/dev/logs.js +9 -1
  6. package/dist/dev/settings.d.ts +2 -0
  7. package/dist/dev/settings.js +5 -2
  8. package/dist/eslint/index.js +4 -1
  9. package/dist/gate/check.d.ts +10 -0
  10. package/dist/gate/check.js +91 -19
  11. package/dist/gate/config.d.ts +12 -0
  12. package/dist/gate/config.js +87 -2
  13. package/dist/gate/contract.d.ts +6 -0
  14. package/dist/gate/guardsStep.d.ts +3 -1
  15. package/dist/gate/guardsStep.js +14 -3
  16. package/dist/gate/plan.d.ts +20 -1
  17. package/dist/gate/plan.js +89 -22
  18. package/dist/gate/report.d.ts +1 -0
  19. package/dist/gate/report.js +12 -3
  20. package/dist/gate/repository.d.ts +1 -0
  21. package/dist/gate/repository.js +8 -0
  22. package/dist/gate/runner.js +18 -3
  23. package/dist/guards/comments/hash.js +22 -1
  24. package/dist/guards/dotnet/appsettingsBound.js +29 -2
  25. package/dist/guards/repository/humanDocs.d.ts +2 -0
  26. package/dist/guards/repository/humanDocs.js +87 -0
  27. package/dist/guards/repository/imagePins.js +1 -1
  28. package/dist/guards/repository/index.js +4 -0
  29. package/dist/guards/repository/justModules.d.ts +1 -0
  30. package/dist/guards/repository/justModules.js +29 -11
  31. package/dist/guards/repository/noRawColors.js +1 -1
  32. package/dist/guards/repository/scriptsCalled.js +38 -11
  33. package/dist/guards/repository/testTiming.d.ts +2 -0
  34. package/dist/guards/repository/testTiming.js +198 -0
  35. package/dist/profiles/contract.js +81 -38
  36. package/dist/profiles/criteriaRan.d.ts +1 -0
  37. package/dist/profiles/criteriaRan.js +44 -1
  38. package/dist/profiles/database.js +11 -4
  39. package/dist/profiles/dotnet.d.ts +1 -0
  40. package/dist/profiles/dotnet.js +28 -5
  41. package/dist/profiles/dotnetGuards.js +17 -1
  42. package/dist/profiles/library.js +4 -1
  43. package/dist/profiles/node.js +1 -0
  44. package/dist/profiles/presets/knip.d.ts +1 -0
  45. package/dist/profiles/presets/knip.js +4 -2
  46. package/dist/profiles/presets/playwright.d.ts +3 -1
  47. package/dist/profiles/presets/playwright.js +7 -1
  48. package/dist/profiles/shell.d.ts +3 -1
  49. package/dist/profiles/shell.js +22 -7
  50. package/dist/profiles/verdict.js +6 -2
  51. package/dist/profiles/web.js +24 -5
  52. package/package.json +1 -1
  53. package/schema/suwgate.schema.json +62 -3
@@ -0,0 +1,87 @@
1
+ import { moduleName } from "./justModules.js";
2
+ import { baseName, inProfileDirectory, numberedLines } from "./text.js";
3
+ const AGENT_SCRIPT = /(^|\/)\.internal\/|^[^/]+\.Gate\/scripts\//;
4
+ const AGENT_PATH = /\.internal\/|\.Gate\/scripts\//;
5
+ const FENCE = /^\s*(```|~~~)\s*([\w-]*)/;
6
+ const SHELL_FENCE = new Set(["", "sh", "bash", "zsh", "shell", "console", "shell-session", "powershell", "pwsh", "ps1", "cmd"]);
7
+ const CODE_SPAN = /(`+)(.+?)\1/g;
8
+ const DESCRIBED = /(\(|\b(runs|calls|starts|through|via)\s+)$/;
9
+ const VARIABLE = /^(?:export\s+)?([A-Za-z_][\w-]*)\s*:=/;
10
+ const RECIPE = /^@?([A-Za-z_][\w-]*)(?:\s[^:]*)?:(?!=)/;
11
+ function documentsOf(context) {
12
+ const folders = context.profiles.flatMap((profile) => context.directories[profile] === undefined ? [] : [inProfileDirectory(context.directories, profile, "README.md")]);
13
+ return [...new Set(["README.md", "docs/development.md", ...folders])].filter((file) => context.files.includes(file));
14
+ }
15
+ function commandsOf(text) {
16
+ const commands = [];
17
+ let fence;
18
+ for (const { line, text: content } of numberedLines(text)) {
19
+ const marker = FENCE.exec(content);
20
+ if (marker !== null) {
21
+ fence = fence === undefined ? (marker[2] ?? "") : undefined;
22
+ }
23
+ else if (fence !== undefined) {
24
+ if (SHELL_FENCE.has(fence) && content.trim() !== "")
25
+ commands.push({ line, text: content.trim() });
26
+ }
27
+ else {
28
+ for (const span of content.matchAll(CODE_SPAN)) {
29
+ const code = (span[2] ?? "").trim();
30
+ if (/\s/.test(code) && !DESCRIBED.test(content.slice(0, span.index)))
31
+ commands.push({ line, text: code });
32
+ }
33
+ }
34
+ }
35
+ return commands;
36
+ }
37
+ function scriptIn(command, agentNames) {
38
+ return command
39
+ .split(/\s+/)
40
+ .map((token) => token.replace(/^["'(]+|["'),;]+$/g, "").replace(/^\.\//, ""))
41
+ .find((token) => AGENT_PATH.test(token) || agentNames.has(token));
42
+ }
43
+ function recipesCalling(context, script) {
44
+ const name = baseName(script);
45
+ return context.files
46
+ .filter((file) => file === "justfile" || file.endsWith(".just"))
47
+ .flatMap((file) => {
48
+ const prefix = file === "justfile" ? "" : `${moduleName(file)} `;
49
+ const lines = numberedLines(context.read(file)).map((line) => line.text);
50
+ const variables = lines.flatMap((text) => {
51
+ const variable = VARIABLE.exec(text);
52
+ return variable?.[1] !== undefined && text.includes(name) ? [variable[1]] : [];
53
+ });
54
+ const calls = (text) => text.includes(name) || variables.some((variable) => new RegExp(`\\{\\{\\s*${variable}\\s*\\}\\}`).test(text));
55
+ let recipe;
56
+ const found = [];
57
+ for (const text of lines) {
58
+ const header = /^\s/.test(text) ? null : RECIPE.exec(text);
59
+ if (header !== null)
60
+ recipe = header[1];
61
+ else if (!/^\s/.test(text) && text.trim() !== "")
62
+ recipe = undefined;
63
+ else if (recipe !== undefined && calls(text))
64
+ found.push(`just ${prefix}${recipe}`);
65
+ }
66
+ return found;
67
+ })
68
+ .filter((recipe, index, all) => all.indexOf(recipe) === index);
69
+ }
70
+ function message(context, script) {
71
+ const recipes = recipesCalling(context, script);
72
+ return recipes.length === 0
73
+ ? `a person runs a just recipe, never ${script}, a script for agents: add a recipe that calls it to the justfile and name the recipe here (a doc may still name it to explain what runs it: in parentheses or after runs, calls or starts)`
74
+ : `a person runs a just recipe, never ${script}, a script for agents: name \`${recipes.join("` or `")}\` instead (a doc may still name it to explain what runs it: in parentheses or after runs, calls or starts)`;
75
+ }
76
+ export const humanDocs = {
77
+ id: "human-docs",
78
+ description: "The docs for people (README.md, docs/development.md and the README of a profile's directory) never tell a person to run a script meant for agents (scripts/.internal/, <name>.Gate/scripts/): people run just recipes",
79
+ profiles: "every",
80
+ check(context) {
81
+ const agentNames = new Set(context.files.filter((file) => AGENT_SCRIPT.test(file)).map(baseName));
82
+ return documentsOf(context).flatMap((document) => commandsOf(context.read(document)).flatMap(({ line, text }) => {
83
+ const script = scriptIn(text, agentNames);
84
+ return script === undefined ? [] : [{ target: document, line, message: message(context, script) }];
85
+ }));
86
+ },
87
+ };
@@ -44,7 +44,7 @@ export const imagePins = {
44
44
  check(context) {
45
45
  const found = context.files.flatMap((file) => isDockerfile(baseName(file)) || /\.(ya?ml|sh)$/.test(file) ? references(file, context.read(file)) : []);
46
46
  const unpinned = found
47
- .filter(({ image }) => !image.includes("$") && !isPinned(image))
47
+ .filter(({ image }) => !image.includes("$") && !image.includes("{{") && !isPinned(image))
48
48
  .map(({ file, line, image }) => ({
49
49
  target: file,
50
50
  line,
@@ -6,6 +6,7 @@ import { dependencyDirection } from "./dependencyDirection.js";
6
6
  import { docsPaths } from "./docsPaths.js";
7
7
  import { forbiddenNames } from "./forbiddenNames.js";
8
8
  import { hooks } from "./hooks.js";
9
+ import { humanDocs } from "./humanDocs.js";
9
10
  import { imagePins } from "./imagePins.js";
10
11
  import { justModules } from "./justModules.js";
11
12
  import { noRawColors } from "./noRawColors.js";
@@ -14,6 +15,7 @@ import { requiredFiles } from "./requiredFiles.js";
14
15
  import { scriptsCalled } from "./scriptsCalled.js";
15
16
  import { scriptsHelp } from "./scriptsHelp.js";
16
17
  import { suwfrontkitWiring } from "./suwfrontkitWiring.js";
18
+ import { testTiming } from "./testTiming.js";
17
19
  import { vsCodeSettings } from "./vsCodeSettings.js";
18
20
  export const repositoryGuards = [
19
21
  requiredFiles,
@@ -33,4 +35,6 @@ export const repositoryGuards = [
33
35
  dependencyDirection,
34
36
  hooks,
35
37
  suwfrontkitWiring,
38
+ testTiming,
39
+ humanDocs,
36
40
  ];
@@ -1,2 +1,3 @@
1
1
  import type { Guard } from "../../gate/contract.ts";
2
+ export declare function moduleName(file: string): string;
2
3
  export declare const justModules: Guard;
@@ -1,31 +1,49 @@
1
1
  import { baseName } from "./text.js";
2
- const MOD_LINE = /^mod\??\s+([\w-]+)\s*$/gm;
3
- function moduleName(file) {
2
+ const MOD_LINE = /^mod\??\s+([\w-]+)(?:\s+(['"])([^'"]+)\2)?\s*$/gm;
3
+ const SOURCES_IN_A_FOLDER = ["mod.just", "justfile", ".justfile"];
4
+ export function moduleName(file) {
4
5
  return file.endsWith("/mod.just") ? (file.split("/")[0] ?? "") : baseName(file).replace(/\.just$/, "");
5
6
  }
7
+ function normalized(file) {
8
+ return file.replace(/^\.\//, "").replace(/\/+$/, "");
9
+ }
10
+ function sourceOf(mod, files) {
11
+ if (mod.path === undefined)
12
+ return files.find((file) => file === `${mod.name}.just` || file === `${mod.name}/mod.just`);
13
+ const path = normalized(mod.path);
14
+ return files.includes(path) ? path : SOURCES_IN_A_FOLDER.map((name) => `${path}/${name}`).find((file) => files.includes(file));
15
+ }
6
16
  export const justModules = {
7
17
  id: "just-modules",
8
- description: "Every just module is <name>.just beside the justfile or <folder>/mod.just, and the justfile names each one with mod <name>",
18
+ description: "Every just module is <name>.just beside the justfile, <folder>/mod.just, or the file a mod line names by its path (mod <name> '<path>'), and the justfile names each one",
9
19
  profiles: "every",
10
20
  check(context) {
11
21
  const modules = context.files.filter((file) => file.endsWith(".just"));
12
- const named = context.files.includes("justfile")
13
- ? [...context.read("justfile").matchAll(MOD_LINE)].map((match) => match[1] ?? "")
22
+ const mods = context.files.includes("justfile")
23
+ ? [...context.read("justfile").matchAll(MOD_LINE)].map((match) => ({
24
+ name: match[1] ?? "",
25
+ ...(match[3] === undefined ? {} : { path: match[3] }),
26
+ }))
14
27
  : [];
28
+ const byPath = mods.filter((mod) => mod.path !== undefined).flatMap((mod) => sourceOf(mod, context.files) ?? []);
29
+ const named = mods.filter((mod) => mod.path === undefined).map((mod) => mod.name);
15
30
  const misplaced = modules
31
+ .filter((file) => !byPath.includes(file))
16
32
  .filter((file) => file.includes("/") && (baseName(file) !== "mod.just" || file.split("/").length !== 2))
17
33
  .map((file) => ({
18
34
  target: file,
19
- message: "just finds a module only as <name>.just beside the justfile or as <folder>/mod.just: move it there",
35
+ message: "just finds a module by its name only as <name>.just beside the justfile or as <folder>/mod.just: move it there, or name its path in the mod line (mod <name> '<path>')",
20
36
  }));
21
- const missing = named
22
- .filter((name) => !modules.includes(`${name}.just`) && !modules.includes(`${name}/mod.just`))
23
- .map((name) => ({
37
+ const missing = mods
38
+ .filter((mod) => sourceOf(mod, context.files) === undefined)
39
+ .map((mod) => ({
24
40
  target: "justfile",
25
- message: `mod ${name} has no ${name}.just or ${name}/mod.just: add the module, or delete the mod line`,
41
+ message: mod.path === undefined
42
+ ? `mod ${mod.name} has no ${mod.name}.just or ${mod.name}/mod.just: add the module, or delete the mod line`
43
+ : `mod ${mod.name} names ${mod.path}, which is not a module file here: fix the path, or delete the mod line`,
26
44
  }));
27
45
  const orphans = modules
28
- .filter((file) => !named.includes(moduleName(file)))
46
+ .filter((file) => !byPath.includes(file) && !named.includes(moduleName(file)))
29
47
  .filter((file) => !misplaced.some((finding) => finding.target === file))
30
48
  .map((file) => ({
31
49
  target: file,
@@ -1,5 +1,5 @@
1
1
  import { inProfileDirectory, numberedLines, stringList } from "./text.js";
2
- const RAW_COLOR = /#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab)\(|\[#/;
2
+ const RAW_COLOR = /(?<!&)#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab)\(|\[#/;
3
3
  const CODE_FILE = /\.(ts|tsx|js|jsx)$/;
4
4
  const TEST_FILE = /\.(test|spec|e2e)\.(ts|tsx|js|jsx)$/;
5
5
  export const noRawColors = {
@@ -1,12 +1,7 @@
1
- import { baseName } from "./text.js";
2
- const CALLER_FILES = new Set([
3
- "justfile",
4
- "package.json",
5
- "suwgate.yml",
6
- ".claude/settings.json",
7
- ".vscode/tasks.json",
8
- ".template.config/template.json",
9
- ]);
1
+ import { parse } from "yaml";
2
+ import { baseName, isRecord } from "./text.js";
3
+ const CONFIG_FILE = "suwgate.yml";
4
+ const CALLER_FILES = new Set(["justfile", "package.json", ".claude/settings.json", ".vscode/tasks.json", ".template.config/template.json"]);
10
5
  export function isScript(file) {
11
6
  return file.endsWith(".sh") || /(^|\/)scripts\/(.+\/)?[^/]+\.(ts|js|mjs|py|ps1)$/.test(file);
12
7
  }
@@ -18,16 +13,48 @@ function isCaller(file) {
18
13
  /\.(sh|just|csproj|proj|props|targets)$/.test(name) ||
19
14
  /^Dockerfile|\.Dockerfile$/.test(name) ||
20
15
  /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/.test(name) ||
16
+ file === "hooks/hooks.json" ||
17
+ file.endsWith("/hooks/hooks.json") ||
21
18
  file.startsWith(".githooks/") ||
22
19
  file.startsWith(".github/workflows/") ||
23
20
  file.startsWith(".github/actions/"));
24
21
  }
22
+ function strings(value) {
23
+ if (typeof value === "string")
24
+ return [value];
25
+ if (Array.isArray(value))
26
+ return value.flatMap(strings);
27
+ return isRecord(value) ? Object.values(value).flatMap(strings) : [];
28
+ }
29
+ function commandsOfConfig(context) {
30
+ let parsed;
31
+ try {
32
+ parsed = parse(context.read(CONFIG_FILE));
33
+ }
34
+ catch {
35
+ return "";
36
+ }
37
+ if (!isRecord(parsed))
38
+ return "";
39
+ const steps = isRecord(parsed["steps"]) ? parsed["steps"] : {};
40
+ const added = Array.isArray(steps["add"]) ? steps["add"] : [];
41
+ return [
42
+ ...added.flatMap((step) => (isRecord(step) ? strings(step["run"]) : [])),
43
+ ...strings(steps["configure"]),
44
+ ...strings(parsed["env"]),
45
+ ...strings(parsed["dev"]),
46
+ ].join("\n");
47
+ }
48
+ function callersOf(context) {
49
+ const callers = context.files.filter(isCaller).map((file) => ({ file, text: context.read(file) }));
50
+ return context.files.includes(CONFIG_FILE) ? [...callers, { file: CONFIG_FILE, text: commandsOfConfig(context) }] : callers;
51
+ }
25
52
  export const scriptsCalled = {
26
53
  id: "scripts-called",
27
- description: "Every script (*.sh, and the files of a scripts/ folder) is called by a recipe, another script, a hook, the workflow or suwgate.yml",
54
+ description: "Every script (*.sh, and the files of a scripts/ folder) is called by a recipe, another script, a hook (also a Claude Code plugin's hooks/hooks.json), the workflow or a command of suwgate.yml (steps.add run, steps.configure, env, dev)",
28
55
  profiles: "every",
29
56
  check(context) {
30
- const callers = context.files.filter(isCaller).map((file) => ({ file, text: context.read(file) }));
57
+ const callers = callersOf(context);
31
58
  return context.files
32
59
  .filter(isScript)
33
60
  .filter((script) => !callers.some((caller) => caller.file !== script && caller.text.includes(baseName(script))))
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const testTiming: Guard;
@@ -0,0 +1,198 @@
1
+ import { lineAt, numberedLines } from "./text.js";
2
+ const FIX = "a test never measures, waits on or limits real time, so it neither flakes on a slow machine nor promises speed: to prove a retry or a timeout, give the code a TimeProvider and advance a FakeTimeProvider (in Vitest, vi.useFakeTimers() and vi.advanceTimersByTime()); to see that something happened, await the event (a task, a signal, Playwright's auto-waiting expect, a later event that must come after it); a speed promise, in milliseconds or in steps counted instead of them, does not belong on the gate, so drop it and its criterion";
3
+ const CSHARP_TEST = /(^|\/)[^/]+\.Test(s|ing)\/.+\.cs$/;
4
+ const WEB_TEST = /\.(test|spec|e2e|visual|stories)\.[cm]?[jt]sx?$/;
5
+ const E2E_HELPER = /(^|\/)e2e\/.+\.[cm]?[jt]sx?$/;
6
+ const TOOL_CONFIG = /\.config\.[cm]?[jt]s$/;
7
+ const VITEST_TEST = /\.test\.[cm]?[jt]sx?$/;
8
+ const FAKE_TIMERS = /\buseFakeTimers\s*\(/;
9
+ const MEASURES = "measures real time";
10
+ const READS_CLOCK = "reads the real clock";
11
+ const WAITS = "waits on real time";
12
+ const LIMITS = "limits the test in real time";
13
+ const CSHARP_RULES = [
14
+ { pattern: /\b(?<found>Stopwatch|GetElapsedTime|GetTimestamp|TickCount64|TickCount)\b/dg, verb: MEASURES },
15
+ { pattern: /\b(?<found>(DateTime|DateTimeOffset)\.(Now|UtcNow|Today))\b/dg, verb: READS_CLOCK },
16
+ { pattern: /\b(?<found>Thread\.Sleep)\b/dg, verb: "sleeps on real time" },
17
+ { pattern: /\[[^[\]]*?\b(?<found>Timeout\s*=)(?!=)/dg, verb: LIMITS },
18
+ ];
19
+ const onFakeClock = (call) => call.args.slice(1).some((arg) => /provider|clock/i.test(arg));
20
+ const CSHARP_CALLS = [
21
+ {
22
+ pattern: /\bTask\.Delay\s*\(/g,
23
+ verb: `${WAITS} outside a polling loop`,
24
+ allowed: (call) => onFakeClock(call) || /^Timeout\.Infinite(TimeSpan)?$/.test(call.args[0] ?? "") || insideLoop(call.text, call.at),
25
+ },
26
+ ];
27
+ const WEB_RULES = [
28
+ { name: "performance.now", pattern: /\bperformance\.now\b/, verb: MEASURES, faked: true },
29
+ { name: "Date.now()", pattern: /\bDate\.now\(\)\s*-|-\s*Date\.now\(\)/, verb: MEASURES, faked: true },
30
+ { name: "setTimeout", pattern: /\bsetTimeout\s*\(/, verb: "waits on or limits real time", faked: true },
31
+ { name: "sleep or delay", pattern: /\b(sleep|delay)\(\s*\d/, verb: WAITS, faked: true },
32
+ { name: "waitForTimeout", pattern: /\bwaitForTimeout\b/, verb: WAITS },
33
+ { name: "interruptAfterTimeLimit", pattern: /\binterruptAfterTimeLimit\b/, verb: LIMITS },
34
+ { name: "timeout:", pattern: /\btimeout\s*:\s*[1-9]/, verb: LIMITS, vitestOnly: true },
35
+ ];
36
+ function blank(text) {
37
+ return text.replace(/[^\n]/g, " ");
38
+ }
39
+ function quoteRun(text, at) {
40
+ let end = at;
41
+ while (text[end] === '"')
42
+ end++;
43
+ return end - at;
44
+ }
45
+ function literalEnd(text, at) {
46
+ const quotes = quoteRun(text, at);
47
+ if (quotes >= 3) {
48
+ let end = at + quotes;
49
+ while (end < text.length && !(text[end] === '"' && quoteRun(text, end) >= quotes))
50
+ end++;
51
+ return Math.min(text.length, end + quotes);
52
+ }
53
+ if (quotes === 2)
54
+ return at + 2;
55
+ const verbatim = /@\$?$|\$@$/.test(text.slice(Math.max(0, at - 2), at));
56
+ let end = at + 1;
57
+ while (end < text.length) {
58
+ const sign = text[end];
59
+ if (sign === "\\" && !verbatim)
60
+ end += 2;
61
+ else if (sign === '"' && verbatim && text[end + 1] === '"')
62
+ end += 2;
63
+ else if (sign === '"' || (sign === "\n" && !verbatim))
64
+ return end + 1;
65
+ else
66
+ end++;
67
+ }
68
+ return text.length;
69
+ }
70
+ function charEnd(text, at) {
71
+ const close = text.indexOf("'", text[at + 1] === "\\" ? at + 3 : at + 2);
72
+ return close === -1 || close - at > 10 ? at + 1 : close + 1;
73
+ }
74
+ function endOfSkipped(text, at) {
75
+ const sign = text.charAt(at);
76
+ const next = text.charAt(at + 1);
77
+ if (sign === "/" && next === "/")
78
+ return text.includes("\n", at) ? text.indexOf("\n", at) : text.length;
79
+ if (sign === "/" && next === "*")
80
+ return text.includes("*/", at + 2) ? text.indexOf("*/", at + 2) + 2 : text.length;
81
+ if (sign === '"')
82
+ return literalEnd(text, at);
83
+ return sign === "'" ? charEnd(text, at) : undefined;
84
+ }
85
+ function codeOnly(text) {
86
+ let kept = "";
87
+ let at = 0;
88
+ while (at < text.length) {
89
+ const end = endOfSkipped(text, at);
90
+ kept += end === undefined ? text.charAt(at) : blank(text.slice(at, end));
91
+ at = end ?? at + 1;
92
+ }
93
+ return kept;
94
+ }
95
+ function matchingBackwards(text, close, open, closing) {
96
+ let depth = 0;
97
+ for (let at = close; at >= 0; at--) {
98
+ if (text[at] === closing)
99
+ depth++;
100
+ else if (text[at] === open && --depth === 0)
101
+ return at;
102
+ }
103
+ return -1;
104
+ }
105
+ function isLoopHeader(header, text, end) {
106
+ if (/\bdo$/.test(header))
107
+ return true;
108
+ if (!header.endsWith(")"))
109
+ return false;
110
+ const open = matchingBackwards(text, end, "(", ")");
111
+ return open > 0 && /\b(while|for|foreach)\s*$/.test(text.slice(0, open));
112
+ }
113
+ function statementStart(text, at) {
114
+ let depth = 0;
115
+ for (let position = at - 1; position >= 0; position--) {
116
+ const sign = text.charAt(position);
117
+ if (sign === ")")
118
+ depth++;
119
+ else if (sign === "(")
120
+ depth--;
121
+ else if (depth === 0 && (sign === ";" || sign === "{" || sign === "}"))
122
+ return position + 1;
123
+ }
124
+ return 0;
125
+ }
126
+ function insideLoop(text, at) {
127
+ if (/^\s*(while|for|foreach)\s*\(/.test(text.slice(statementStart(text, at), at)))
128
+ return true;
129
+ let depth = 0;
130
+ for (let position = at - 1; position >= 0; position--) {
131
+ if (text[position] === "}")
132
+ depth++;
133
+ else if (text[position] === "{" && depth > 0)
134
+ depth--;
135
+ else if (text[position] === "{") {
136
+ const header = text.slice(0, position).trimEnd();
137
+ if (isLoopHeader(header, text, header.length - 1))
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ function argumentsOf(text, open) {
144
+ const args = [];
145
+ let depth = 0;
146
+ let start = open + 1;
147
+ for (let at = open; at < text.length; at++) {
148
+ const sign = text[at];
149
+ if (sign === "(" || sign === "[" || sign === "{")
150
+ depth++;
151
+ else if (sign === ")" || sign === "]" || sign === "}")
152
+ depth--;
153
+ if ((depth === 1 && sign === ",") || depth === 0) {
154
+ args.push(text.slice(start, at).trim());
155
+ start = at + 1;
156
+ }
157
+ if (depth === 0)
158
+ break;
159
+ }
160
+ return args.filter((arg) => arg !== "");
161
+ }
162
+ function finding(file, line, found, verb) {
163
+ return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${FIX}` };
164
+ }
165
+ function csharpFindings(file, source) {
166
+ const text = codeOnly(source);
167
+ const plain = CSHARP_RULES.flatMap((rule) => [...text.matchAll(rule.pattern)].flatMap((match) => {
168
+ const found = match.indices?.groups?.["found"];
169
+ return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb)];
170
+ }));
171
+ const calls = CSHARP_CALLS.flatMap((rule) => [...text.matchAll(rule.pattern)]
172
+ .filter((match) => !rule.allowed({ text, at: match.index, args: argumentsOf(text, match.index + match[0].length - 1) }))
173
+ .map((match) => finding(file, lineAt(text, match.index), match[0].replace(/^\.|\s*\($/g, ""), rule.verb)));
174
+ return [...plain, ...calls].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
175
+ }
176
+ function webFindings(file, source) {
177
+ const faked = FAKE_TIMERS.test(source);
178
+ const rules = WEB_RULES.filter((rule) => !(faked && rule.faked) && (VITEST_TEST.test(file) || rule.vitestOnly !== true));
179
+ return numberedLines(source).flatMap(({ line, text }) => rules.flatMap((rule) => {
180
+ const match = rule.pattern.exec(text);
181
+ return match === null ? [] : [finding(file, line, rule.name, rule.verb)];
182
+ }));
183
+ }
184
+ function isWebTest(file) {
185
+ return !file.includes("node_modules/") && !TOOL_CONFIG.test(file) && (WEB_TEST.test(file) || E2E_HELPER.test(file));
186
+ }
187
+ export const testTiming = {
188
+ id: "test-timing",
189
+ description: "No test measures, sleeps on, waits for or limits real time (the .cs files of *.Tests and *.Testing projects; *.test, *.spec, *.e2e, *.visual and *.stories files and e2e/ helpers): tests drive a fake clock",
190
+ profiles: ["dotnet", "web", "library"],
191
+ check(context) {
192
+ return context.files.flatMap((file) => {
193
+ if (CSHARP_TEST.test(file))
194
+ return csharpFindings(file, context.read(file));
195
+ return isWebTest(file) ? webFindings(file, context.read(file)) : [];
196
+ });
197
+ },
198
+ };
@@ -2,9 +2,36 @@ import { existsSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { DOTNET_TEST, NO_IDLE_BUILD_PROCESSES } from "./dotnet.js";
4
4
  import { PNPM_INSTALL } from "./node.js";
5
- import { has, quoted, read, script, tracked } from "./shell.js";
6
- const CONTRACT = "contract/openapi.json";
7
- const CONTRACT_VERSION = "contract/package.json";
5
+ import { has, quoted, read, script, settingsOf, tracked } from "./shell.js";
6
+ const DEFAULT_CONTRACT = "contract/openapi.json";
7
+ const API_VERSION_STEP = "api-version";
8
+ const CONTRACT_SETTINGS = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ properties: {
12
+ contract: {
13
+ description: "Where the API contract is, relative to the dotnet directory (default contract/openapi.json); api-version compares the same file, and reads its version from the package.json beside it.",
14
+ type: "string",
15
+ pattern: "^[A-Za-z0-9._-][A-Za-z0-9._/-]*\\.json$",
16
+ },
17
+ },
18
+ };
19
+ const VERSION_SETTINGS = {
20
+ type: "object",
21
+ additionalProperties: false,
22
+ properties: {
23
+ breaking: {
24
+ description: "major (default): a breaking change of the contract needs a new major version in the package.json beside it; never: every breaking change fails, whatever the version.",
25
+ enum: ["major", "never"],
26
+ },
27
+ },
28
+ };
29
+ function contractOf(context) {
30
+ return settingsOf(context, API_CONTRACT).contract ?? DEFAULT_CONTRACT;
31
+ }
32
+ function versionFileOf(contract) {
33
+ return path.posix.join(path.posix.dirname(contract), "package.json");
34
+ }
8
35
  export const API_TYPES = "src/api/openapi.d.ts";
9
36
  export const API_CONTRACT = "api-contract";
10
37
  const GENERATOR = "Microsoft.Extensions.ApiDescription.Server";
@@ -22,14 +49,15 @@ function webApp(context) {
22
49
  return existsSync(path.join(directory, API_TYPES)) ? directory : null;
23
50
  }
24
51
  export function apiContract(context) {
25
- if (!has(context, CONTRACT))
52
+ const contract = contractOf(context);
53
+ if (!has(context, contract))
26
54
  return null;
27
55
  const servers = tracked(context, ["*.csproj"]).filter((project) => (read(context, project) ?? "").includes(GENERATOR));
28
56
  const [server, ...others] = servers;
29
57
  if (server === undefined)
30
- return fail(`${CONTRACT} is there, but no project writes it: reference ${GENERATOR} in the server's project`);
58
+ return fail(`${contract} is there, but no project writes it: reference ${GENERATOR} in the server's project`);
31
59
  if (others.length > 0)
32
- return fail(`${CONTRACT} has more than one project that could write it (${servers.join(", ")}): keep ${GENERATOR} in the server's project only`);
60
+ return fail(`${contract} has more than one project that could write it (${servers.join(", ")}): keep ${GENERATOR} in the server's project only`);
33
61
  const name = path.basename(server, ".csproj");
34
62
  const document = `"$work"/${quoted(`${name}.json`)}`;
35
63
  const web = webApp(context);
@@ -41,7 +69,7 @@ export function apiContract(context) {
41
69
  `rm -f ${quoted(path.join(path.dirname(server), "obj", `${name}.OpenApiFiles.cache`))}`,
42
70
  `dotnet build ${quoted(server)} --nologo -v quiet -p:OpenApiGenerateDocumentsOnBuild=true -p:OpenApiDocumentsDirectory="$work" >"$work/build.log" || { cat "$work/build.log" >&2; exit 1; }`,
43
71
  "stale=()",
44
- `diff -q ${document} ${CONTRACT} >/dev/null 2>&1 || stale+=(${quoted(path.relative(context.root, path.join(context.cwd, CONTRACT)))})`,
72
+ `diff -q ${document} ${contract} >/dev/null 2>&1 || stale+=(${quoted(path.relative(context.root, path.join(context.cwd, contract)))})`,
45
73
  ...(web === null
46
74
  ? []
47
75
  : [
@@ -53,33 +81,44 @@ export function apiContract(context) {
53
81
  `echo "API contract${web === null ? "" : " and types"} up to date"`,
54
82
  ]);
55
83
  }
56
- const API_VERSION = script([
57
- 'if ! git rev-parse --verify -q master >/dev/null && ! git rev-parse --verify -q origin/master >/dev/null; then echo "no master yet: nothing to compare the contract with"; exit 0; fi',
58
- "if git show-ref --verify --quiet refs/heads/master; then base=master; else base=origin/master; fi",
59
- 'work="$(mktemp -d)"',
60
- "trap 'rm -rf \"$work\"' EXIT",
61
- `if ! git show "$base:./${CONTRACT}" >"$work/base.json" 2>/dev/null; then echo "no ${CONTRACT} on $base yet; nothing to compare against."; exit 0; fi`,
62
- `if git diff --quiet --no-index "$work/base.json" ${CONTRACT} 2>/dev/null; then echo "API contract unchanged since $base"; exit 0; fi`,
63
- `if ! oasdiff breaking "$work/base.json" ${CONTRACT} >"$work/load.log" 2>&1; then cat "$work/load.log" >&2; echo "oasdiff could not compare the documents (see above); is ${CONTRACT} valid JSON? Regenerate it (just api-types)" >&2; exit 1; fi`,
64
- `version_of() { node -e 'let text = ""; process.stdin.on("data", (chunk) => (text += chunk)).on("end", () => console.log(JSON.parse(text).version));'; }`,
65
- `now="$(version_of <${CONTRACT_VERSION})"`,
66
- `was="$(git show "$base:./${CONTRACT_VERSION}" 2>/dev/null | version_of 2>/dev/null || true)"`,
67
- `version_is_higher() { [ "$1" != "$2" ] && [ "$(printf '%s\\n%s\\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }`,
68
- `if oasdiff breaking "$work/base.json" ${CONTRACT} --fail-on ERR; then`,
69
- ' if [ -n "$was" ] && ! version_is_higher "$now" "$was"; then',
70
- ` echo "the API contract changed since $base, but ${CONTRACT_VERSION} still says $now. Raise its minor version (a compatible change), so a consumer can pin the new one." >&2`,
71
- " exit 1",
72
- " fi",
73
- ' echo "API contract changed since $base, compatibly (nothing breaks a consumer), as version $now"',
74
- "else",
75
- ' if [ -n "$was" ] && [ "${now%%.*}" -gt "${was%%.*}" ]; then',
76
- ' echo "API contract breaks consumers since $base (see above), as the new major version $now: every consumer moves to it on purpose."',
77
- " exit 0",
78
- " fi",
79
- ` echo "the API contract breaks consumers (see above). Keep the old shape and add the new one beside it, or, agreed with every consumer, raise the major version in ${CONTRACT_VERSION}." >&2`,
80
- " exit 1",
81
- "fi",
82
- ]);
84
+ function apiVersionScript(contract, breaking) {
85
+ const versionFile = versionFileOf(contract);
86
+ const breakingAllowed = breaking === "never"
87
+ ? [
88
+ ` echo "the API contract breaks consumers (see above), and this repository allows no break (api-version breaking: never in suwgate.yml): keep the old shape and add the new one beside it." >&2`,
89
+ " exit 1",
90
+ ]
91
+ : [
92
+ ' if [ -n "$was" ] && [ "${now%%.*}" -gt "${was%%.*}" ]; then',
93
+ ' echo "API contract breaks consumers since $base (see above), as the new major version $now: every consumer moves to it on purpose."',
94
+ " exit 0",
95
+ " fi",
96
+ ` echo "the API contract breaks consumers (see above). Keep the old shape and add the new one beside it, or, agreed with every consumer, raise the major version in ${versionFile}." >&2`,
97
+ " exit 1",
98
+ ];
99
+ return script([
100
+ 'if ! git rev-parse --verify -q master >/dev/null && ! git rev-parse --verify -q origin/master >/dev/null; then echo "no master yet: nothing to compare the contract with"; exit 0; fi',
101
+ "if git show-ref --verify --quiet refs/heads/master; then base=master; else base=origin/master; fi",
102
+ 'work="$(mktemp -d)"',
103
+ "trap 'rm -rf \"$work\"' EXIT",
104
+ `if ! git show "$base:./${contract}" >"$work/base.json" 2>/dev/null; then echo "no ${contract} on $base yet; nothing to compare against."; exit 0; fi`,
105
+ `if git diff --quiet --no-index "$work/base.json" ${contract} 2>/dev/null; then echo "API contract unchanged since $base"; exit 0; fi`,
106
+ `if ! oasdiff breaking "$work/base.json" ${contract} >"$work/load.log" 2>&1; then cat "$work/load.log" >&2; echo "oasdiff could not compare the documents (see above); is ${contract} valid JSON? Regenerate it (just api-types)" >&2; exit 1; fi`,
107
+ `version_of() { node -e 'let text = ""; process.stdin.on("data", (chunk) => (text += chunk)).on("end", () => console.log(JSON.parse(text).version));'; }`,
108
+ `now="$(version_of <${versionFile} 2>/dev/null || true)"`,
109
+ `was="$(git show "$base:./${versionFile}" 2>/dev/null | version_of 2>/dev/null || true)"`,
110
+ `version_is_higher() { [ "$1" != "$2" ] && [ "$(printf '%s\\n%s\\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }`,
111
+ `if oasdiff breaking "$work/base.json" ${contract} --fail-on ERR; then`,
112
+ ' if [ -n "$was" ] && ! version_is_higher "$now" "$was"; then',
113
+ ` echo "the API contract changed since $base, but ${versionFile} still says $now. Raise its minor version (a compatible change), so a consumer can pin the new one." >&2`,
114
+ " exit 1",
115
+ " fi",
116
+ ' echo "API contract changed since $base, compatibly (nothing breaks a consumer), as version $now"',
117
+ "else",
118
+ ...breakingAllowed,
119
+ "fi",
120
+ ]);
121
+ }
83
122
  function pins(context) {
84
123
  return tracked({ ...context, cwd: context.root }, TAGGED).flatMap((file) => (read({ ...context, cwd: context.root }, file) ?? "").split("\n").flatMap((line, index) => {
85
124
  const tag = TRAIT_TAG.exec(line)?.[1] ?? TITLE_TAG.exec(line)?.[1];
@@ -100,20 +139,24 @@ export function contractPins(context) {
100
139
  export const contractSteps = [
101
140
  {
102
141
  id: API_CONTRACT,
103
- title: `the API contract and the web app's types up to date with the server (${CONTRACT}, ${API_TYPES}, openapi-typescript)`,
142
+ title: `the API contract and the web app's types up to date with the server (${DEFAULT_CONTRACT} or settings.contract, ${API_TYPES}, openapi-typescript)`,
104
143
  profile: "dotnet",
105
144
  needs: ["dotnet"],
106
145
  after: [DOTNET_TEST, PNPM_INSTALL],
107
146
  run: apiContract,
147
+ settingsSchema: CONTRACT_SETTINGS,
108
148
  limitSeconds: 300,
109
149
  },
110
150
  {
111
- id: "api-version",
112
- title: `the API contract's version right for what changed since master (${CONTRACT_VERSION}, oasdiff breaking)`,
151
+ id: API_VERSION_STEP,
152
+ title: "the API contract's version right for what changed since master (the package.json beside the contract, oasdiff breaking)",
113
153
  profile: "dotnet",
114
154
  needs: ["oasdiff", "node"],
115
155
  after: [API_CONTRACT],
116
- run: (context) => (has(context, CONTRACT) ? API_VERSION : null),
156
+ run: (context) => has(context, contractOf(context))
157
+ ? apiVersionScript(contractOf(context), settingsOf(context, API_VERSION_STEP).breaking ?? "major")
158
+ : null,
159
+ settingsSchema: VERSION_SETTINGS,
117
160
  limitSeconds: 60,
118
161
  },
119
162
  {