@shivaedev/quality 0.67.3 → 0.68.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 (106) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +22 -5
  3. package/dist/PackageManifest.d.ts +1 -0
  4. package/dist/PackageManifest.d.ts.map +1 -1
  5. package/dist/PackageManifest.js +1 -1
  6. package/dist/PackageManifest.js.map +1 -1
  7. package/dist/adapters/biome/browserDiagnostic.d.ts +3 -0
  8. package/dist/adapters/biome/browserDiagnostic.d.ts.map +1 -0
  9. package/dist/adapters/biome/browserDiagnostic.js +93 -0
  10. package/dist/adapters/biome/browserDiagnostic.js.map +1 -0
  11. package/dist/adapters/biome/browserTargets.d.ts +19 -0
  12. package/dist/adapters/biome/browserTargets.d.ts.map +1 -0
  13. package/dist/adapters/biome/browserTargets.js +26 -0
  14. package/dist/adapters/biome/browserTargets.js.map +1 -0
  15. package/dist/adapters/biome/run.js +2 -2
  16. package/dist/adapters/biome/run.js.map +1 -1
  17. package/dist/adapters/biome/vitestEntry.d.ts +4 -0
  18. package/dist/adapters/biome/vitestEntry.d.ts.map +1 -0
  19. package/dist/adapters/biome/vitestEntry.js +27 -0
  20. package/dist/adapters/biome/vitestEntry.js.map +1 -0
  21. package/dist/adapters/biome/withExceptionConfig.d.ts +1 -1
  22. package/dist/adapters/biome/withExceptionConfig.d.ts.map +1 -1
  23. package/dist/adapters/biome/withExceptionConfig.js +4 -2
  24. package/dist/adapters/biome/withExceptionConfig.js.map +1 -1
  25. package/dist/adapters/knip/configuration.d.ts.map +1 -1
  26. package/dist/adapters/knip/configuration.js +1 -4
  27. package/dist/adapters/knip/configuration.js.map +1 -1
  28. package/dist/adapters/knip/run.js +3 -3
  29. package/dist/adapters/knip/run.js.map +1 -1
  30. package/dist/biome/recognizeDiagnostics.d.ts.map +1 -1
  31. package/dist/biome/recognizeDiagnostics.js +13 -6
  32. package/dist/biome/recognizeDiagnostics.js.map +1 -1
  33. package/dist/inventory/collect.js +2 -2
  34. package/dist/inventory/collect.js.map +1 -1
  35. package/dist/inventory/toolOwnedFiles.d.ts +4 -0
  36. package/dist/inventory/toolOwnedFiles.d.ts.map +1 -0
  37. package/dist/inventory/toolOwnedFiles.js +36 -0
  38. package/dist/inventory/toolOwnedFiles.js.map +1 -0
  39. package/dist/rules/files/otherNames.d.ts.map +1 -1
  40. package/dist/rules/files/otherNames.js +13 -1
  41. package/dist/rules/files/otherNames.js.map +1 -1
  42. package/dist/rules/stories/adapters/authTables.d.ts +3 -0
  43. package/dist/rules/stories/adapters/authTables.d.ts.map +1 -0
  44. package/dist/rules/stories/adapters/authTables.js +52 -0
  45. package/dist/rules/stories/adapters/authTables.js.map +1 -0
  46. package/dist/rules/stories/adapters/eventConsumption.d.ts +5 -0
  47. package/dist/rules/stories/adapters/eventConsumption.d.ts.map +1 -0
  48. package/dist/rules/stories/adapters/eventConsumption.js +30 -0
  49. package/dist/rules/stories/adapters/eventConsumption.js.map +1 -0
  50. package/dist/rules/stories/adapters/outcomeShapes.d.ts +5 -0
  51. package/dist/rules/stories/adapters/outcomeShapes.d.ts.map +1 -0
  52. package/dist/rules/stories/adapters/outcomeShapes.js +46 -0
  53. package/dist/rules/stories/adapters/outcomeShapes.js.map +1 -0
  54. package/dist/rules/stories/adapters/sqlTables.d.ts +5 -0
  55. package/dist/rules/stories/adapters/sqlTables.d.ts.map +1 -0
  56. package/dist/rules/stories/adapters/sqlTables.js +85 -0
  57. package/dist/rules/stories/adapters/sqlTables.js.map +1 -0
  58. package/dist/rules/stories/adapters/sqlTokens.d.ts +3 -0
  59. package/dist/rules/stories/adapters/sqlTokens.d.ts.map +1 -0
  60. package/dist/rules/stories/adapters/sqlTokens.js +30 -0
  61. package/dist/rules/stories/adapters/sqlTokens.js.map +1 -0
  62. package/dist/rules/stories/authSql.d.ts.map +1 -1
  63. package/dist/rules/stories/authSql.js +18 -111
  64. package/dist/rules/stories/authSql.js.map +1 -1
  65. package/dist/rules/stories/domainOutcomes.d.ts.map +1 -1
  66. package/dist/rules/stories/domainOutcomes.js +24 -17
  67. package/dist/rules/stories/domainOutcomes.js.map +1 -1
  68. package/dist/rules/stories/waitOnEvents.d.ts.map +1 -1
  69. package/dist/rules/stories/waitOnEvents.js +18 -2
  70. package/dist/rules/stories/waitOnEvents.js.map +1 -1
  71. package/package.json +3 -1
  72. package/src/PackageManifest.ts +1 -1
  73. package/src/adapters/biome/browserDiagnostic.ts +100 -0
  74. package/src/adapters/biome/browserTargets.ts +27 -0
  75. package/src/adapters/biome/run.ts +2 -2
  76. package/src/adapters/biome/vitestEntry.ts +37 -0
  77. package/src/adapters/biome/withExceptionConfig.ts +4 -2
  78. package/src/adapters/knip/configuration.ts +1 -4
  79. package/src/adapters/knip/run.ts +3 -3
  80. package/src/biome/recognizeDiagnostics.ts +12 -5
  81. package/src/inventory/collect.ts +2 -2
  82. package/src/inventory/toolOwnedFiles.ts +41 -0
  83. package/src/rules/files/otherNames.ts +13 -1
  84. package/src/rules/stories/adapters/authTables.ts +58 -0
  85. package/src/rules/stories/adapters/eventConsumption.ts +35 -0
  86. package/src/rules/stories/adapters/outcomeShapes.ts +57 -0
  87. package/src/rules/stories/adapters/sqlTables.ts +96 -0
  88. package/src/rules/stories/adapters/sqlTokens.ts +31 -0
  89. package/src/rules/stories/authSql.ts +20 -128
  90. package/src/rules/stories/domainOutcomes.ts +25 -18
  91. package/src/rules/stories/waitOnEvents.ts +24 -2
  92. package/dist/inventory/shadcnAlias.d.ts +0 -2
  93. package/dist/inventory/shadcnAlias.d.ts.map +0 -1
  94. package/dist/inventory/shadcnAlias.js +0 -73
  95. package/dist/inventory/shadcnAlias.js.map +0 -1
  96. package/dist/inventory/shadcnFiles.d.ts +0 -4
  97. package/dist/inventory/shadcnFiles.d.ts.map +0 -1
  98. package/dist/inventory/shadcnFiles.js +0 -83
  99. package/dist/inventory/shadcnFiles.js.map +0 -1
  100. package/dist/inventory/shadcnFolders.d.ts +0 -6
  101. package/dist/inventory/shadcnFolders.d.ts.map +0 -1
  102. package/dist/inventory/shadcnFolders.js +0 -27
  103. package/dist/inventory/shadcnFolders.js.map +0 -1
  104. package/src/inventory/shadcnAlias.ts +0 -88
  105. package/src/inventory/shadcnFiles.ts +0 -87
  106. package/src/inventory/shadcnFolders.ts +0 -36
