@shivaedev/quality 0.49.0 → 0.50.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 (75) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +8 -2
  3. package/dist/cli/args.d.ts +1 -0
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +8 -34
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/baseline.d.ts +1 -1
  8. package/dist/cli/baseline.d.ts.map +1 -1
  9. package/dist/cli/baseline.js +9 -3
  10. package/dist/cli/baseline.js.map +1 -1
  11. package/dist/cli/messages.d.ts +1 -1
  12. package/dist/cli/messages.d.ts.map +1 -1
  13. package/dist/cli/messages.js +2 -1
  14. package/dist/cli/messages.js.map +1 -1
  15. package/dist/cli/options.d.ts +45 -0
  16. package/dist/cli/options.d.ts.map +1 -0
  17. package/dist/cli/options.js +35 -0
  18. package/dist/cli/options.js.map +1 -0
  19. package/dist/cli/program.js +1 -1
  20. package/dist/cli/program.js.map +1 -1
  21. package/dist/imports/classifyRuntime.d.ts.map +1 -1
  22. package/dist/imports/classifyRuntime.js +4 -1
  23. package/dist/imports/classifyRuntime.js.map +1 -1
  24. package/dist/imports/runtime.d.ts +6 -3
  25. package/dist/imports/runtime.d.ts.map +1 -1
  26. package/dist/imports/runtime.js +15 -21
  27. package/dist/imports/runtime.js.map +1 -1
  28. package/dist/naming/migrationFile.d.ts.map +1 -1
  29. package/dist/naming/migrationFile.js +3 -1
  30. package/dist/naming/migrationFile.js.map +1 -1
  31. package/dist/naming/moduleRoot.d.ts +2 -0
  32. package/dist/naming/moduleRoot.d.ts.map +1 -0
  33. package/dist/naming/moduleRoot.js +13 -0
  34. package/dist/naming/moduleRoot.js.map +1 -0
  35. package/dist/rules/builtIn.d.ts +1 -1
  36. package/dist/rules/effect/boundary.d.ts.map +1 -1
  37. package/dist/rules/effect/boundary.js +30 -6
  38. package/dist/rules/effect/boundary.js.map +1 -1
  39. package/dist/rules/effect/boundaryCalls.d.ts +3 -0
  40. package/dist/rules/effect/boundaryCalls.d.ts.map +1 -0
  41. package/dist/rules/effect/boundaryCalls.js +121 -0
  42. package/dist/rules/effect/boundaryCalls.js.map +1 -0
  43. package/dist/rules/effect/boundaryReference.d.ts +4 -0
  44. package/dist/rules/effect/boundaryReference.d.ts.map +1 -0
  45. package/dist/rules/effect/boundaryReference.js +80 -0
  46. package/dist/rules/effect/boundaryReference.js.map +1 -0
  47. package/dist/rules/effect/program.d.ts +1 -1
  48. package/dist/rules/effect/program.d.ts.map +1 -1
  49. package/dist/rules/effect/program.js +4 -1
  50. package/dist/rules/effect/program.js.map +1 -1
  51. package/dist/rules/effect/promiseParameter.d.ts +3 -0
  52. package/dist/rules/effect/promiseParameter.d.ts.map +1 -0
  53. package/dist/rules/effect/promiseParameter.js +24 -0
  54. package/dist/rules/effect/promiseParameter.js.map +1 -0
  55. package/dist/rules/imports/runtime.d.ts +1 -1
  56. package/dist/rules/imports/runtime.d.ts.map +1 -1
  57. package/dist/rules/stories/groupedOutcomes.js +1 -1
  58. package/dist/rules/stories/groupedOutcomes.js.map +1 -1
  59. package/docs/debt-and-hooks.md +3 -1
  60. package/package.json +2 -2
  61. package/src/cli/args.ts +15 -43
  62. package/src/cli/baseline.ts +9 -2
  63. package/src/cli/messages.ts +2 -1
  64. package/src/cli/options.ts +43 -0
  65. package/src/cli/program.ts +1 -1
  66. package/src/imports/classifyRuntime.ts +4 -1
  67. package/src/imports/runtime.ts +19 -21
  68. package/src/naming/migrationFile.ts +3 -1
  69. package/src/naming/moduleRoot.ts +13 -0
  70. package/src/rules/effect/boundary.ts +48 -24
  71. package/src/rules/effect/boundaryCalls.ts +130 -0
  72. package/src/rules/effect/boundaryReference.ts +85 -0
  73. package/src/rules/effect/program.ts +4 -1
  74. package/src/rules/effect/promiseParameter.ts +26 -0
  75. package/src/rules/stories/groupedOutcomes.ts +1 -1
package/src/cli/args.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { Result } from "effect";
3
3
  import { SUBCOMMANDS } from "./messages.ts";
4
+ import { ACCEPTS, misplaced, OPTIONS, type Values } from "./options.ts";
4
5
 
5
6
  export type Command =
6
7
  | { readonly _tag: "Ci"; readonly coverage: boolean }
