@maniumek/suwgate 0.0.0-stage → 0.1.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +149 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +97 -0
  5. package/dist/dev/checkoutEnv.d.ts +20 -0
  6. package/dist/dev/checkoutEnv.js +101 -0
  7. package/dist/dev/db.d.ts +25 -0
  8. package/dist/dev/db.js +103 -0
  9. package/dist/dev/index.d.ts +16 -0
  10. package/dist/dev/index.js +108 -0
  11. package/dist/dev/logs.d.ts +15 -0
  12. package/dist/dev/logs.js +127 -0
  13. package/dist/dev/process.d.ts +24 -0
  14. package/dist/dev/process.js +34 -0
  15. package/dist/dev/server.d.ts +8 -0
  16. package/dist/dev/server.js +61 -0
  17. package/dist/dev/settings.d.ts +46 -0
  18. package/dist/dev/settings.js +160 -0
  19. package/dist/dev/smoke.d.ts +15 -0
  20. package/dist/dev/smoke.js +50 -0
  21. package/dist/dev/testing.d.ts +19 -0
  22. package/dist/dev/testing.js +18 -0
  23. package/dist/dev/tmux.d.ts +24 -0
  24. package/dist/dev/tmux.js +121 -0
  25. package/dist/eslint/index.d.ts +17 -0
  26. package/dist/eslint/index.js +91 -0
  27. package/dist/eslint/noComments.d.ts +2 -0
  28. package/dist/eslint/noComments.js +27 -0
  29. package/dist/gate/check.d.ts +13 -0
  30. package/dist/gate/check.js +49 -0
  31. package/dist/gate/config.d.ts +34 -0
  32. package/dist/gate/config.js +170 -0
  33. package/dist/gate/contract.d.ts +51 -0
  34. package/dist/gate/contract.js +1 -0
  35. package/dist/gate/guardsStep.d.ts +14 -0
  36. package/dist/gate/guardsStep.js +53 -0
  37. package/dist/gate/plan.d.ts +29 -0
  38. package/dist/gate/plan.js +86 -0
  39. package/dist/gate/report.d.ts +15 -0
  40. package/dist/gate/report.js +65 -0
  41. package/dist/gate/repository.d.ts +3 -0
  42. package/dist/gate/repository.js +37 -0
  43. package/dist/gate/runner.d.ts +10 -0
  44. package/dist/gate/runner.js +75 -0
  45. package/dist/guards/comments/csharp.d.ts +3 -0
  46. package/dist/guards/comments/csharp.js +163 -0
  47. package/dist/guards/comments/css.d.ts +3 -0
  48. package/dist/guards/comments/css.js +11 -0
  49. package/dist/guards/comments/eslint.d.ts +2 -0
  50. package/dist/guards/comments/eslint.js +81 -0
  51. package/dist/guards/comments/hash.d.ts +3 -0
  52. package/dist/guards/comments/hash.js +72 -0
  53. package/dist/guards/comments/index.d.ts +2 -0
  54. package/dist/guards/comments/index.js +18 -0
  55. package/dist/guards/comments/json.d.ts +3 -0
  56. package/dist/guards/comments/json.js +13 -0
  57. package/dist/guards/comments/markup.d.ts +3 -0
  58. package/dist/guards/comments/markup.js +14 -0
  59. package/dist/guards/comments/scan.d.ts +19 -0
  60. package/dist/guards/comments/scan.js +84 -0
  61. package/dist/guards/comments/sql.d.ts +3 -0
  62. package/dist/guards/comments/sql.js +11 -0
  63. package/dist/guards/comments/switches.d.ts +3 -0
  64. package/dist/guards/comments/switches.js +30 -0
  65. package/dist/guards/criteria/criteriaKinds.d.ts +2 -0
  66. package/dist/guards/criteria/criteriaKinds.js +45 -0
  67. package/dist/guards/criteria/index.d.ts +2 -0
  68. package/dist/guards/criteria/index.js +2 -0
  69. package/dist/guards/database/connectionHost.d.ts +2 -0
  70. package/dist/guards/database/connectionHost.js +30 -0
  71. package/dist/guards/database/index.d.ts +2 -0
  72. package/dist/guards/database/index.js +3 -0
  73. package/dist/guards/database/migrationsUnchanged.d.ts +2 -0
  74. package/dist/guards/database/migrationsUnchanged.js +56 -0
  75. package/dist/guards/dotnet/appsettingsBound.d.ts +2 -0
  76. package/dist/guards/dotnet/appsettingsBound.js +43 -0
  77. package/dist/guards/dotnet/bannedNugetPackages.d.ts +2 -0
  78. package/dist/guards/dotnet/bannedNugetPackages.js +51 -0
  79. package/dist/guards/dotnet/index.d.ts +2 -0
  80. package/dist/guards/dotnet/index.js +4 -0
  81. package/dist/guards/dotnet/msbuild.d.ts +5 -0
  82. package/dist/guards/dotnet/msbuild.js +17 -0
  83. package/dist/guards/dotnet/testContext.d.ts +2 -0
  84. package/dist/guards/dotnet/testContext.js +12 -0
  85. package/dist/guards/dotnet/unusedNugetVersions.d.ts +2 -0
  86. package/dist/guards/dotnet/unusedNugetVersions.js +21 -0
  87. package/dist/guards/index.d.ts +2 -0
  88. package/dist/guards/index.js +6 -0
  89. package/dist/guards/repository/agentsFile.d.ts +3 -0
  90. package/dist/guards/repository/agentsFile.js +56 -0
  91. package/dist/guards/repository/bannedNpmPackages.d.ts +2 -0
  92. package/dist/guards/repository/bannedNpmPackages.js +43 -0
  93. package/dist/guards/repository/composePorts.d.ts +6 -0
  94. package/dist/guards/repository/composePorts.js +57 -0
  95. package/dist/guards/repository/dependencyDirection.d.ts +2 -0
  96. package/dist/guards/repository/dependencyDirection.js +87 -0
  97. package/dist/guards/repository/docsPaths.d.ts +2 -0
  98. package/dist/guards/repository/docsPaths.js +54 -0
  99. package/dist/guards/repository/forbiddenNames.d.ts +4 -0
  100. package/dist/guards/repository/forbiddenNames.js +69 -0
  101. package/dist/guards/repository/hooks.d.ts +3 -0
  102. package/dist/guards/repository/hooks.js +86 -0
  103. package/dist/guards/repository/imagePins.d.ts +3 -0
  104. package/dist/guards/repository/imagePins.js +68 -0
  105. package/dist/guards/repository/index.d.ts +2 -0
  106. package/dist/guards/repository/index.js +32 -0
  107. package/dist/guards/repository/justModules.d.ts +2 -0
  108. package/dist/guards/repository/justModules.js +36 -0
  109. package/dist/guards/repository/noRawColors.d.ts +2 -0
  110. package/dist/guards/repository/noRawColors.js +29 -0
  111. package/dist/guards/repository/packageManifests.d.ts +13 -0
  112. package/dist/guards/repository/packageManifests.js +26 -0
  113. package/dist/guards/repository/repositoryLayout.d.ts +3 -0
  114. package/dist/guards/repository/repositoryLayout.js +75 -0
  115. package/dist/guards/repository/requiredFiles.d.ts +6 -0
  116. package/dist/guards/repository/requiredFiles.js +78 -0
  117. package/dist/guards/repository/scriptsCalled.d.ts +3 -0
  118. package/dist/guards/repository/scriptsCalled.js +39 -0
  119. package/dist/guards/repository/scriptsHelp.d.ts +2 -0
  120. package/dist/guards/repository/scriptsHelp.js +37 -0
  121. package/dist/guards/repository/testRepository.d.ts +4 -0
  122. package/dist/guards/repository/testRepository.js +39 -0
  123. package/dist/guards/repository/text.d.ts +20 -0
  124. package/dist/guards/repository/text.js +33 -0
  125. package/dist/guards/repository/vsCodeSettings.d.ts +3 -0
  126. package/dist/guards/repository/vsCodeSettings.js +49 -0
  127. package/dist/profiles/contract.d.ts +5 -0
  128. package/dist/profiles/contract.js +124 -0
  129. package/dist/profiles/criteria.d.ts +25 -0
  130. package/dist/profiles/criteria.js +162 -0
  131. package/dist/profiles/database.d.ts +4 -0
  132. package/dist/profiles/database.js +23 -0
  133. package/dist/profiles/dotnet.d.ts +5 -0
  134. package/dist/profiles/dotnet.js +56 -0
  135. package/dist/profiles/everyRepository.d.ts +2 -0
  136. package/dist/profiles/everyRepository.js +32 -0
  137. package/dist/profiles/index.d.ts +2 -0
  138. package/dist/profiles/index.js +21 -0
  139. package/dist/profiles/library.d.ts +7 -0
  140. package/dist/profiles/library.js +132 -0
  141. package/dist/profiles/node.d.ts +5 -0
  142. package/dist/profiles/node.js +79 -0
  143. package/dist/profiles/presets/knip.d.ts +11 -0
  144. package/dist/profiles/presets/knip.js +29 -0
  145. package/dist/profiles/presets/playwright.d.ts +68 -0
  146. package/dist/profiles/presets/playwright.js +37 -0
  147. package/dist/profiles/presets/prettier.d.ts +12 -0
  148. package/dist/profiles/presets/prettier.js +7 -0
  149. package/dist/profiles/presets/tsconfig/browser.json +11 -0
  150. package/dist/profiles/presets/tsconfig/node.json +8 -0
  151. package/dist/profiles/presets/tsconfig/strict.json +17 -0
  152. package/dist/profiles/presets/vitest.d.ts +36 -0
  153. package/dist/profiles/presets/vitest.js +16 -0
  154. package/dist/profiles/shell.d.ts +10 -0
  155. package/dist/profiles/shell.js +62 -0
  156. package/dist/profiles/web.d.ts +2 -0
  157. package/dist/profiles/web.js +17 -0
  158. package/dist/session/guardEdit.d.ts +19 -0
  159. package/dist/session/guardEdit.js +96 -0
  160. package/dist/session/preCommit.d.ts +16 -0
  161. package/dist/session/preCommit.js +33 -0
  162. package/dist/session/stop.d.ts +8 -0
  163. package/dist/session/stop.js +39 -0
  164. package/package.json +97 -3
  165. package/schema/suwgate.schema.json +196 -0