@@ -1,13 +1,15 @@
1
1
  import { resolve } from "node:path";
2
2
  import ts from "typescript";
3
+ import { browserDiagnostic } from "#adapters/biome/browserDiagnostic.ts";
3
4
  import { syntaxOf } from "#adapters/biome/syntaxOf.ts";
5
+ import { vitestEntry } from "#adapters/biome/vitestEntry.ts";
4
6
  import { nativeEffectCall } from "./nativeEffectCall.ts";
5
7
  import type { Diagnostic } from "./report.ts";
6
8
  import { nodeAt, offsetOf, type Syntax } from "./syntax.ts";
7
9
 
8
10
  const RECOGNIZED: ReadonlySet<string> = new Set(["lint/correctness/noComponentHookFactories", "lint/style/noDoneCallback"]);
9
11
 
10
- function generatorParameter(node: ts.Node): boolean {
12
+ function generatorParameter(node: ts.Node, syntax: Syntax): boolean {
11
13
  const parameter = node.parent;
12
14
  const callback = parameter.parent;
13
15
  return (
@@ -17,6 +19,7 @@ function generatorParameter(node: ts.Node): boolean {
17
19
  && callback.asteriskToken !== undefined
18
20
  && ts.isCallExpression(callback.parent)
19
21
  && callback.parent.arguments.includes(callback)
22
+ && !vitestEntry(callback.parent.expression, syntax)
20
23
  );
21
24
  }
22
25
 
@@ -44,7 +47,7 @@ function misclassified(diagnostic: Diagnostic, syntax: Syntax): boolean {
44
47
  }
45
48
  switch (diagnostic.category) {
46
49
  case "lint/style/noDoneCallback":
47
- return generatorParameter(node);
50
+ return generatorParameter(node, syntax);
48
51
  case "lint/correctness/noComponentHookFactories":
49
52
  return tagHandler(node, syntax);
50
53
  default:
@@ -54,14 +57,18 @@ function misclassified(diagnostic: Diagnostic, syntax: Syntax): boolean {
54
57
 
55
58
  export function recognizeDiagnostics(root: string, diagnostics: readonly Diagnostic[]): readonly Diagnostic[] {
56
59
  const sources = new Map<string, Syntax>();
57
- return diagnostics.filter((diagnostic) => {
60
+ return diagnostics.flatMap((diagnostic) => {
58
61
  const path = diagnostic.location.path;
62
+ if (diagnostic.category === "lint/suspicious/useBaseline" && path !== undefined) {
63
+ const recognized = browserDiagnostic(diagnostic, resolve(root, path));
64
+ return recognized === undefined ? [] : [recognized];
65
+ }
59
66
  if (!RECOGNIZED.has(diagnostic.category ?? "") || path === undefined) {
60
- return true;
67
+ return [diagnostic];
61
68
  }
62
69
  const file = resolve(root, path);
63
70
  const syntax = sources.get(file) ?? syntaxOf(file);
64
71
  sources.set(file, syntax);
65
- return !misclassified(diagnostic, syntax);
72
+ return misclassified(diagnostic, syntax) ? [] : [diagnostic];
66
73
  });
67
74
  }
@@ -7,8 +7,8 @@ import type { RuleServices, SourceFile } from "#rule.ts";
7
7
  import { FilesystemFailure, orWhenAbsent, readRequiredText } from "./filesystem.ts";
8
8
  import { posix } from "./ignoreScope.ts";
9
9
  import { linesOf } from "./linesOf.ts";
10
- import { shadcnFiles } from "./shadcnFiles.ts";
11
10
  import { skillCopies } from "./skillCopies.ts";
11
+ import { toolOwnedFiles } from "./toolOwnedFiles.ts";
12
12
  import { scopeAbove, walk } from "./walk.ts";
13
13
 
14
14
  export interface InventoryScope {
@@ -50,7 +50,7 @@ export const collectInventory = Effect.fn("Inventory.collectInventory")(function
50
50
  scope: InventoryScope,
51
51
  ): Effect.fn.Return<Inventory, FilesystemFailure | SetupFailure, RuleServices> {
52
52
  const excluded = ignorePatterns([...scope.exclude]);
53
- const toolOwned = new Set(yield* shadcnFiles(root));
53
+ const toolOwned = new Set(yield* toolOwnedFiles(root));
54
54
  const copies = yield* skillCopies(root);
55
55
  const zones = yield* Effect.forEach(scope.sources, (zone) => zoneFiles(root, zone), { concurrency: READ_CONCURRENCY });
56
56
  const relativePaths = zones.flat().map((absolute) => posix(relative(root, absolute)));
@@ -0,0 +1,41 @@
1
+ import * as NodePath from "@effect/platform-node/NodePath";
2
+ import { Effect, Path, Result, Schema } from "effect";
3
+ import { ignorePatterns } from "#adapters/ignore.ts";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
5
+ import { FilesystemFailure, readRequiredText } from "#inventory/filesystem.ts";
6
+ import { posix } from "#inventory/ignoreScope.ts";
7
+ import { walk } from "#inventory/walk.ts";
8
+ import { PackageManifest } from "#PackageManifest.ts";
9
+
10
+ const decodeManifest = Schema.decodeUnknownResult(Schema.fromJsonString(PackageManifest));
11
+
12
+ export const toolOwnedFiles = Effect.fn("Inventory.toolOwnedFiles")(function* (root: string) {
13
+ const { basename, dirname, join, relative } = yield* Path.Path.pipe(Effect.provide(NodePath.layer));
14
+ const paths = yield* walk(root);
15
+ const manifests = paths.filter((path) => basename(path) === "package.json");
16
+ const owned = yield* Effect.forEach(manifests, (path) =>
17
+ Effect.gen(function* () {
18
+ // Manifest validation reports unreadable or malformed manifests; they establish no ownership.
19
+ const text = yield* readRequiredText(path).pipe(Effect.catchTag("FilesystemFailure", () => Effect.succeed(undefined)));
20
+ if (text === undefined) {
21
+ return [];
22
+ }
23
+ const decoded = decodeManifest(text);
24
+ if (Result.isFailure(decoded)) {
25
+ return [];
26
+ }
27
+ const declarations = yield* Schema.decodeUnknownEffect(GlobDeclarations)(decoded.success.quality?.toolOwned ?? []).pipe(
28
+ Effect.mapError((cause) => new FilesystemFailure({ message: `Cannot read tool-owned facts in ${path}: ${cause.message}`, path })),
29
+ );
30
+ const directory = dirname(path);
31
+ const files = paths.map((file) => posix(relative(directory, file))).filter((file) => !file.startsWith("../"));
32
+ const problems = validateGlobs({ files, options: { toolOwned: declarations } });
33
+ if (problems.length > 0) {
34
+ return yield* new FilesystemFailure({ message: `${path}: ${problems.join("; ")}`, path });
35
+ }
36
+ const matcher = ignorePatterns([...globPatterns(declarations)]);
37
+ return files.filter((file) => matcher.ignores(file)).map((file) => posix(relative(root, join(directory, file))));
38
+ }),
39
+ );
40
+ return [...new Set(owned.flat())];
41
+ });
@@ -9,7 +9,19 @@ import { stylesheetImporters } from "./stylesheetImporters.ts";
9
9
 
10
10
  const DEFAULT_TOOL_OWNED: readonly string[] = [".*", "package.json", "tsconfig*.json", "biome.json", "biome.jsonc", "*.config.*"];
11
11
 
12
- const CONVENTIONAL: ReadonlySet<string> = new Set(["AGENTS", "CHANGELOG", "CLAUDE", "CONTRIBUTING", "LICENSE", "README", "SECURITY", "SKILL"]);
12
+ const CONVENTIONAL: ReadonlySet<string> = new Set([
13
+ "AGENTS",
14
+ "ARCHITECTURE",
15
+ "DESIGN",
16
+ "GLOSSARY",
17
+ "CHANGELOG",
18
+ "CLAUDE",
19
+ "CONTRIBUTING",
20
+ "LICENSE",
21
+ "README",
22
+ "SECURITY",
23
+ "SKILL",
24
+ ]);
13
25
 
14
26
  const KEBAB_KINDS: ReadonlySet<string> = new Set([
15
27
  "avif",
@@ -0,0 +1,58 @@
1
+ import type { SqlText } from "#rules/stories/sqlText.ts";
2
+ import { sqlTokens, tableAt } from "./sqlTokens.ts";
3
+
4
+ const SIGNATURES = [
5
+ ["id", "email", "emailverified"],
6
+ ["id", "accountid", "providerid", "userid"],
7
+ ["id", "token", "expiresat", "userid"],
8
+ ["id", "identifier", "value", "expiresat"],
9
+ ];
10
+
11
+ function columnsAt(tokens: readonly string[], open: number): ReadonlySet<string> {
12
+ let depth = 1;
13
+ let end = open + 1;
14
+ for (; end < tokens.length && depth > 0; end += 1) {
15
+ depth += tokens[end] === "(" ? 1 : 0;
16
+ depth -= tokens[end] === ")" ? 1 : 0;
17
+ }
18
+ const columns = new Set<string>();
19
+ let column = true;
20
+ depth = 0;
21
+ for (const part of tokens.slice(open + 1, end - 1)) {
22
+ if (column) {
23
+ columns.add(part.replaceAll('"', "").replaceAll("_", "").toLowerCase());
24
+ column = false;
25
+ }
26
+ depth += part === "(" ? 1 : 0;
27
+ depth -= part === ")" ? 1 : 0;
28
+ column = part === "," && depth === 0;
29
+ }
30
+ return columns;
31
+ }
32
+
33
+ function definitions(query: SqlText): readonly { readonly name: string; readonly auth: boolean }[] {
34
+ const tokens = sqlTokens(query.text);
35
+ return tokens.flatMap((token, index) => {
36
+ if (token.toLowerCase() !== "create" || tokens[index + 1]?.toLowerCase() !== "table") {
37
+ return [];
38
+ }
39
+ const name = tableAt(tokens, index + 2);
40
+ const open = tokens.indexOf("(", index + 2);
41
+ if (open < 0) {
42
+ return [];
43
+ }
44
+ const columns = columnsAt(tokens, open);
45
+ return name === "" ? [] : [{ auth: SIGNATURES.some((signature) => signature.every((columnName) => columns.has(columnName))), name }];
46
+ });
47
+ }
48
+
49
+ function canonical(name: string): string {
50
+ return name.startsWith("public.") ? name.slice("public.".length) : name;
51
+ }
52
+
53
+ export function authTables(queries: readonly SqlText[], owns: (file: string) => boolean): ReadonlySet<string> {
54
+ const declared = queries.flatMap((query) => definitions(query).map((definition) => ({ ...definition, owner: owns(query.file) })));
55
+ const protectedTables = [...declared.filter(({ auth, owner }) => auth || owner).map(({ name }) => canonical(name))];
56
+
57
+ return new Set([...protectedTables, ...protectedTables.filter((name) => !name.includes(".")).map((name) => `public.${name}`)]);
58
+ }
@@ -0,0 +1,35 @@
1
+ import ts from "typescript";
2
+ import { bindsModule, type ImportBinding } from "#rules/stories/importBindings.ts";
3
+ import { memberName, unwrapped } from "#rules/stories/syntax.ts";
4
+
5
+ export function eventConsumption(node: ts.Node, bindings: ReadonlyMap<string, ImportBinding>): boolean {
6
+ if (ts.isCallExpression(node)) {
7
+ const callee = unwrapped(node.expression);
8
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
9
+ const binding = bindings.get(callee.expression.text);
10
+ const member = memberName(callee);
11
+ if (
12
+ (member === "take" && bindsModule(binding, "Queue", ["effect"]))
13
+ || (member === "await" && bindsModule(binding, "Deferred", ["effect"]))
14
+ || (member === "runCollect" && bindsModule(binding, "Stream", ["effect"]))
15
+ ) {
16
+ return true;
17
+ }
18
+ }
19
+ }
20
+ return ts.forEachChild(node, (child) => eventConsumption(child, bindings)) === true;
21
+ }
22
+
23
+ export function repeatedEventConsumption(call: ts.CallExpression, bindings: ReadonlyMap<string, ImportBinding>): boolean {
24
+ if (eventConsumption(call, bindings)) {
25
+ return true;
26
+ }
27
+ const parent = call.parent;
28
+ return (
29
+ ts.isCallExpression(parent)
30
+ && parent.arguments.includes(call)
31
+ && ts.isPropertyAccessExpression(parent.expression)
32
+ && parent.expression.name.text === "pipe"
33
+ && eventConsumption(parent.expression.expression, bindings)
34
+ );
35
+ }
@@ -0,0 +1,57 @@
1
+ import ts from "typescript";
2
+ import { bindsModule, type ImportBinding } from "#rules/stories/importBindings.ts";
3
+ import { unwrapped } from "#rules/stories/syntax.ts";
4
+
5
+ const SHAPES = ["Exit", "Cause", "Result"];
6
+
7
+ export function shapeModule(node: ts.Expression, bindings: ReadonlyMap<string, ImportBinding>): boolean {
8
+ const value = unwrapped(node);
9
+ return ts.isIdentifier(value) && SHAPES.some((shape) => bindsModule(bindings.get(value.text), shape, ["effect"]));
10
+ }
11
+
12
+ function shapeType(node: ts.Node | undefined, bindings: ReadonlyMap<string, ImportBinding>): boolean {
13
+ if (node === undefined) {
14
+ return false;
15
+ }
16
+ if (ts.isQualifiedName(node) && ts.isIdentifier(node.left) && shapeModule(node.left, bindings)) {
17
+ return true;
18
+ }
19
+ return ts.forEachChild(node, (child) => shapeType(child, bindings)) === true;
20
+ }
21
+
22
+ export function internalValue(
23
+ expression: ts.Expression,
24
+ bindings: ReadonlyMap<string, ImportBinding>,
25
+ checker: ts.TypeChecker,
26
+ seen = new Set<ts.Node>(),
27
+ ): boolean {
28
+ const value = unwrapped(expression);
29
+ if (seen.has(value)) {
30
+ return false;
31
+ }
32
+ seen.add(value);
33
+ if (ts.isYieldExpression(value) && value.expression !== undefined) {
34
+ return internalValue(value.expression, bindings, checker, seen);
35
+ }
36
+ if (ts.isCallExpression(value)) {
37
+ const callee = unwrapped(value.expression);
38
+ if (ts.isPropertyAccessExpression(callee) && shapeModule(callee.expression, bindings)) {
39
+ return true;
40
+ }
41
+ if (ts.isPropertyAccessExpression(callee) && ["exit", "result"].includes(callee.name.text) && ts.isIdentifier(callee.expression)) {
42
+ return bindsModule(bindings.get(callee.expression.text), "Effect", ["effect"]);
43
+ }
44
+ }
45
+ if (ts.isAsExpression(expression) && shapeType(expression.type, bindings)) {
46
+ return true;
47
+ }
48
+ if (ts.isIdentifier(value)) {
49
+ const declarations = (checker.getSymbolAtLocation(value)?.declarations ?? []).filter(ts.isVariableDeclaration);
50
+ return declarations.some(
51
+ (declaration) =>
52
+ shapeType(declaration.type, bindings)
53
+ || (declaration.initializer !== undefined && internalValue(declaration.initializer, bindings, checker, seen)),
54
+ );
55
+ }
56
+ return false;
57
+ }
@@ -0,0 +1,96 @@
1
+ import { sqlTokens, tableAt } from "./sqlTokens.ts";
2
+
3
+ const TABLE_START = new Set(["from", "join", "update", "into", "table", "truncate", "references", "using"]);
4
+ const TABLE_END = new Set(["where", "group", "order", "having", "limit", "returning", "set", "values", "on", ";"]);
5
+ const EXPRESSION_FROM = new Set(["extract", "overlay", "substring", "trim"]);
6
+ const NON_TABLE_TARGETS = new Set([
7
+ "all",
8
+ "database",
9
+ "domain",
10
+ "foreign",
11
+ "function",
12
+ "language",
13
+ "large",
14
+ "parameter",
15
+ "procedure",
16
+ "routine",
17
+ "schema",
18
+ "sequence",
19
+ "tablespace",
20
+ "type",
21
+ ]);
22
+
23
+ function tableBoundary(tokens: readonly string[], index: number, statementStart: number, fromIsTable: boolean) {
24
+ const word = tokens[index]?.toLowerCase() ?? "";
25
+ const permissions = ["grant", "revoke"].includes(tokens[statementStart]?.toLowerCase() ?? "");
26
+ const roleTarget = permissions && (word === "to" || word === "from");
27
+ const permissionTarget = permissions && word === "on" && !NON_TABLE_TARGETS.has(tokens[index + 1]?.toLowerCase() ?? "");
28
+ const indexTarget = word === "on" && tokens.slice(statementStart, index).some((part) => part.toLowerCase() === "index");
29
+ const tableClause = TABLE_START.has(word) && (word !== "from" || fromIsTable);
30
+ return {
31
+ ends: TABLE_END.has(word) || roleTarget,
32
+ starts: !roleTarget && (tableClause || indexTarget || permissionTarget),
33
+ };
34
+ }
35
+
36
+ function userForeignKeyAt(tokens: readonly string[], index: number, statementStart: number): boolean {
37
+ const statement = tokens.slice(statementStart, index).map((token) => token.toLowerCase());
38
+ if (tokens[index]?.toLowerCase() !== "references" || !["create", "alter"].includes(statement[0] ?? "") || !statement.includes("table")) {
39
+ return false;
40
+ }
41
+ let table = index + 1;
42
+ while (tokens[table + 1] === ".") {
43
+ table += 2;
44
+ }
45
+ if (tokens[table + 1] !== "(" || !["id", '"id"'].includes(tokens[table + 2]?.toLowerCase() ?? "") || tokens[table + 3] !== ")") {
46
+ return false;
47
+ }
48
+ const remainder = tokens.slice(table + 4);
49
+ const end = remainder.findIndex((token) => [",", ";", ")"].includes(token));
50
+ const clause = remainder.slice(0, end === -1 ? undefined : end).join(" ");
51
+ return /\bon delete (?:cascade|set null)\b/iu.test(clause);
52
+ }
53
+
54
+ interface SqlContext {
55
+ depth: number;
56
+ readonly expressionFromDepths: Set<number>;
57
+ statementStart: number;
58
+ readonly tablesAtDepth: Set<number>;
59
+ }
60
+
61
+ function advanceContext(context: SqlContext, token: string, index: number, previous: string | undefined): void {
62
+ if (token === ";") {
63
+ context.statementStart = index + 1;
64
+ context.expressionFromDepths.clear();
65
+ }
66
+ if (token === "(") {
67
+ context.depth += 1;
68
+ if (EXPRESSION_FROM.has(previous?.toLowerCase() ?? "")) {
69
+ context.expressionFromDepths.add(context.depth);
70
+ }
71
+ }
72
+ if (token === ")") {
73
+ context.tablesAtDepth.delete(context.depth);
74
+ context.expressionFromDepths.delete(context.depth);
75
+ context.depth -= 1;
76
+ }
77
+ }
78
+
79
+ export function sqlTables(text: string): readonly { readonly name: string; readonly userReference: boolean }[] {
80
+ const tokens = sqlTokens(text);
81
+ const context: SqlContext = { depth: 0, expressionFromDepths: new Set(), statementStart: 0, tablesAtDepth: new Set() };
82
+ return tokens.flatMap((token, index) => {
83
+ advanceContext(context, token, index, tokens[index - 1]);
84
+ const boundary = tableBoundary(tokens, index, context.statementStart, !context.expressionFromDepths.has(context.depth));
85
+ if (boundary.ends) {
86
+ context.tablesAtDepth.delete(context.depth);
87
+ }
88
+ if (boundary.starts) {
89
+ context.tablesAtDepth.add(context.depth);
90
+ }
91
+ const name = tableAt(tokens, index + 1);
92
+ return boundary.starts || (token === "," && context.tablesAtDepth.has(context.depth))
93
+ ? [{ name, userReference: name.split(".").at(-1) === "user" && userForeignKeyAt(tokens, index, context.statementStart) }]
94
+ : [];
95
+ });
96
+ }
@@ -0,0 +1,31 @@
1
+ const TOKENS = /--[^\n]*|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|[\w$]+|[?.,;()]/gu;
2
+ const SKIP = new Set(["if", "not", "exists", "only", "table"]);
3
+ export function sqlTokens(text: string): readonly string[] {
4
+ return [...text.matchAll(TOKENS)]
5
+ .map(([token]) => token)
6
+ .filter((token) => !(token.startsWith("--") || token.startsWith("/*") || token.startsWith("'")));
7
+ }
8
+
9
+ function identifier(token: string): string {
10
+ if (token.startsWith('"')) {
11
+ return token.slice(1, -1).replaceAll('""', '"');
12
+ }
13
+ return /^[a-z_][\w$]*$/iu.test(token) ? token.toLowerCase() : "";
14
+ }
15
+
16
+ export function tableAt(tokens: readonly string[], index: number): string {
17
+ let next = index;
18
+ while (SKIP.has(tokens[next]?.toLowerCase() ?? "")) {
19
+ const only = tokens[next]?.toLowerCase() === "only";
20
+ next += 1;
21
+ if (only && tokens[next] === "(") {
22
+ next += 1;
23
+ }
24
+ }
25
+ const parts = [identifier(tokens[next] ?? "")];
26
+ while (tokens[next + 1] === ".") {
27
+ next += 2;
28
+ parts.push(identifier(tokens[next] ?? ""));
29
+ }
30
+ return parts.includes("") ? "" : parts.join(".");
31
+ }
@@ -1,7 +1,8 @@
1
- import { matchesGlob } from "node:path";
2
- import { Schema } from "effect";
1
+ import { Effect, Schema } from "effect";
3
2
  import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
3
  import { defineRule } from "#rule.ts";
4
+ import { authTables } from "#rules/stories/adapters/authTables.ts";
5
+ import { sqlTables } from "#rules/stories/adapters/sqlTables.ts";
5
6
  import { matchesAny } from "./matchesAny.ts";
6
7
  import { sqlTexts } from "./sqlText.ts";
7
8
 
@@ -9,134 +10,25 @@ const AuthSqlOptions = Schema.Struct({
9
10
  owners: GlobDeclarations,
10
11
  });
11
12
 
12
- const TOKENS = /--[^\n]*|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|[\w$]+|[.,;()]/gu;
13
- const TABLE_START = new Set(["from", "join", "update", "into", "table", "truncate", "references", "using"]);
14
- const TABLE_END = new Set(["where", "group", "order", "having", "limit", "returning", "set", "values", "on", ";"]);
15
- const SKIP = new Set(["if", "not", "exists", "only", "table"]);
16
- const AUTH_TABLES = new Set(["user", "account", "session", "verification"]);
17
- const EXPRESSION_FROM = new Set(["extract", "overlay", "substring", "trim"]);
18
- const NON_TABLE_TARGETS = new Set([
19
- "all",
20
- "database",
21
- "domain",
22
- "foreign",
23
- "function",
24
- "language",
25
- "large",
26
- "parameter",
27
- "procedure",
28
- "routine",
29
- "schema",
30
- "sequence",
31
- "tablespace",
32
- "type",
33
- ]);
34
-
35
- function tableAt(tokens: readonly string[], index: number): string {
36
- let next = index;
37
- while (SKIP.has(tokens[next]?.toLowerCase() ?? "")) {
38
- const only = tokens[next]?.toLowerCase() === "only";
39
- next += 1;
40
- if (only && tokens[next] === "(") {
41
- next += 1;
42
- }
43
- }
44
- while (tokens[next + 1] === ".") {
45
- next += 2;
46
- }
47
- return (tokens[next] ?? "").replaceAll('"', "").toLowerCase();
48
- }
49
-
50
- function tableBoundary(tokens: readonly string[], index: number, statementStart: number, fromIsTable: boolean) {
51
- const word = tokens[index]?.toLowerCase() ?? "";
52
- const permissions = ["grant", "revoke"].includes(tokens[statementStart]?.toLowerCase() ?? "");
53
- const roleTarget = permissions && (word === "to" || word === "from");
54
- const permissionTarget = permissions && word === "on" && !NON_TABLE_TARGETS.has(tokens[index + 1]?.toLowerCase() ?? "");
55
- const indexTarget = word === "on" && tokens.slice(statementStart, index).some((part) => part.toLowerCase() === "index");
56
- const tableClause = TABLE_START.has(word) && (word !== "from" || fromIsTable);
57
- return {
58
- ends: TABLE_END.has(word) || roleTarget,
59
- starts: !roleTarget && (tableClause || indexTarget || permissionTarget),
60
- };
61
- }
62
-
63
- function userForeignKeyAt(tokens: readonly string[], index: number, statementStart: number): boolean {
64
- const statement = tokens.slice(statementStart, index).map((token) => token.toLowerCase());
65
- if (tokens[index]?.toLowerCase() !== "references" || !["create", "alter"].includes(statement[0] ?? "") || !statement.includes("table")) {
66
- return false;
67
- }
68
- let table = index + 1;
69
- while (tokens[table + 1] === ".") {
70
- table += 2;
71
- }
72
- if (tokens[table + 1] !== "(" || !["id", '"id"'].includes(tokens[table + 2]?.toLowerCase() ?? "") || tokens[table + 3] !== ")") {
73
- return false;
74
- }
75
- const remainder = tokens.slice(table + 4);
76
- const end = remainder.findIndex((token) => [",", ";", ")"].includes(token));
77
- const clause = remainder.slice(0, end === -1 ? undefined : end).join(" ");
78
- return /\bon delete (?:cascade|set null)\b/iu.test(clause);
79
- }
80
-
81
- interface SqlContext {
82
- depth: number;
83
- readonly expressionFromDepths: Set<number>;
84
- statementStart: number;
85
- readonly tablesAtDepth: Set<number>;
86
- }
87
-
88
- function advanceContext(context: SqlContext, token: string, index: number, previous: string | undefined): void {
89
- if (token === ";") {
90
- context.statementStart = index + 1;
91
- context.expressionFromDepths.clear();
92
- }
93
- if (token === "(") {
94
- context.depth += 1;
95
- if (EXPRESSION_FROM.has(previous?.toLowerCase() ?? "")) {
96
- context.expressionFromDepths.add(context.depth);
97
- }
98
- }
99
- if (token === ")") {
100
- context.tablesAtDepth.delete(context.depth);
101
- context.expressionFromDepths.delete(context.depth);
102
- context.depth -= 1;
103
- }
104
- }
105
-
106
- function authTableIn(text: string): boolean {
107
- const tokens = [...text.matchAll(TOKENS)]
108
- .map(([token]) => token)
109
- .filter((token) => !(token.startsWith("--") || token.startsWith("/*") || token.startsWith("'")));
110
- const context: SqlContext = { depth: 0, expressionFromDepths: new Set(), statementStart: 0, tablesAtDepth: new Set() };
111
- return tokens.some((token, index) => {
112
- advanceContext(context, token, index, tokens[index - 1]);
113
- const boundary = tableBoundary(tokens, index, context.statementStart, !context.expressionFromDepths.has(context.depth));
114
- if (boundary.ends) {
115
- context.tablesAtDepth.delete(context.depth);
116
- }
117
- if (boundary.starts) {
118
- context.tablesAtDepth.add(context.depth);
119
- }
120
- return (
121
- (boundary.starts || (token === "," && context.tablesAtDepth.has(context.depth)))
122
- && AUTH_TABLES.has(tableAt(tokens, index + 1))
123
- && !(tableAt(tokens, index + 1) === "user" && userForeignKeyAt(tokens, index, context.statementStart))
124
- );
125
- });
126
- }
127
-
128
13
  export const authSql = defineRule({
129
- check: async ({ options, ...inputs }) =>
130
- (await sqlTexts(inputs))
131
- .filter((query) => !matchesAny(query.file, globPatterns(options.owners)) && authTableIn(query.text))
132
- .map((query) => ({
133
- file: query.file,
134
- line: query.line,
135
- message:
136
- "SQL accesses a Better Auth table (user, account, session or verification). Use platform's auth API (@shivaedev/identity) for account data; app migrations may only reference user(id) with ON DELETE CASCADE or ON DELETE SET NULL. Only the configured auth-sql owners manage auth storage.",
137
- })),
14
+ check: ({ options, ...inputs }) =>
15
+ Effect.gen(function* () {
16
+ const queries = yield* Effect.promise(() => sqlTexts(inputs));
17
+ function owns(file: string): boolean {
18
+ return matchesAny(file, globPatterns(options.owners));
19
+ }
20
+ const tables = authTables(queries, owns);
21
+ return queries
22
+ .filter((query) => !owns(query.file) && sqlTables(query.text).some((table) => tables.has(table.name) && !table.userReference))
23
+ .map((query) => ({
24
+ file: query.file,
25
+ line: query.line,
26
+ message:
27
+ "SQL accesses a table owned by Better Auth or matching its schema. Use platform's auth API (@shivaedev/identity) for account data; app migrations may only reference user(id) with ON DELETE CASCADE or ON DELETE SET NULL. Only the configured auth-sql owners manage auth storage.",
28
+ }));
29
+ }),
138
30
  description: "Apps reference user IDs by foreign key and use identity for account data.",
139
31
  id: "boundaries/auth-sql",
140
32
  options: Schema.toStandardSchemaV1(AuthSqlOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
141
- validate: (context) => validateGlobs(context, matchesGlob),
33
+ validate: (context) => validateGlobs(context, (file, glob) => matchesAny(file, [glob])),
142
34
  });
@@ -1,44 +1,51 @@
1
1
  import { Effect } from "effect";
2
2
  import ts from "typescript";
3
+ import { importGraph } from "#imports/graph.ts";
3
4
  import { defineRule } from "#rule.ts";
4
- import { bindsModule, importBindings } from "./importBindings.ts";
5
+ import { internalValue, shapeModule } from "#rules/stories/adapters/outcomeShapes.ts";
6
+ import { importBindings } from "./importBindings.ts";
7
+ import { storyOrigins } from "./origins.ts";
5
8
  import { storySources } from "./sources.ts";
6
- import { memberName, nodesWhere, syntaxFindings, unwrapped } from "./syntax.ts";
9
+ import { findingAt, memberName, nodesWhere, unwrapped } from "./syntax.ts";
7
10
 
8
11
  const MESSAGE =
9
- 'Uses an Exit, Cause or Result value or reads a _tag in a story. Have the kit\'s verb or readout return the outcome in the domain\'s words, such as "unauthorized" or "rolled back", and expect that; build failing inputs in a kit trait.';
12
+ 'Uses an Exit, Cause or Result value or reads an internal outcome tag in a story. Have the kit\'s verb or readout return the outcome in the domain\'s words, such as "unauthorized" or "rolled back", and expect that; build failing inputs in a kit trait.';
10
13
 
11
- const SHAPES = ["Exit", "Cause", "Result"];
12
14
  const OUTCOME_TAGS = new Set(["Failure", "Success"]);
13
15
 
14
- function shapeModule(source: ts.SourceFile): (node: ts.Expression) => boolean {
15
- const bindings = importBindings(source);
16
- return (node) => {
17
- const value = unwrapped(node);
18
- return ts.isIdentifier(value) && SHAPES.some((shape) => bindsModule(bindings.get(value.text), shape, ["effect"]));
19
- };
20
- }
21
-
22
16
  function outcomeTag(node: ts.PropertyAssignment): boolean {
23
17
  const name = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
24
18
  const value = unwrapped(node.initializer);
25
19
  return name === "_tag" && ts.isStringLiteralLike(value) && OUTCOME_TAGS.has(value.text);
26
20
  }
27
21
 
28
- function shapeReads(source: ts.SourceFile): readonly ts.Node[] {
29
- const fromShapeModule = shapeModule(source);
22
+ function shapeReads(source: ts.SourceFile, checker: ts.TypeChecker): readonly ts.Node[] {
23
+ const bindings = importBindings(source);
30
24
  return nodesWhere(
31
25
  source,
32
26
  (node) =>
33
27
  ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
34
- && (memberName(node) === "_tag" || fromShapeModule(node.expression)))
35
- || (ts.isBindingElement(node) && (node.propertyName ?? node.name).getText(source) === "_tag")
28
+ && (shapeModule(node.expression, bindings) || (memberName(node) === "_tag" && internalValue(node.expression, bindings, checker))))
29
+ || (ts.isBindingElement(node)
30
+ && (node.propertyName ?? node.name).getText(source) === "_tag"
31
+ && ts.isVariableDeclaration(node.parent.parent)
32
+ && node.parent.parent.initializer !== undefined
33
+ && internalValue(node.parent.parent.initializer, bindings, checker))
36
34
  || (ts.isPropertyAssignment(node) && outcomeTag(node)),
37
35
  );
38
36
  }
39
37
 
40
38
  export const domainOutcomes = defineRule({
41
- check: (inputs) => Effect.map(storySources(inputs), (stories) => stories.flatMap((file) => syntaxFindings(file, shapeReads, MESSAGE))),
42
- description: "Story verbs and readouts return outcomes in the domain's words, not Exit, Cause or Result shapes or _tag reads.",
39
+ check: (inputs) =>
40
+ Effect.gen(function* () {
41
+ const stories = yield* storySources(inputs);
42
+ const origins = storyOrigins(inputs, yield* importGraph(inputs));
43
+ const checker = origins.checker;
44
+ return stories.flatMap((file) => {
45
+ const source = origins.source(file.path);
46
+ return source === undefined ? [] : shapeReads(source, checker).map((node) => ({ ...findingAt(source, node, MESSAGE), file: file.path }));
47
+ });
48
+ }),
49
+ description: "Story verbs and readouts return outcomes in the domain's words, not Exit, Cause or Result shapes or their internal tag reads.",
43
50
  id: "tests/domain-outcomes",
44
51
  });