@@ -10,7 +11,13 @@ export type Command =
10
11
  | { readonly _tag: "Fix"; readonly config: string | undefined; readonly rules: readonly string[] }
11
12
  | { readonly _tag: "BaselineMerge"; readonly base: string; readonly ours: string; readonly theirs: string }
12
13
  | { readonly _tag: "BaselineInstallDriver" }
13
- | { readonly _tag: "BaselineWrite"; readonly config: string | undefined; readonly rules: readonly string[]; readonly files: readonly string[] }
14
+ | {
15
+ readonly _tag: "BaselineWrite";
16
+ readonly config: string | undefined;
17
+ readonly rules: readonly string[];
18
+ readonly files: readonly string[];
19
+ readonly firstAdoption: boolean;
20
+ }
14
21
  | { readonly _tag: "BaselinePrune"; readonly config: string | undefined; readonly against: string | undefined }
15
22
  | { readonly _tag: "BaselineTighten"; readonly config: string | undefined; readonly staged: boolean }
16
23
  | { readonly _tag: "BaselineMigrate"; readonly config: string | undefined; readonly from: string | undefined }
@@ -22,18 +29,6 @@ export type Command =
22
29
 
23
30
  export type Parsed = { readonly _tag: "Parsed"; readonly command: Command } | { readonly _tag: "Usage"; readonly problem: string };
24
31
 
25
- const OPTIONS = {
26
- against: { type: "string" },
27
- config: { type: "string" },
28
- coverage: { type: "boolean" },
29
- file: { multiple: true, type: "string" },
30
- force: { type: "boolean" },
31
- from: { type: "string" },
32
- help: { short: "h", type: "boolean" },
33
- rule: { multiple: true, type: "string" },
34
- staged: { type: "boolean" },
35
- } as const;
36
-
37
32
  function usage(problem: string): Parsed {
38
33
  return { _tag: "Usage", problem };
39
34
  }
@@ -42,35 +37,6 @@ function parsed(command: Command): Parsed {
42
37
  return { _tag: "Parsed", command };
43
38
  }
44
39
 
45
- type Values = ReturnType<typeof parseArgs<{ options: typeof OPTIONS; allowPositionals: true }>>["values"];
46
-
47
- type Option = Exclude<keyof Values, "config" | "help">;
48
-
49
- const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "file", "force", "from", "rule", "staged"];
50
-
51
- const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
52
- "baseline install-driver": [],
53
- "baseline migrate": ["from"],
54
- "baseline prune": ["against"],
55
- "baseline tighten": ["staged"],
56
- "baseline write": ["rule", "file"],
57
- ci: ["coverage"],
58
- "exceptions migrate": ["from"],
59
- fix: ["rule"],
60
- "hooks install": ["force"],
61
- "hooks pre-commit": [],
62
- "hooks status": [],
63
- "hooks uninstall": [],
64
- lint: [],
65
- setup: [],
66
- };
67
-
68
- function misplaced(name: string, values: Values): string | undefined {
69
- const option = COMMAND_OPTIONS.find((key) => values[key] !== undefined && !(ACCEPTS[name] ?? []).includes(key));
70
- const owners = Object.keys(ACCEPTS).filter((owner) => option !== undefined && (ACCEPTS[owner] ?? []).includes(option));
71
- return option === undefined ? undefined : `--${option} applies only to ${owners.join(" and ")}.`;
72
- }
73
-
74
40
  function ref(against: string | undefined, command: Command): Parsed {
75
41
  return against?.startsWith("-") === true ? usage(`--against takes a git ref, not "${against}".`) : parsed(command);
76
42
  }