@@ -0,0 +1,72 @@
1
+ import { CRITERION_ID, commentGuard, fileName } from "./scan.js";
2
+ const ALL_COMMENTS_ARE_SETTINGS = ".env.example";
3
+ const IGNORE_FILE = /^\.[\w-]*ignore$/;
4
+ const WHOLE_LINE_ONLY = new Set([".gitattributes", ".editorconfig"]);
5
+ const ALSO_AT_THE_END_OF_A_LINE = [".sh", ".bash", ".yaml", ".yml", ".rsp"];
6
+ const NGINX = new Set(["nginx.conf", "nginx.conf.template"]);
7
+ const SHELLCHECK_DIRECTIVE = /^# shellcheck (disable|enable|source|shell|external-sources)=\S+$/;
8
+ const DOCKERFILE_SYNTAX = /^# syntax=\S+$/;
9
+ const EDITORCONFIG_CRITERION = new RegExp(`^# ${CRITERION_ID}$`);
10
+ const RECIPE_OR_MODULE = /^(@?[A-Za-z_][\w-]*(\s+[^:=]*)?:(?!=)|mod\s+[\w-]+\s*$)/;
11
+ const isJust = (file) => ["justfile", ".justfile"].includes(fileName(file).toLowerCase()) || file.endsWith(".just");
12
+ const isShell = (file) => file.endsWith(".sh") || file.endsWith(".bash") || file.startsWith(".githooks/");
13
+ const isDockerfile = (file) => /^Dockerfile(\..+)?$/.test(fileName(file)) || file.endsWith(".Dockerfile");
14
+ const isEditorconfig = (file) => fileName(file) === ".editorconfig";
15
+ const alsoAtTheEnd = (file) => isShell(file) || NGINX.has(fileName(file)) || ALSO_AT_THE_END_OF_A_LINE.some((extension) => file.endsWith(extension));
16
+ function usesHashComments(file) {
17
+ const name = fileName(file);
18
+ return (name !== ALL_COMMENTS_ARE_SETTINGS &&
19
+ (isJust(file) || isDockerfile(file) || IGNORE_FILE.test(name) || WHOLE_LINE_ONLY.has(name) || alsoAtTheEnd(file)));
20
+ }
21
+ function commentAtTheEnd(line) {
22
+ let quote = "";
23
+ for (let at = 0; at < line.length; at++) {
24
+ const sign = line.charAt(at);
25
+ if (quote !== "") {
26
+ if (sign === "\\" && quote === '"')
27
+ at++;
28
+ else if (sign === quote)
29
+ quote = "";
30
+ }
31
+ else if (sign === '"' || sign === "'") {
32
+ quote = sign;
33
+ }
34
+ else if (sign === "#" && at > 0 && /\s/.test(line.charAt(at - 1))) {
35
+ return line.slice(at).trimEnd();
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+ function commentOn(file, line) {
41
+ const trimmed = line.trimStart();
42
+ if (trimmed.startsWith("#") || (isEditorconfig(file) && trimmed.startsWith(";")))
43
+ return trimmed.trimEnd();
44
+ return alsoAtTheEnd(file) ? commentAtTheEnd(line) : null;
45
+ }
46
+ function describesTheRecipeBelow(lines, index) {
47
+ let next = index + 1;
48
+ while (next < lines.length && (lines[next] ?? "").startsWith("[") && !(lines[next] ?? "").startsWith("[private]"))
49
+ next++;
50
+ return next < lines.length && RECIPE_OR_MODULE.test(lines[next] ?? "");
51
+ }
52
+ function isAllowed(file, lines, index, comment) {
53
+ return ((index === 0 && comment.startsWith("#!")) ||
54
+ (isShell(file) && SHELLCHECK_DIRECTIVE.test(comment)) ||
55
+ (isDockerfile(file) && index === 0 && DOCKERFILE_SYNTAX.test(comment)) ||
56
+ (isEditorconfig(file) && EDITORCONFIG_CRITERION.test(comment)) ||
57
+ (isJust(file) && describesTheRecipeBelow(lines, index)));
58
+ }
59
+ export function hashCommentsIn(file, text) {
60
+ const lines = text.split("\n");
61
+ return lines.flatMap((line, index) => {
62
+ const comment = commentOn(file, line);
63
+ return comment !== null && !isAllowed(file, lines, index, comment) ? [{ line: index + 1, text: comment }] : [];
64
+ });
65
+ }
66
+ export const commentsHash = commentGuard({
67
+ id: "comments-hash",
68
+ description: "No shell, YAML, Dockerfile, ignore, .editorconfig, justfile, nginx or .rsp file holds a comment but a tool directive (a shebang, shellcheck, Dockerfile syntax, a criterion id in .editorconfig, the justfile recipe line; .env.example keeps its comments)",
69
+ profiles: "every",
70
+ scans: usesHashComments,
71
+ commentsIn: hashCommentsIn,
72
+ });
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const commentGuards: readonly Guard[];
@@ -0,0 +1,18 @@
1
+ import { commentsCsharp } from "./csharp.js";
2
+ import { commentsCss } from "./css.js";
3
+ import { commentsEslint } from "./eslint.js";
4
+ import { commentsHash } from "./hash.js";
5
+ import { commentsJson } from "./json.js";
6
+ import { commentsMarkup } from "./markup.js";
7
+ import { commentsSql } from "./sql.js";
8
+ import { noInPlaceSwitches } from "./switches.js";
9
+ export const commentGuards = [
10
+ commentsHash,
11
+ commentsCss,
12
+ commentsJson,
13
+ commentsMarkup,
14
+ commentsSql,
15
+ commentsCsharp,
16
+ commentsEslint,
17
+ noInPlaceSwitches,
18
+ ];
@@ -0,0 +1,3 @@
1
+ import { type FoundComment } from "./scan.ts";
2
+ export declare function jsonCommentsIn(file: string, text: string): FoundComment[];
3
+ export declare const commentsJson: import("../../gate/contract.ts").Guard;
@@ -0,0 +1,13 @@
1
+ import { CRITERION_ID, commentGuard, fileName, scan } from "./scan.js";
2
+ const CRITERION_MARKER = new RegExp(`^// ${CRITERION_ID}$`);
3
+ export function jsonCommentsIn(file, text) {
4
+ const readsCriterionMarkers = /^tsconfig[\w.-]*\.json$/.test(fileName(file));
5
+ return scan(text, "//", '"').filter((comment) => !(readsCriterionMarkers && CRITERION_MARKER.test(comment.text)));
6
+ }
7
+ export const commentsJson = commentGuard({
8
+ id: "comments-json",
9
+ description: "No JSON file holds a comment but a criterion id on its own line in a tsconfig, where the criteria check reads it",
10
+ profiles: "every",
11
+ scans: (file) => file.endsWith(".json") || file.endsWith(".jsonc"),
12
+ commentsIn: jsonCommentsIn,
13
+ });
@@ -0,0 +1,3 @@
1
+ import { type FoundComment } from "./scan.ts";
2
+ export declare function markupCommentsIn(file: string, text: string): FoundComment[];
3
+ export declare const commentsMarkup: import("../../gate/contract.ts").Guard;
@@ -0,0 +1,14 @@
1
+ import { CRITERION_ID, commentGuard, fileName, scan } from "./scan.js";
2
+ const EXTENSIONS = [".props", ".targets", ".csproj", ".proj", ".slnx", ".config", ".html", ".svg", ".xml"];
3
+ const CRITERION_MARKER = new RegExp(`^<!-- ${CRITERION_ID} -->$`);
4
+ export function markupCommentsIn(file, text) {
5
+ const readsCriterionMarkers = fileName(file) === "Directory.Build.props";
6
+ return scan(text, null, "", "<!--", "-->").filter((comment) => !(readsCriterionMarkers && CRITERION_MARKER.test(comment.text)));
7
+ }
8
+ export const commentsMarkup = commentGuard({
9
+ id: "comments-markup",
10
+ description: "No XML, HTML, SVG or MSBuild file holds a comment but a criterion id in Directory.Build.props, where the criteria check reads it",
11
+ profiles: "every",
12
+ scans: (file) => EXTENSIONS.some((extension) => file.endsWith(extension)),
13
+ commentsIn: markupCommentsIn,
14
+ });
@@ -0,0 +1,19 @@
1
+ import type { Guard, Profile } from "../../gate/contract.ts";
2
+ export interface FoundComment {
3
+ line: number;
4
+ text: string;
5
+ }
6
+ export declare const CRITERION_ID = "AC-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9]+";
7
+ export declare function fileName(file: string): string;
8
+ export declare function isScanned(file: string): boolean;
9
+ export declare function lineBreaks(text: string, start: number, end: number): number;
10
+ export declare function scan(text: string, lineComment: string | null, quotes: string, blockStart?: string, blockEnd?: string): FoundComment[];
11
+ interface CommentGuard {
12
+ id: string;
13
+ description: string;
14
+ profiles: readonly Profile[] | "every";
15
+ scans(file: string): boolean;
16
+ commentsIn(file: string, text: string): readonly FoundComment[];
17
+ }
18
+ export declare function commentGuard(guard: CommentGuard): Guard;
19
+ export {};
@@ -0,0 +1,84 @@
1
+ import path from "node:path";
2
+ export const CRITERION_ID = "AC-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9]+";
3
+ const FIX = 'delete it; rename or split the code so it explains itself; put lasting knowledge in a test, the README, AGENTS.md or docs/ (the only comments allowed are the tool directives listed in AGENTS.md, "No comments")';
4
+ const LOCKFILES = new Set(["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "packages.lock.json"]);
5
+ const SKIPPED_FOLDERS = [
6
+ "node_modules/",
7
+ "dist/",
8
+ "bin/",
9
+ "obj/",
10
+ ".artifacts/",
11
+ ".changeset/",
12
+ "docs/",
13
+ "storybook-static/",
14
+ "visual/snapshots/",
15
+ ];
16
+ export function fileName(file) {
17
+ return path.posix.basename(file);
18
+ }
19
+ export function isScanned(file) {
20
+ return !LOCKFILES.has(fileName(file)) && !SKIPPED_FOLDERS.some((folder) => file.startsWith(folder) || file.includes(`/${folder}`));
21
+ }
22
+ function endOfString(text, opening, quote) {
23
+ for (let at = opening + 1; at < text.length; at++) {
24
+ if (text[at] === "\\")
25
+ at++;
26
+ else if (text[at] === quote)
27
+ return at + 1;
28
+ }
29
+ return text.length;
30
+ }
31
+ export function lineBreaks(text, start, end) {
32
+ return text.slice(start, end).split("\n").length - 1;
33
+ }
34
+ export function scan(text, lineComment, quotes, blockStart = "/*", blockEnd = "*/") {
35
+ const found = [];
36
+ let line = 1;
37
+ let at = 0;
38
+ while (at < text.length) {
39
+ const sign = text.charAt(at);
40
+ if (sign === "\n") {
41
+ line++;
42
+ at++;
43
+ }
44
+ else if (quotes.includes(sign)) {
45
+ const end = endOfString(text, at, sign);
46
+ line += lineBreaks(text, at, end);
47
+ at = end;
48
+ }
49
+ else if (lineComment !== null && text.startsWith(lineComment, at)) {
50
+ const newline = text.indexOf("\n", at);
51
+ const end = newline < 0 ? text.length : newline;
52
+ found.push({ line, text: text.slice(at, end).trim() });
53
+ at = end;
54
+ }
55
+ else if (text.startsWith(blockStart, at)) {
56
+ const close = text.indexOf(blockEnd, at + blockStart.length);
57
+ const end = close < 0 ? text.length : close + blockEnd.length;
58
+ found.push({ line, text: text.slice(at, end).trim() });
59
+ line += lineBreaks(text, at, end);
60
+ at = end;
61
+ }
62
+ else {
63
+ at++;
64
+ }
65
+ }
66
+ return found;
67
+ }
68
+ function shown(comment) {
69
+ const first = (comment.text.split("\n")[0] ?? "").trim();
70
+ return first.length > 120 ? `${first.slice(0, 120)}…` : first;
71
+ }
72
+ function commentFinding(file, comment) {
73
+ return { target: file, line: comment.line, message: `comment "${shown(comment)}": ${FIX}` };
74
+ }
75
+ export function commentGuard(guard) {
76
+ return {
77
+ id: guard.id,
78
+ description: guard.description,
79
+ profiles: guard.profiles,
80
+ check: (context) => context.files
81
+ .filter((file) => isScanned(file) && guard.scans(file))
82
+ .flatMap((file) => guard.commentsIn(file, context.read(file)).map((comment) => commentFinding(file, comment))),
83
+ };
84
+ }
@@ -0,0 +1,3 @@
1
+ import { type FoundComment } from "./scan.ts";
2
+ export declare function sqlCommentsIn(text: string): FoundComment[];
3
+ export declare const commentsSql: import("../../gate/contract.ts").Guard;
@@ -0,0 +1,11 @@
1
+ import { commentGuard, scan } from "./scan.js";
2
+ export function sqlCommentsIn(text) {
3
+ return scan(text, "--", "'\"");
4
+ }
5
+ export const commentsSql = commentGuard({
6
+ id: "comments-sql",
7
+ description: "No SQL file holds a comment",
8
+ profiles: ["database"],
9
+ scans: (file) => file.endsWith(".sql"),
10
+ commentsIn: (_, text) => sqlCommentsIn(text),
11
+ });
@@ -0,0 +1,3 @@
1
+ import type { Finding, Guard } from "../../gate/contract.ts";
2
+ export declare function switchesIn(file: string, text: string): Finding[];
3
+ export declare const noInPlaceSwitches: Guard;
@@ -0,0 +1,30 @@
1
+ import { isScanned } from "./scan.js";
2
+ const SWITCHES = [
3
+ {
4
+ files: /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/,
5
+ directive: /(?:\/\/+|\/\*+)\s*(@ts-ignore|@ts-nocheck|eslint-disable[\w-]*|eslint(?=\s))/,
6
+ fix: "fix the type or the code; a rule that does not fit this repository is switched off once, for every file, in eslint.config.js or tsconfig.json",
7
+ },
8
+ {
9
+ files: /\.cs$/,
10
+ directive: /^\s*#\s*pragma\s+warning\s+disable\b/,
11
+ fix: "fix the code; a rule that does not fit is switched off in .editorconfig, or [SuppressMessage(..., Justification = ...)] goes on the member",
12
+ },
13
+ ];
14
+ export function switchesIn(file, text) {
15
+ const kind = SWITCHES.find((candidate) => candidate.files.test(file));
16
+ if (kind === undefined)
17
+ return [];
18
+ return text.split("\n").flatMap((line, index) => {
19
+ const match = kind.directive.exec(line);
20
+ return match === null
21
+ ? []
22
+ : [{ target: file, line: index + 1, message: `${match[0].trim()} switches a check off in place: ${kind.fix}` }];
23
+ });
24
+ }
25
+ export const noInPlaceSwitches = {
26
+ id: "no-in-place-switches",
27
+ description: "No source file switches the type checker, a lint rule or an analyzer off in place (@ts-ignore, @ts-nocheck, eslint-disable, an eslint config comment, #pragma warning disable)",
28
+ profiles: ["web", "library", "dotnet"],
29
+ check: (context) => context.files.filter(isScanned).flatMap((file) => switchesIn(file, context.read(file))),
30
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const criteriaKinds: Guard;
@@ -0,0 +1,45 @@
1
+ const CRITERIA_FILE = "criteria.json";
2
+ const DOCUMENTS = ["README.md", "docs/development.md"];
3
+ function row(line) {
4
+ return line.replace(/\s+\|/g, " |").replace(/\|\s+/g, "| ");
5
+ }
6
+ function kindsOf(text) {
7
+ try {
8
+ const parsed = JSON.parse(text);
9
+ if (parsed.kinds === undefined)
10
+ return [];
11
+ if (!Array.isArray(parsed.kinds))
12
+ return null;
13
+ return parsed.kinds.map((kind) => kind !== null && typeof kind === "object" && "kind" in kind && typeof kind.kind === "string" ? kind.kind : "");
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ export const criteriaKinds = {
20
+ id: "criteria-kinds",
21
+ description: "Every kind of guardrail criteria.json adds to the defaults of the profiles is explained in a table of README.md or docs/development.md",
22
+ profiles: "every",
23
+ check(context) {
24
+ if (!context.files.includes(CRITERIA_FILE))
25
+ return [];
26
+ const kinds = kindsOf(context.read(CRITERIA_FILE));
27
+ if (kinds === null) {
28
+ return [
29
+ {
30
+ target: CRITERIA_FILE,
31
+ message: 'not a list of kinds: write { "kinds": [{ "kind": "<name>", "paths": ["<glob>"], "how": "<how the id is written>" }] }',
32
+ },
33
+ ];
34
+ }
35
+ const rows = DOCUMENTS.filter((document) => context.files.includes(document)).flatMap((document) => context.read(document).split("\n").map(row));
36
+ return kinds
37
+ .filter((kind) => !rows.some((line) => line.includes(`| \`${kind}\` |`)))
38
+ .map((kind) => ({
39
+ target: kind === "" ? CRITERIA_FILE : kind,
40
+ message: kind === ""
41
+ ? 'a kind without a name: give each kind of criteria.json its "kind"'
42
+ : `no row explains this kind of guardrail of ${CRITERIA_FILE}: add \`| \`${kind}\` | where | how it names the id |\` to a table of ${DOCUMENTS.join(" or ")}`,
43
+ }));
44
+ },
45
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const criteriaGuards: readonly Guard[];
@@ -0,0 +1,2 @@
1
+ import { criteriaKinds } from "./criteriaKinds.js";
2
+ export const criteriaGuards = [criteriaKinds];
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const connectionHost: Guard;
@@ -0,0 +1,30 @@
1
+ const SCANNED = new Set([".cs", ".json", ".sh", ".ts", ".yaml", ".yml", ".md"]);
2
+ const GENERATED = ["pnpm-lock.yaml", "packages.lock.json", "package-lock.json"];
3
+ const LOCALHOST_HOST = new RegExp(String.raw `\bHost\s*=\s*local` + "host\\b", "i");
4
+ function scanned(file) {
5
+ const name = file.slice(file.lastIndexOf("/") + 1);
6
+ return SCANNED.has(name.slice(name.lastIndexOf("."))) && !GENERATED.includes(name);
7
+ }
8
+ export const connectionHost = {
9
+ id: "connection-host",
10
+ description: "No connection string names the host by its name instead of its address (write Host=127.0.0.1)",
11
+ profiles: ["database"],
12
+ check(context) {
13
+ const findings = [];
14
+ for (const file of context.files.filter(scanned)) {
15
+ context
16
+ .read(file)
17
+ .split("\n")
18
+ .forEach((text, index) => {
19
+ if (LOCALHOST_HOST.test(text)) {
20
+ findings.push({
21
+ target: file,
22
+ line: index + 1,
23
+ message: "write Host=127.0.0.1: on Windows the name tries IPv6 first and every new connection waits seconds",
24
+ });
25
+ }
26
+ });
27
+ }
28
+ return findings;
29
+ },
30
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const databaseGuards: readonly Guard[];
@@ -0,0 +1,3 @@
1
+ import { connectionHost } from "./connectionHost.js";
2
+ import { migrationsUnchanged } from "./migrationsUnchanged.js";
3
+ export const databaseGuards = [connectionHost, migrationsUnchanged];
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const migrationsUnchanged: Guard;
@@ -0,0 +1,56 @@
1
+ import { execFileSync } from "node:child_process";
2
+ const DEFAULT_FOLDER = /(^|\/)Database\/Migrations\/up\//;
3
+ const MAIN_BRANCHES = ["master", "origin/master"];
4
+ function git(root, args) {
5
+ try {
6
+ return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ function branchPoint(root) {
13
+ for (const branch of MAIN_BRANCHES) {
14
+ const base = git(root, ["merge-base", "HEAD", branch])?.trim();
15
+ if (base !== undefined && base.length > 0)
16
+ return base;
17
+ }
18
+ return null;
19
+ }
20
+ function inMigrations(file, folders) {
21
+ if (folders === undefined)
22
+ return DEFAULT_FOLDER.test(file);
23
+ return folders.some((folder) => file.startsWith(folder.endsWith("/") ? folder : `${folder}/`));
24
+ }
25
+ const CHANGED = "changed after master had it: restore it (git checkout master -- <file>) and add a new numbered script instead, because grate refuses to start when a script changes after it ran";
26
+ const FIXES = {
27
+ M: CHANGED,
28
+ T: CHANGED,
29
+ D: "deleted although master has it: restore it (git checkout master -- <file>); to undo its effect add a new numbered script, because grate refuses to start when a script is missing or changed after it ran",
30
+ };
31
+ export const migrationsUnchanged = {
32
+ id: "migrations-unchanged",
33
+ description: "A migration script that exists on master is not changed or deleted; a new numbered script is added instead",
34
+ profiles: ["database"],
35
+ settingsSchema: {
36
+ type: "object",
37
+ additionalProperties: false,
38
+ properties: { folders: { type: "array", minItems: 1, uniqueItems: true, items: { type: "string", minLength: 1 } } },
39
+ },
40
+ check(context) {
41
+ const base = branchPoint(context.root);
42
+ if (base === null)
43
+ return [];
44
+ const settings = (context.settings ?? {});
45
+ const diff = git(context.root, ["diff", "--name-status", "--no-renames", base]) ?? "";
46
+ const findings = [];
47
+ for (const line of diff.split("\n")) {
48
+ const [status = "", file = ""] = line.split("\t");
49
+ const fix = FIXES[status];
50
+ if (fix !== undefined && inMigrations(file, settings.folders)) {
51
+ findings.push({ target: file, message: fix.replace("<file>", file) });
52
+ }
53
+ }
54
+ return findings;
55
+ },
56
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const appsettingsBound: Guard;
@@ -0,0 +1,43 @@
1
+ import { dotnetFiles } from "./msbuild.js";
2
+ const FRAMEWORK_SECTIONS = ["Logging", "AllowedHosts", "ConnectionStrings", "Kestrel"];
3
+ const APPSETTINGS = /(^|\/)appsettings(\.[\w-]+)?\.json$/;
4
+ const CSHARP = /\.cs$/;
5
+ const SECTION_READ = /\b(?:BindConfiguration|GetSection|GetRequiredSection)\(\s*"([^":]+)/g;
6
+ function sectionsOf(file, text) {
7
+ try {
8
+ const parsed = JSON.parse(text);
9
+ return { sections: typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? Object.keys(parsed) : [] };
10
+ }
11
+ catch (error) {
12
+ return {
13
+ sections: [],
14
+ problem: { target: file, message: `not valid JSON (${error instanceof Error ? error.message : String(error)}): fix the file` },
15
+ };
16
+ }
17
+ }
18
+ export const appsettingsBound = {
19
+ id: "appsettings-bound",
20
+ description: "Every section of appsettings*.json is read by the code (an options class bound to it), so no setting is dead",
21
+ profiles: ["dotnet"],
22
+ check(context) {
23
+ const read = new Set(dotnetFiles(context, CSHARP).flatMap((file) => [...context.read(file).matchAll(SECTION_READ)].map((match) => match[1] ?? "")));
24
+ const problems = [];
25
+ const unread = new Map();
26
+ for (const file of dotnetFiles(context, APPSETTINGS)) {
27
+ const { sections, problem } = sectionsOf(file, context.read(file));
28
+ if (problem !== undefined) {
29
+ problems.push(problem);
30
+ }
31
+ for (const section of sections.filter((name) => !FRAMEWORK_SECTIONS.includes(name) && !read.has(name))) {
32
+ unread.set(section, [...(unread.get(section) ?? []), file]);
33
+ }
34
+ }
35
+ const unbound = [...unread.entries()]
36
+ .sort(([a], [b]) => a.localeCompare(b))
37
+ .map(([section, files]) => ({
38
+ target: section,
39
+ message: `no code reads it (in ${files.join(", ")}): remove the setting, or bind it with services.AddOptions<T>().BindConfiguration("${section}")`,
40
+ }));
41
+ return [...problems, ...unbound];
42
+ },
43
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const bannedNugetPackages: Guard;
@@ -0,0 +1,51 @@
1
+ import { msbuildFiles, packagesIn } from "./msbuild.js";
2
+ const AGAINST_A_REAL_THING = "test against the real thing (a real PostgreSQL) or a recorded answer";
3
+ const BANNED_NUGET_PACKAGES = {
4
+ MediatR: "call the handler explicitly from the endpoint, so that grep finds the call",
5
+ AutoMapper: "write the mapping by hand (a ToNote() method), so that grep finds it",
6
+ Mapster: "write the mapping by hand (a ToNote() method), so that grep finds it",
7
+ Scrutor: "register the services explicitly, no assembly scanning",
8
+ Moq: AGAINST_A_REAL_THING,
9
+ NSubstitute: AGAINST_A_REAL_THING,
10
+ FakeItEasy: AGAINST_A_REAL_THING,
11
+ FluentAssertions: "use xUnit's Assert",
12
+ "Newtonsoft.Json": "use System.Text.Json, the serializer ASP.NET Core is configured with",
13
+ "Microsoft.EntityFrameworkCore": "use Dapper with hand-written SQL",
14
+ };
15
+ function bannedAs(name, banned) {
16
+ const lower = name.toLowerCase();
17
+ const entry = Object.entries(banned).find(([prefix]) => lower === prefix.toLowerCase() || lower.startsWith(`${prefix.toLowerCase()}.`));
18
+ return entry?.[1];
19
+ }
20
+ export const bannedNugetPackages = {
21
+ id: "banned-nuget-packages",
22
+ description: "No project references or versions a NuGet package that hides calls from grep, mocks the real thing or duplicates the platform",
23
+ profiles: ["dotnet"],
24
+ settingsSchema: {
25
+ type: "object",
26
+ additionalProperties: false,
27
+ properties: {
28
+ packages: { type: "object", additionalProperties: { type: "string", minLength: 1 }, propertyNames: { minLength: 1 } },
29
+ },
30
+ },
31
+ check(context) {
32
+ const banned = { ...BANNED_NUGET_PACKAGES, ...(context.settings ?? {}).packages };
33
+ const found = new Map();
34
+ for (const file of msbuildFiles(context)) {
35
+ for (const name of packagesIn(context.read(file), ["PackageReference", "PackageVersion", "GlobalPackageReference"])) {
36
+ const fix = bannedAs(name, banned);
37
+ if (fix !== undefined) {
38
+ const entry = found.get(name) ?? { fix, files: [] };
39
+ entry.files.push(file);
40
+ found.set(name, entry);
41
+ }
42
+ }
43
+ }
44
+ return [...found.entries()]
45
+ .sort(([a], [b]) => a.localeCompare(b))
46
+ .map(([name, { fix, files }]) => ({
47
+ target: name,
48
+ message: `banned package (in ${[...new Set(files)].join(", ")}): remove it and ${fix}`,
49
+ }));
50
+ },
51
+ };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const dotnetGuards: readonly Guard[];
@@ -0,0 +1,4 @@
1
+ import { appsettingsBound } from "./appsettingsBound.js";
2
+ import { bannedNugetPackages } from "./bannedNugetPackages.js";
3
+ import { unusedNugetVersions } from "./unusedNugetVersions.js";
4
+ export const dotnetGuards = [bannedNugetPackages, unusedNugetVersions, appsettingsBound];
@@ -0,0 +1,5 @@
1
+ import type { GuardContext } from "../../gate/contract.ts";
2
+ export declare function dotnetFiles(context: GuardContext, pattern: RegExp): string[];
3
+ export declare function msbuildFiles(context: GuardContext): string[];
4
+ export declare function centralPackagesFile(context: GuardContext): string;
5
+ export declare function packagesIn(text: string, elements: readonly string[]): string[];
@@ -0,0 +1,17 @@
1
+ const MSBUILD_FILE = /\.(csproj|props|targets)$/;
2
+ const ARTIFACTS = /(^|\/)(bin|obj)\//;
3
+ export function dotnetFiles(context, pattern) {
4
+ const directory = context.directories.dotnet;
5
+ return context.files.filter((file) => (directory === undefined || file.startsWith(`${directory}/`)) && pattern.test(file) && !ARTIFACTS.test(file));
6
+ }
7
+ export function msbuildFiles(context) {
8
+ return dotnetFiles(context, MSBUILD_FILE);
9
+ }
10
+ export function centralPackagesFile(context) {
11
+ const directory = context.directories.dotnet;
12
+ return directory === undefined ? "Directory.Packages.props" : `${directory}/Directory.Packages.props`;
13
+ }
14
+ export function packagesIn(text, elements) {
15
+ const pattern = new RegExp(`<(?:${elements.join("|")})\\b[^>]*?\\bInclude\\s*=\\s*"([^"]+)"`, "g");
16
+ return [...text.matchAll(pattern)].map((match) => match[1] ?? "").filter((name) => name !== "");
17
+ }
@@ -0,0 +1,2 @@
1
+ import type { GuardContext } from "../../gate/contract.ts";
2
+ export declare function contextOf(files: Readonly<Record<string, string>>, extra?: Partial<GuardContext>): GuardContext;
@@ -0,0 +1,12 @@
1
+ export function contextOf(files, extra = {}) {
2
+ return {
3
+ root: "/",
4
+ files: Object.keys(files),
5
+ profiles: ["dotnet"],
6
+ directories: {},
7
+ exceptions: [],
8
+ settings: undefined,
9
+ read: (file) => files[file] ?? "",
10
+ ...extra,
11
+ };
12
+ }
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const unusedNugetVersions: Guard;
@@ -0,0 +1,21 @@
1
+ import { centralPackagesFile, msbuildFiles, packagesIn } from "./msbuild.js";
2
+ export const unusedNugetVersions = {
3
+ id: "unused-nuget-versions",
4
+ description: "Every package version of Directory.Packages.props is referenced by a project",
5
+ profiles: ["dotnet"],
6
+ check(context) {
7
+ const central = centralPackagesFile(context);
8
+ if (!context.files.includes(central)) {
9
+ return [];
10
+ }
11
+ const centralText = context.read(central);
12
+ const referenced = new Set(msbuildFiles(context).flatMap((file) => packagesIn(file === central ? centralText : context.read(file), ["PackageReference", "GlobalPackageReference"])));
13
+ return [...new Set(packagesIn(centralText, ["PackageVersion"]))]
14
+ .filter((name) => !referenced.has(name))
15
+ .sort((a, b) => a.localeCompare(b))
16
+ .map((name) => ({
17
+ target: name,
18
+ message: `no project references it: remove its PackageVersion from ${central}; a package arrives with the first code that uses it`,
19
+ }));
20
+ },
21
+ };