@@ -91,7 +57,13 @@ function commandFor(name: string, values: Values): Parsed {
91
57
  case "baseline install-driver":
92
58
  return parsed({ _tag: "BaselineInstallDriver" });
93
59
  case "baseline write":
94
- return parsed({ _tag: "BaselineWrite", config, files: values.file ?? [], rules: values.rule ?? [] });
60
+ return parsed({
61
+ _tag: "BaselineWrite",
62
+ config,
63
+ files: values.file ?? [],
64
+ firstAdoption: values["first-adoption"] === true,
65
+ rules: values.rule ?? [],
66
+ });
95
67
  case "baseline prune":
96
68
  return ref(values.against, { _tag: "BaselinePrune", against: values.against, config });
97
69
  case "baseline tighten":
@@ -4,6 +4,7 @@ import type { BaselineEntry } from "#baseline/format.ts";
4
4
  import { saveShards } from "#baseline/shards.ts";
5
5
  import { adopt, type Pruned, prune, type Scope } from "#baseline/update.ts";
6
6
  import { openSession, type Session } from "#engine/session.ts";
7
+ import { registrable } from "#engine/violation.ts";
7
8
  import { applyRegistry } from "#exceptions/registry.ts";
8
9
  import { SetupFailure } from "#failure.ts";
9
10
  import { changesSince } from "#git/history.ts";
@@ -23,16 +24,22 @@ export const writeBaseline = Effect.fn("Cli.writeBaseline")(function* (
23
24
  config: string | undefined,
24
25
  rules: readonly string[],
25
26
  files: readonly string[],
27
+ firstAdoption = false,
26
28
  ): Effect.fn.Return<void, SetupFailure, RuleServices> {
27
29
  const session = yield* openSession(cwd, config);
28
30
  const existing = session.baseline.files.size === 0 ? undefined : session.baseline.entries;
29
- if (existing !== undefined && files.length === 0) {
31
+ if (firstAdoption && (rules.length === 0 || rules.some((rule) => registrable(session.config, rule)))) {
32
+ return yield* new SetupFailure({
33
+ message: "baseline write refused: --first-adoption requires explicit --rule ids that refuse config exceptions.",
34
+ });
35
+ }
36
+ if (existing !== undefined && files.length === 0 && !firstAdoption) {
30
37
  return yield* new SetupFailure({
31
38
  message: "baseline write refused: a baseline exists. Record a rule with --rule <id> and --file <path>; use prune for moved or fixed debt.",
32
39
  });
33
40
  }
34
41
  const selected = files.length === 0 ? undefined : new Set(files.map((file) => relative(session.config.root, resolve(session.config.root, file))));
35
- if (selected !== undefined) {
42
+ if (selected !== undefined && !firstAdoption) {
36
43
  const changed = yield* changesSince(session.config.root, ["HEAD"]);
37
44
  const outside = [...selected].filter((file) => !changed.files.has(file));
38
45
  if (outside.length > 0) {
@@ -6,7 +6,7 @@ export const USAGE = `Usage:
6
6
  quality exceptions migrate [--config <file>] [--from <registry>]
7
7
  quality baseline merge <ancestor> <current> <other>
8
8
  quality baseline install-driver
9
- quality baseline write [--config <file>] [--rule <id>]... [--file <path>]...
9
+ quality baseline write [--config <file>] [--rule <id>]... [--file <path>]... [--first-adoption]
10
10
  quality baseline prune [--config <file>] [--against <ref>]
11
11
  quality baseline tighten [--config <file>] [--staged]
12
12
  quality baseline migrate [--config <file>] [--from <file>]
@@ -25,6 +25,7 @@ exceptions migrate Move legacy registry entries and Biome declarations into qual
25
25
  baseline merge Merge Git baseline versions into <current>: deletions win and counts take the minimum.
26
26
  baseline install-driver Configure only the repository-local merge.quality-baseline.driver setting.
27
27
  baseline write Adopt initial debt once, or record named rules only for --file paths changed since HEAD. Stage new files first.
28
+ --first-adoption records a shared policy upgrade for explicit rules that refuse config exceptions, including unchanged files.
28
29
  baseline prune Drop fixed debt, lower entries to what is left and carry entries to files git saw move. Never adds or raises an entry.
29
30
  baseline tighten Prune only the entries of files changed since HEAD, or with --staged, in the index.
30
31
  baseline migrate Move a JSON or JSON Lines baseline (--from, quality/baseline.json by default) into root and package shards.
@@ -0,0 +1,43 @@
1
+ import type { parseArgs } from "node:util";
2
+
3
+ export const OPTIONS = {
4
+ against: { type: "string" },
5
+ config: { type: "string" },
6
+ coverage: { type: "boolean" },
7
+ file: { multiple: true, type: "string" },
8
+ "first-adoption": { type: "boolean" },
9
+ force: { type: "boolean" },
10
+ from: { type: "string" },
11
+ help: { short: "h", type: "boolean" },
12
+ rule: { multiple: true, type: "string" },
13
+ staged: { type: "boolean" },
14
+ } as const;
15
+
16
+ export type Values = ReturnType<typeof parseArgs<{ options: typeof OPTIONS; allowPositionals: true }>>["values"];
17
+
18
+ type Option = Exclude<keyof Values, "config" | "help">;
19
+
20
+ const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "file", "first-adoption", "force", "from", "rule", "staged"];
21
+
22
+ export const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
23
+ "baseline install-driver": [],
24
+ "baseline migrate": ["from"],
25
+ "baseline prune": ["against"],
26
+ "baseline tighten": ["staged"],
27
+ "baseline write": ["rule", "file", "first-adoption"],
28
+ ci: ["coverage"],
29
+ "exceptions migrate": ["from"],
30
+ fix: ["rule"],
31
+ "hooks install": ["force"],
32
+ "hooks pre-commit": [],
33
+ "hooks status": [],
34
+ "hooks uninstall": [],
35
+ lint: [],
36
+ setup: [],
37
+ };
38
+
39
+ export function misplaced(name: string, values: Values): string | undefined {
40
+ const option = COMMAND_OPTIONS.find((key) => values[key] !== undefined && !(ACCEPTS[name] ?? []).includes(key));
41
+ const owners = Object.keys(ACCEPTS).filter((owner) => option !== undefined && (ACCEPTS[owner] ?? []).includes(option));
42
+ return option === undefined ? undefined : `--${option} applies only to ${owners.join(" and ")}.`;
43
+ }
@@ -46,7 +46,7 @@ export const program = Effect.fn("Cli.program")(function* (args: readonly string
46
46
  case "BaselineInstallDriver":
47
47
  return yield* installDriver(cwd, launch);
48
48
  case "BaselineWrite":
49
- return yield* writeBaseline(cwd, command.config, command.rules, command.files);
49
+ return yield* writeBaseline(cwd, command.config, command.rules, command.files, command.firstAdoption);
50
50
  case "BaselinePrune":
51
51
  return yield* pruneBaseline(cwd, command.config, command.against);
52
52
  case "BaselineTighten":
@@ -1,4 +1,5 @@
1
1
  import { posix } from "node:path";
2
+ import { moduleRoot } from "#naming/moduleRoot.ts";
2
3
  import { isTooling } from "./isTooling.ts";
3
4
  import type { DeclaredRuntime, Runtime } from "./runtime.ts";
4
5
  import { packageOf, type WorkspacePackage } from "./workspace.ts";
@@ -22,7 +23,9 @@ export function classifyRuntime(policy: RuntimePolicy, path: string): Runtime |
22
23
  if (!policy.adopted.has(owner)) {
23
24
  return policy.executable.has(owner) ? "server" : undefined;
24
25
  }
25
- const local = posix.relative(owner, path).replace(/^src\/modules\/[^/]+\//u, "src/");
26
+ const source = posix.relative(owner, path);
27
+ const module = moduleRoot(source);
28
+ const local = module === undefined ? source : `src/${posix.relative(module, source)}`;
26
29
  if (local.startsWith("src/client/")) {
27
30
  return "client";
28
31
  }
@@ -1,7 +1,7 @@
1
- import { statSync } from "node:fs";
2
1
  import { join, posix } from "node:path";
3
- import { Effect } from "effect";
2
+ import { Effect, FileSystem } from "effect";
4
3
  import { readPackageManifest } from "#adapters/manifestInventory.ts";
4
+ import { orWhenAbsent } from "#inventory/filesystem.ts";
5
5
  import type { RuleInputs } from "#rule.ts";
6
6
  import { classifyRuntime } from "./classifyRuntime.ts";
7
7
  import type { WorkspacePackage } from "./workspace.ts";
@@ -29,29 +29,26 @@ function declaredRuntime(manifest: object | undefined): DeclaredRuntime | undefi
29
29
  return value === "client" || value === "server" ? value : undefined;
30
30
  }
31
31
 
32
- function directoryExists(path: string): boolean {
33
- try {
34
- return statSync(path).isDirectory();
35
- } catch (cause) {
36
- if (cause instanceof Error && "code" in cause && (cause.code === "ENOENT" || cause.code === "ENOTDIR")) {
37
- return false;
38
- }
39
- throw cause;
40
- }
41
- }
42
-
43
32
  type Owner = Pick<WorkspacePackage, "directory">;
44
33
 
45
- function runtimeFoldersOf(root: string, owner: Owner): readonly string[] {
46
- return ["client", "server"].filter((folder) => directoryExists(join(root, owner.directory, "src", folder)));
47
- }
34
+ const runtimeFoldersOf = Effect.fn("Imports.runtimeFoldersOf")(function* (root: string, owner: Owner) {
35
+ const fs = yield* FileSystem.FileSystem;
36
+ return yield* Effect.filter(["client", "server"], (folder) => {
37
+ const path = join(root, owner.directory, "src", folder);
38
+ return orWhenAbsent(
39
+ path,
40
+ Effect.map(fs.stat(path), (info) => info.type === "Directory"),
41
+ false,
42
+ );
43
+ });
44
+ });
48
45
 
49
46
  export interface RuntimeDeclarationProblem {
50
47
  readonly directory: string;
51
48
  readonly message: string;
52
49
  }
53
50
 
54
- function problemsFor(root: string, owner: Owner, manifest: object | undefined): readonly RuntimeDeclarationProblem[] {
51
+ const problemsFor = Effect.fn("Imports.problemsFor")(function* (root: string, owner: Owner, manifest: object | undefined) {
55
52
  const value = declaredValue(manifest);
56
53
  if (value === undefined) {
57
54
  return [];
@@ -64,7 +61,7 @@ function problemsFor(root: string, owner: Owner, manifest: object | undefined):
64
61
  },
65
62
  ];
66
63
  }
67
- const folders = runtimeFoldersOf(root, owner);
64
+ const folders = yield* runtimeFoldersOf(root, owner);
68
65
  return folders.length === 0
69
66
  ? []
70
67
  : [
@@ -73,14 +70,14 @@ function problemsFor(root: string, owner: Owner, manifest: object | undefined):
73
70
  message: `"quality.runtime" declares the whole package ${value} code, but it also has ${folders.map((folder) => `src/${folder}/`).join(" and ")}. Keep one convention: remove the declaration and classify code by runtime folders, or move the code out of the runtime folders.`,
74
71
  },
75
72
  ];
76
- }
73
+ });
77
74
 
78
75
  export const runtimeDeclarationProblems = Effect.fn("Imports.runtimeDeclarationProblems")(function* (
79
76
  inputs: RuleInputs,
80
77
  packages: readonly WorkspacePackage[],
81
78
  ) {
82
79
  const problems = yield* Effect.forEach([...packages, { directory: ".", name: "." }], (owner) =>
83
- Effect.map(
80
+ Effect.flatMap(
84
81
  Effect.promise(() => readPackageManifest(inputs.readText, posix.join(owner.directory, "package.json"))),
85
82
  (manifest) => problemsFor(inputs.root, owner, manifest),
86
83
  ),
@@ -98,7 +95,8 @@ export const runtimeOf = Effect.fn("Imports.runtimeOf")(function* (inputs: RuleI
98
95
  ),
99
96
  ),
100
97
  );
101
- const adopted = new Set(owners.filter((owner) => runtimeFoldersOf(inputs.root, owner).length > 0).map((owner) => owner.directory));
98
+ const folders = yield* Effect.filter(owners, (owner) => Effect.map(runtimeFoldersOf(inputs.root, owner), (found) => found.length > 0));
99
+ const adopted = new Set(folders.map((owner) => owner.directory));
102
100
  const declared = new Map(
103
101
  owners.flatMap((owner) => {
104
102
  const runtime = declaredRuntime(manifests.get(owner.directory));
@@ -1,4 +1,5 @@
1
1
  import { posix } from "node:path";
2
+ import { moduleRoot } from "./moduleRoot.ts";
2
3
 
3
4
  export const MIGRATIONS_DIRECTORY = "src/server/migrations";
4
5
  export const MIGRATION_FILE_PATTERN = /^[0-9]{4}_[a-z][a-z0-9]*(?:_[a-z0-9]+)*\.ts$/u;
@@ -6,6 +7,7 @@ export const MIGRATION_FILE_PATTERN = /^[0-9]{4}_[a-z][a-z0-9]*(?:_[a-z0-9]+)*\.
6
7
  export function isMigrationFile(path: string): boolean {
7
8
  const directory = posix.dirname(path);
8
9
  const conventional = directory === MIGRATIONS_DIRECTORY || directory.endsWith(`/${MIGRATIONS_DIRECTORY}`);
9
- const modular = /(?:^|\/)src\/modules\/[^/]+\/server\/migrations$/u.test(directory);
10
+ const root = moduleRoot(path);
11
+ const modular = root !== undefined && directory === `${root}/server/migrations`;
10
12
  return (conventional || modular) && MIGRATION_FILE_PATTERN.test(posix.basename(path));
11
13
  }
@@ -0,0 +1,13 @@
1
+ const RUNTIME = /^(?:client|server|test-support)\//u;
2
+
3
+ export function moduleRoot(path: string): string | undefined {
4
+ const match = /^(?<root>(?:.*\/)?src\/modules\/[^/]+)\/(?<local>.+)$/u.exec(path)?.groups;
5
+ if (match?.root === undefined || match.local === undefined) {
6
+ return undefined;
7
+ }
8
+ if (RUNTIME.test(match.local)) {
9
+ return match.root;
10
+ }
11
+ const separator = match.local.indexOf("/");
12
+ return separator > 0 && RUNTIME.test(match.local.slice(separator + 1)) ? `${match.root}/${match.local.slice(0, separator)}` : undefined;
13
+ }
@@ -1,5 +1,10 @@
1
+ import { join } from "node:path";
1
2
  import ts from "typescript";
2
- import { defineRule, type Finding } from "#rule.ts";
3
+ import { defineRule, type Finding, type RuleInputs } from "#rule.ts";
4
+ import { boundaryCalls } from "#rules/effect/boundaryCalls.ts";
5
+ import { boundaryEntryPoint } from "#rules/effect/boundaryReference.ts";
6
+ import { effectProgram } from "#rules/effect/program.ts";
7
+ import { promiseParameter } from "#rules/effect/promiseParameter.ts";
3
8
  import { parse } from "#rules/parse.ts";
4
9
 
5
10
  function asyncConstruct(node: ts.Node): string | undefined {
@@ -44,32 +49,51 @@ function construct(node: ts.Node): string | undefined {
44
49
  return ts.isThrowStatement(node) ? "throw statement" : asyncConstruct(node);
45
50
  }
46
51
 
47
- export const effectBoundary = defineRule({
48
- check: ({ sources }) =>
49
- sources.flatMap((file) => {
50
- if (/(?:^|\/)(?:adapters|test-support)\//u.test(file.path)) {
51
- return [];
52
- }
53
- const source = parse(file);
54
- const findings: Finding[] = [];
55
- function visit(node: ts.Node): void {
56
- const name = construct(node);
57
- if (name !== undefined && source !== undefined) {
58
- findings.push({
59
- file: file.path,
60
- line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
61
- message: `Uses ${name}. Model the work with Effect; fail with a tagged error (or Effect.die for a defect). Move a bridge to an outside library into an adapters/ folder, returning Effect values.`,
62
- });
63
- }
64
- ts.forEachChild(node, visit);
52
+ function checkBoundary(inputs: RuleInputs): readonly Finding[] {
53
+ const program = effectProgram(inputs, false);
54
+ const checker = program.getTypeChecker();
55
+ const call = boundaryCalls(checker);
56
+ return inputs.sources.flatMap((file) => {
57
+ if (/(?:^|\/)(?:adapters|test-support)\//u.test(file.path)) {
58
+ return [];
59
+ }
60
+ const source = parse(file) === undefined ? undefined : program.getSourceFile(join(inputs.root, file.path));
61
+ const findings: Finding[] = [];
62
+ const entryPoint = source !== undefined && boundaryEntryPoint(file.path, source, checker);
63
+ function visit(node: ts.Node): void {
64
+ const name = construct(node) ?? call(node, entryPoint) ?? promiseParameter(checker, node);
65
+ if (name !== undefined && source !== undefined) {
66
+ findings.push({
67
+ file: file.path,
68
+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
69
+ message: `Uses ${name}. Model the work with Effect; fail with a tagged error (or Effect.die for a defect). Move a bridge to an outside library into an adapters/ folder, returning Effect values.`,
70
+ });
65
71
  }
66
- if (source !== undefined) {
67
- visit(source);
72
+ ts.forEachChild(node, visit);
73
+ }
74
+ if (source !== undefined) {
75
+ visit(source);
76
+ }
77
+ return findings;
78
+ });
79
+ }
80
+
81
+ export const effectBoundary = defineRule({
82
+ check: (inputs) => {
83
+ const groups = new Map<string, RuleInputs["sources"][number][]>();
84
+ for (const source of inputs.sources) {
85
+ if (/(?:^|\/)(?:adapters|test-support)\//u.test(source.path) || !/\.[cm]?[jt]sx?$/u.test(source.path)) {
86
+ continue;
68
87
  }
69
- return findings;
70
- }),
88
+ const group = /^(?:packages|examples)\/[^/]+/u.exec(source.path)?.[0] ?? ".";
89
+ const sources = groups.get(group) ?? [];
90
+ sources.push(source);
91
+ groups.set(group, sources);
92
+ }
93
+ return [...groups.values()].flatMap((sources) => checkBoundary({ ...inputs, sources }));
94
+ },
71
95
  description:
72
- "All checked source, tooling and specs use Effect instead of async, await, new Promise, .then, try or throw. Only adapters/ and test-support/ folders at any depth are exempt. adapters/ bridges outside libraries to Effect; it remains subject to service-parameter and ambient runtime bans. Use tagged errors or Effect.die for defects. Config exceptions and inline suppressions are refused; baseline existing debt.",
96
+ "Use Effect instead of Promise syntax and parameters, synchronous Node IO, throwing helper calls or Effect.sync with throwing APIs. Runners belong at entry points, tool configs and tests. Only adapters/ and test-support/ folders are exempt. Use Effect services and tagged errors; bridge outside libraries in adapters/. No config exceptions or inline suppressions; baseline existing debt.",
73
97
  id: "effect/boundary",
74
98
  registrable: false,
75
99
  });
@@ -0,0 +1,130 @@
1
+ import ts from "typescript";
2
+ import { boundaryReference } from "#rules/effect/boundaryReference.ts";
3
+
4
+ function synchronousIo(reference: string): boolean {
5
+ return /^(?:node:)?fs\.[^.]+Sync$/u.test(reference) || /^(?:node:)?child_process\.(?:execSync|execFileSync|spawnSync)$/u.test(reference);
6
+ }
7
+
8
+ function knownThrowing(reference: string): boolean {
9
+ return (
10
+ (synchronousIo(reference) && !/^(?:node:)?fs\.existsSync$/u.test(reference))
11
+ || /^(?:JSON\.parse|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|BigInt)$/u.test(reference)
12
+ || /^(?:effect\.Schema|effect\/Schema)\.(?:decodeUnknownSync|decodeSync|encodeUnknownSync|encodeSync)$/u.test(reference)
13
+ );
14
+ }
15
+
16
+ function immediateBody(node: ts.Node): ts.ConciseBody | undefined {
17
+ if (!(ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node))) {
18
+ return undefined;
19
+ }
20
+ if (
21
+ node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)
22
+ || ("asteriskToken" in node && node.asteriskToken !== undefined)
23
+ ) {
24
+ return undefined;
25
+ }
26
+ return node.body;
27
+ }
28
+
29
+ function functionBody(checker: ts.TypeChecker, expression: ts.Expression): ts.ConciseBody | undefined {
30
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) {
31
+ return immediateBody(expression);
32
+ }
33
+ const symbol = checker.getSymbolAtLocation(expression);
34
+ const target = symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
35
+ for (const declaration of target?.declarations ?? []) {
36
+ if (declaration.getSourceFile().isDeclarationFile || /(?:^|\/)node_modules\//u.test(declaration.getSourceFile().fileName)) {
37
+ continue;
38
+ }
39
+ if (ts.isVariableDeclaration(declaration) && declaration.initializer !== undefined) {
40
+ return functionBody(checker, declaration.initializer);
41
+ }
42
+ const body = immediateBody(declaration);
43
+ if (body !== undefined) {
44
+ return body;
45
+ }
46
+ }
47
+ return undefined;
48
+ }
49
+
50
+ function runnerReference(node: ts.Node): ts.Node | undefined {
51
+ if (ts.isCallExpression(node)) {
52
+ return ts.isIdentifier(node.expression) ? node.expression : undefined;
53
+ }
54
+ if (!ts.isIdentifier(node)) {
55
+ return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? node : undefined;
56
+ }
57
+ const parent = node.parent;
58
+ if (ts.isCallExpression(parent) && parent.expression === node) {
59
+ return undefined;
60
+ }
61
+ return "name" in parent && parent.name === node && !ts.isShorthandPropertyAssignment(parent) ? undefined : node;
62
+ }
63
+
64
+ export function boundaryCalls(checker: ts.TypeChecker) {
65
+ const throwing = new Map<ts.Node, boolean>();
66
+ function throws(body: ts.Node): boolean {
67
+ const previous = throwing.get(body);
68
+ if (previous !== undefined) {
69
+ return previous;
70
+ }
71
+ function visit(node: ts.Node): boolean {
72
+ return ts.isThrowStatement(node) || (!ts.isFunctionLike(node) && (ts.forEachChild(node, visit) ?? false));
73
+ }
74
+ const result = visit(body);
75
+ throwing.set(body, result);
76
+ return result;
77
+ }
78
+ function guard(call: ts.CallExpression): boolean {
79
+ const body = functionBody(checker, call.expression);
80
+ return body !== undefined && throws(body);
81
+ }
82
+ function unsafeSync(call: ts.CallExpression): boolean {
83
+ const callback = call.arguments[0];
84
+ const body = callback === undefined ? undefined : functionBody(checker, callback);
85
+ if (body === undefined) {
86
+ return callback !== undefined && knownThrowing(boundaryReference(checker, callback) ?? "");
87
+ }
88
+ function visit(node: ts.Node): boolean {
89
+ if (ts.isFunctionLike(node)) {
90
+ return false;
91
+ }
92
+ if (ts.isThrowStatement(node)) {
93
+ return true;
94
+ }
95
+ if (ts.isCallExpression(node) && (knownThrowing(boundaryReference(checker, node.expression) ?? "") || guard(node))) {
96
+ return true;
97
+ }
98
+ return ts.forEachChild(node, visit) ?? false;
99
+ }
100
+ return visit(body);
101
+ }
102
+ function runner(node: ts.Node, entryPoint: boolean): string | undefined {
103
+ if (entryPoint) {
104
+ return undefined;
105
+ }
106
+ const expression = runnerReference(node);
107
+ if (expression === undefined) {
108
+ return undefined;
109
+ }
110
+ const reference = boundaryReference(checker, expression);
111
+ return /^effect(?:\.Effect|\/Effect)\.run/u.test(reference ?? "") ? `${reference} outside an entry point` : undefined;
112
+ }
113
+ return (node: ts.Node, entryPoint: boolean): string | undefined => {
114
+ const runtime = runner(node, entryPoint);
115
+ if (runtime !== undefined) {
116
+ return runtime;
117
+ }
118
+ if (!ts.isCallExpression(node)) {
119
+ return undefined;
120
+ }
121
+ const reference = boundaryReference(checker, node.expression) ?? "";
122
+ if (synchronousIo(reference)) {
123
+ return `synchronous IO (${reference})`;
124
+ }
125
+ if (/^effect(?:\.Effect|\/Effect)\.sync$/u.test(reference) && unsafeSync(node)) {
126
+ return "Effect.sync with a throwing body";
127
+ }
128
+ return guard(node) ? `throwing helper call (${node.expression.getText()})` : undefined;
129
+ };
130
+ }
@@ -0,0 +1,85 @@
1
+ import ts from "typescript";
2
+
3
+ function importedReference(declaration: ts.Declaration): string | undefined {
4
+ if (ts.isImportSpecifier(declaration)) {
5
+ const module = declaration.parent.parent.parent.moduleSpecifier;
6
+ return ts.isStringLiteral(module) ? `${module.text}.${(declaration.propertyName ?? declaration.name).text}` : undefined;
7
+ }
8
+ if (ts.isNamespaceImport(declaration) || ts.isImportClause(declaration)) {
9
+ const module = ts.isNamespaceImport(declaration) ? declaration.parent.parent.moduleSpecifier : declaration.parent.moduleSpecifier;
10
+ return ts.isStringLiteral(module) ? module.text : undefined;
11
+ }
12
+ return undefined;
13
+ }
14
+
15
+ function memberName(node: ts.PropertyAccessExpression | ts.ElementAccessExpression): string | undefined {
16
+ if (ts.isPropertyAccessExpression(node)) {
17
+ return node.name.text;
18
+ }
19
+ return ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text : undefined;
20
+ }
21
+
22
+ function bindingReference(checker: ts.TypeChecker, declaration: ts.Declaration, seen: Set<ts.Symbol>): string | undefined {
23
+ if (!(ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent))) {
24
+ return undefined;
25
+ }
26
+ const variable = declaration.parent.parent;
27
+ const name = declaration.propertyName ?? declaration.name;
28
+ if (!ts.isVariableDeclaration(variable) || variable.initializer === undefined || !(ts.isIdentifier(name) || ts.isStringLiteral(name))) {
29
+ return undefined;
30
+ }
31
+ const owner = boundaryReference(checker, variable.initializer, seen);
32
+ return owner === undefined ? undefined : `${owner}.${name.text}`;
33
+ }
34
+
35
+ function symbolReference(checker: ts.TypeChecker, node: ts.Identifier, seen: Set<ts.Symbol>): string | undefined {
36
+ const symbol = checker.getSymbolAtLocation(node);
37
+ if (symbol === undefined) {
38
+ return node.text;
39
+ }
40
+ if (seen.has(symbol)) {
41
+ return undefined;
42
+ }
43
+ seen.add(symbol);
44
+ for (const declaration of symbol.declarations ?? []) {
45
+ if (ts.isVariableDeclaration(declaration) && declaration.initializer !== undefined) {
46
+ return boundaryReference(checker, declaration.initializer, seen);
47
+ }
48
+ const imported = importedReference(declaration) ?? bindingReference(checker, declaration, seen);
49
+ if (imported !== undefined) {
50
+ return imported;
51
+ }
52
+ }
53
+ return symbol.declarations?.some((declaration) => !declaration.getSourceFile().isDeclarationFile) ? undefined : node.text;
54
+ }
55
+
56
+ export function boundaryReference(checker: ts.TypeChecker, node: ts.Node, seen = new Set<ts.Symbol>()): string | undefined {
57
+ if (ts.isParenthesizedExpression(node)) {
58
+ return boundaryReference(checker, node.expression, seen);
59
+ }
60
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
61
+ const member = memberName(node);
62
+ const owner = boundaryReference(checker, node.expression, seen);
63
+ return owner === undefined || member === undefined ? undefined : `${owner}.${member}`;
64
+ }
65
+ return ts.isIdentifier(node) ? symbolReference(checker, node, seen) : undefined;
66
+ }
67
+
68
+ export function boundaryEntryPoint(path: string, source: ts.SourceFile, checker: ts.TypeChecker): boolean {
69
+ if (/(?:^|\/)(?:cli|main|[^/]+-cli)\.[cm]?[jt]sx?$|\.(?:config|test|spec)\.[cm]?[jt]sx?$/u.test(path)) {
70
+ return true;
71
+ }
72
+ function visit(node: ts.Node): boolean {
73
+ if (ts.isCallExpression(node)) {
74
+ const reference = boundaryReference(checker, node.expression);
75
+ if (reference?.endsWith(".runMain") || (ts.isIdentifier(node.expression) && node.expression.text === "runMain")) {
76
+ return true;
77
+ }
78
+ }
79
+ if (ts.isBinaryExpression(node) && node.getText(source).replace(/\s/gu, "") === "fileURLToPath(import.meta.url)===process.argv[1]") {
80
+ return true;
81
+ }
82
+ return ts.forEachChild(node, visit) ?? false;
83
+ }
84
+ return visit(source);
85
+ }
@@ -3,7 +3,7 @@ import ts from "typescript";
3
3
  import { projectsFor } from "#imports/projects.ts";
4
4
  import type { RuleInputs } from "#rule.ts";
5
5
 
6
- export function effectProgram(inputs: RuleInputs): ts.Program {
6
+ export function effectProgram(inputs: RuleInputs, externalTypes = true): ts.Program {
7
7
  const projectOf = projectsFor(inputs.root);
8
8
  const options: ts.CompilerOptions = {
9
9
  allowJs: true,
@@ -19,6 +19,9 @@ export function effectProgram(inputs: RuleInputs): ts.Program {
19
19
  host.readFile = (path) => texts.get(path) ?? read(path);
20
20
  host.resolveModuleNames = (names, from) =>
21
21
  names.map((name) => {
22
+ if (!(externalTypes || name.startsWith(".") || name.startsWith("#") || name.startsWith("@shivaedev/"))) {
23
+ return undefined;
24
+ }
22
25
  const project = projectOf(from);
23
26
  return ts.resolveModuleName(name, from, project.typesOptions, host, project.typesCache).resolvedModule;
24
27
  });