@shivaedev/quality 0.49.0 → 0.51.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 (103) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +20 -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/config/resolve.d.ts.map +1 -1
  22. package/dist/config/resolve.js +9 -6
  23. package/dist/config/resolve.js.map +1 -1
  24. package/dist/imports/classifyRuntime.d.ts.map +1 -1
  25. package/dist/imports/classifyRuntime.js +4 -1
  26. package/dist/imports/classifyRuntime.js.map +1 -1
  27. package/dist/imports/runtime.d.ts +6 -3
  28. package/dist/imports/runtime.d.ts.map +1 -1
  29. package/dist/imports/runtime.js +15 -21
  30. package/dist/imports/runtime.js.map +1 -1
  31. package/dist/naming/migrationFile.d.ts.map +1 -1
  32. package/dist/naming/migrationFile.js +3 -1
  33. package/dist/naming/migrationFile.js.map +1 -1
  34. package/dist/naming/moduleRoot.d.ts +2 -0
  35. package/dist/naming/moduleRoot.d.ts.map +1 -0
  36. package/dist/naming/moduleRoot.js +13 -0
  37. package/dist/naming/moduleRoot.js.map +1 -0
  38. package/dist/rules/builtIn.d.ts +2 -2
  39. package/dist/rules/builtIn.d.ts.map +1 -1
  40. package/dist/rules/builtIn.js +2 -0
  41. package/dist/rules/builtIn.js.map +1 -1
  42. package/dist/rules/effect/boundary.d.ts.map +1 -1
  43. package/dist/rules/effect/boundary.js +30 -6
  44. package/dist/rules/effect/boundary.js.map +1 -1
  45. package/dist/rules/effect/boundaryCalls.d.ts +3 -0
  46. package/dist/rules/effect/boundaryCalls.d.ts.map +1 -0
  47. package/dist/rules/effect/boundaryCalls.js +121 -0
  48. package/dist/rules/effect/boundaryCalls.js.map +1 -0
  49. package/dist/rules/effect/boundaryReference.d.ts +4 -0
  50. package/dist/rules/effect/boundaryReference.d.ts.map +1 -0
  51. package/dist/rules/effect/boundaryReference.js +80 -0
  52. package/dist/rules/effect/boundaryReference.js.map +1 -0
  53. package/dist/rules/effect/failureFindings.d.ts +8 -0
  54. package/dist/rules/effect/failureFindings.d.ts.map +1 -0
  55. package/dist/rules/effect/failureFindings.js +47 -0
  56. package/dist/rules/effect/failureFindings.js.map +1 -0
  57. package/dist/rules/effect/failureHonesty.d.ts +2 -0
  58. package/dist/rules/effect/failureHonesty.d.ts.map +1 -0
  59. package/dist/rules/effect/failureHonesty.js +53 -0
  60. package/dist/rules/effect/failureHonesty.js.map +1 -0
  61. package/dist/rules/effect/failureOperations.d.ts +9 -0
  62. package/dist/rules/effect/failureOperations.d.ts.map +1 -0
  63. package/dist/rules/effect/failureOperations.js +55 -0
  64. package/dist/rules/effect/failureOperations.js.map +1 -0
  65. package/dist/rules/effect/program.d.ts +1 -1
  66. package/dist/rules/effect/program.d.ts.map +1 -1
  67. package/dist/rules/effect/program.js +4 -1
  68. package/dist/rules/effect/program.js.map +1 -1
  69. package/dist/rules/effect/promiseParameter.d.ts +3 -0
  70. package/dist/rules/effect/promiseParameter.d.ts.map +1 -0
  71. package/dist/rules/effect/promiseParameter.js +24 -0
  72. package/dist/rules/effect/promiseParameter.js.map +1 -0
  73. package/dist/rules/effect/successRecovery.d.ts +3 -0
  74. package/dist/rules/effect/successRecovery.d.ts.map +1 -0
  75. package/dist/rules/effect/successRecovery.js +43 -0
  76. package/dist/rules/effect/successRecovery.js.map +1 -0
  77. package/dist/rules/imports/runtime.d.ts +1 -1
  78. package/dist/rules/imports/runtime.d.ts.map +1 -1
  79. package/dist/rules/stories/groupedOutcomes.js +1 -1
  80. package/dist/rules/stories/groupedOutcomes.js.map +1 -1
  81. package/docs/debt-and-hooks.md +3 -1
  82. package/package.json +2 -2
  83. package/src/cli/args.ts +15 -43
  84. package/src/cli/baseline.ts +9 -2
  85. package/src/cli/messages.ts +2 -1
  86. package/src/cli/options.ts +43 -0
  87. package/src/cli/program.ts +1 -1
  88. package/src/config/resolve.ts +4 -6
  89. package/src/imports/classifyRuntime.ts +4 -1
  90. package/src/imports/runtime.ts +19 -21
  91. package/src/naming/migrationFile.ts +3 -1
  92. package/src/naming/moduleRoot.ts +13 -0
  93. package/src/rules/builtIn.ts +2 -0
  94. package/src/rules/effect/boundary.ts +48 -24
  95. package/src/rules/effect/boundaryCalls.ts +130 -0
  96. package/src/rules/effect/boundaryReference.ts +85 -0
  97. package/src/rules/effect/failureFindings.ts +55 -0
  98. package/src/rules/effect/failureHonesty.ts +59 -0
  99. package/src/rules/effect/failureOperations.ts +66 -0
  100. package/src/rules/effect/program.ts +4 -1
  101. package/src/rules/effect/promiseParameter.ts +26 -0
  102. package/src/rules/effect/successRecovery.ts +44 -0
  103. package/src/rules/stories/groupedOutcomes.ts +1 -1
@@ -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
+ }
@@ -8,6 +8,7 @@ import { noTodo } from "#rules/comments/noTodo.ts";
8
8
  import { docsReferences } from "#rules/docs/references.ts";
9
9
  import { docsUnversionedInstalls } from "#rules/docs/unversionedInstalls.ts";
10
10
  import { effectBoundary } from "#rules/effect/boundary.ts";
11
+ import { failureHonesty } from "#rules/effect/failureHonesty.ts";
11
12
  import { serviceParameters } from "#rules/effect/serviceParameters.ts";
12
13
  import { distinctCase } from "#rules/files/distinctCase.ts";
13
14
  import { folderNames } from "#rules/files/folderNames.ts";
@@ -55,6 +56,7 @@ import { unusedCode } from "./unusedCode.ts";
55
56
  export const builtInRules = [
56
57
  unusedCode,
57
58
  effectBoundary,
59
+ failureHonesty,
58
60
  serviceParameters,
59
61
  jsxConditionals,
60
62
  maxLines,
@@ -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
+ }
@@ -0,0 +1,55 @@
1
+ import ts from "typescript";
2
+ import { effectName, type FailureOperation, failureOperations, fileSystemCall } from "./failureOperations.ts";
3
+ import { successRecovery } from "./successRecovery.ts";
4
+
5
+ interface FailureFinding {
6
+ readonly message: string;
7
+ readonly node: ts.Node;
8
+ }
9
+
10
+ function unboundedRetry(node: ts.CallExpression): boolean {
11
+ const options = node.arguments.at(-1);
12
+ if (options === undefined || !ts.isObjectLiteralExpression(options)) {
13
+ return false;
14
+ }
15
+ const names = options.properties.flatMap((property) => (property.name === undefined ? [] : [property.name.getText().replaceAll(/["']/gu, "")]));
16
+ return names.includes("while") && !names.includes("times") && !names.includes("schedule") && !options.properties.some(ts.isSpreadAssignment);
17
+ }
18
+
19
+ function operationFailure(checker: ts.TypeChecker, operation: FailureOperation, before: readonly FailureOperation[]): string | undefined {
20
+ if (["option", "orElseSucceed"].includes(operation.name) && before.some((part) => fileSystemCall(checker, part.node))) {
21
+ return "FileSystem failure becomes absence or success. Catch a named reason such as NotFound, re-fail other errors, or return an explicit unavailable state.";
22
+ }
23
+ if (/^fork(?:Scoped|In|Detach|Daemon|Child)?$/u.test(operation.name)) {
24
+ const names = before.map((part) => part.name);
25
+ const forever = names.indexOf("forever");
26
+ if (forever !== -1 && names.indexOf("orDie", forever + 1) !== -1) {
27
+ return "Forked forever loop dies on failure. Catch a named reason within each iteration with a Schedule-bounded retry, or expose an explicit unavailable state and supervise termination.";
28
+ }
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ export function failureFindings(checker: ts.TypeChecker, node: ts.CallExpression): readonly FailureFinding[] {
34
+ const findings: FailureFinding[] = [];
35
+ const name = effectName(checker, node.expression);
36
+ if (name === "retry" && unboundedRetry(node)) {
37
+ findings.push({ message: "Retry has while without times or schedule. Use a Schedule-bounded retry and preserve the final typed failure.", node });
38
+ }
39
+ const handler = node.arguments.at(-1);
40
+ if (["catch", "catchAll", "catchCause", "catchAllCause"].includes(name ?? "") && handler !== undefined && successRecovery(checker, handler)) {
41
+ findings.push({
42
+ message:
43
+ "Catch turns every failure into success. Catch a named reason with catchTag or catchIf and re-fail the rest, or model an explicit unavailable state.",
44
+ node,
45
+ });
46
+ }
47
+ const operations = failureOperations(checker, node);
48
+ for (const [index, operation] of operations.entries()) {
49
+ const message = operationFailure(checker, operation, operations.slice(0, index));
50
+ if (message !== undefined) {
51
+ findings.push({ message, node: operation.node });
52
+ }
53
+ }
54
+ return findings;
55
+ }
@@ -0,0 +1,59 @@
1
+ import { join } from "node:path";
2
+ import ts from "typescript";
3
+ import { defineRule, type Finding, type RuleInputs } from "#rule.ts";
4
+ import { failureFindings } from "./failureFindings.ts";
5
+ import { effectProgram } from "./program.ts";
6
+
7
+ function checkFailures(inputs: RuleInputs): readonly Finding[] {
8
+ const program = effectProgram(inputs, false);
9
+ const checker = program.getTypeChecker();
10
+ return inputs.sources.flatMap((file) => {
11
+ const source = program.getSourceFile(join(inputs.root, file.path));
12
+ const findings: Finding[] = [];
13
+ const reported = new Set<string>();
14
+ function report(node: ts.Node, message: string): void {
15
+ const key = `${node.pos}:${message}`;
16
+ if (source !== undefined && !reported.has(key)) {
17
+ reported.add(key);
18
+ findings.push({ file: file.path, line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1, message });
19
+ }
20
+ }
21
+ function visit(node: ts.Node): void {
22
+ if (ts.isCallExpression(node)) {
23
+ for (const finding of failureFindings(checker, node)) {
24
+ report(finding.node, finding.message);
25
+ }
26
+ }
27
+ ts.forEachChild(node, visit);
28
+ }
29
+ if (source !== undefined) {
30
+ visit(source);
31
+ }
32
+ return findings;
33
+ });
34
+ }
35
+
36
+ export const failureHonesty = defineRule({
37
+ check: (inputs) => {
38
+ const groups = new Map<string, RuleInputs["sources"][number][]>();
39
+ for (const source of inputs.sources) {
40
+ if (
41
+ !(
42
+ /\.[cm]?[jt]sx?$/u.test(source.path)
43
+ && /\b(?:catch|catchAll|catchCause|catchAllCause|retry|forever|option|orElseSucceed)\b/u.test(source.text)
44
+ )
45
+ ) {
46
+ continue;
47
+ }
48
+ const group = /^(?:packages|examples)\/[^/]+/u.exec(source.path)?.[0] ?? ".";
49
+ const sources = groups.get(group) ?? [];
50
+ sources.push(source);
51
+ groups.set(group, sources);
52
+ }
53
+ return [...groups.values()].flatMap((sources) => checkFailures({ ...inputs, sources }));
54
+ },
55
+ description:
56
+ "Keep failures typed and observable: no forked forever/orDie loops, retry({ while }) without a bound, blanket catch-to-success, or FileSystem option/orElseSucceed. Catch a named reason, use a Schedule-bounded retry or model an explicit unavailable state. No config exceptions or inline suppressions; baseline existing debt.",
57
+ id: "effect/failure-honesty",
58
+ registrable: false,
59
+ });
@@ -0,0 +1,66 @@
1
+ import ts from "typescript";
2
+ import { boundaryReference } from "./boundaryReference.ts";
3
+
4
+ export interface FailureOperation {
5
+ readonly name: string;
6
+ readonly node: ts.Node;
7
+ }
8
+
9
+ export function effectName(checker: ts.TypeChecker, node: ts.Node): string | undefined {
10
+ return /^effect(?:\.Effect|\/Effect)\.(?<name>\w+)$/u.exec(boundaryReference(checker, node) ?? "")?.groups?.name;
11
+ }
12
+
13
+ export function failureOperations(checker: ts.TypeChecker, node: ts.Node, seen = new Set<ts.Symbol>()): FailureOperation[] {
14
+ if (ts.isParenthesizedExpression(node)) {
15
+ return failureOperations(checker, node.expression, seen);
16
+ }
17
+ if (ts.isIdentifier(node)) {
18
+ const symbol = checker.getSymbolAtLocation(node);
19
+ if (symbol !== undefined && !seen.has(symbol)) {
20
+ seen.add(symbol);
21
+ const declaration = symbol.valueDeclaration;
22
+ if (declaration !== undefined && ts.isVariableDeclaration(declaration) && declaration.initializer !== undefined) {
23
+ return failureOperations(checker, declaration.initializer, seen);
24
+ }
25
+ }
26
+ }
27
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "pipe") {
28
+ return [
29
+ failureOperations(checker, node.expression.expression, seen),
30
+ ...node.arguments.map((part) => failureOperations(checker, part, new Set(seen))),
31
+ ].flat();
32
+ }
33
+ const name = effectName(checker, ts.isCallExpression(node) ? node.expression : node);
34
+ if (name === undefined) {
35
+ return [{ name: "source", node }];
36
+ }
37
+ const args = ts.isCallExpression(node) ? node.arguments : [];
38
+ const first = args[0];
39
+ return [...(first === undefined ? [] : failureOperations(checker, first, seen)), { name, node }];
40
+ }
41
+
42
+ function fileSystemService(checker: ts.TypeChecker, node: ts.Node, seen = new Set<ts.Symbol>()): boolean {
43
+ if (/^effect(?:\.FileSystem|\/FileSystem)\.FileSystem$/u.test(boundaryReference(checker, node) ?? "")) {
44
+ return true;
45
+ }
46
+ if (ts.isYieldExpression(node) || ts.isParenthesizedExpression(node)) {
47
+ return node.expression !== undefined && fileSystemService(checker, node.expression, seen);
48
+ }
49
+ const symbol = checker.getSymbolAtLocation(node);
50
+ if (symbol === undefined || seen.has(symbol)) {
51
+ return false;
52
+ }
53
+ seen.add(symbol);
54
+ return (symbol.declarations ?? []).some(
55
+ (declaration) =>
56
+ ts.isVariableDeclaration(declaration) && declaration.initializer !== undefined && fileSystemService(checker, declaration.initializer, seen),
57
+ );
58
+ }
59
+
60
+ export function fileSystemCall(checker: ts.TypeChecker, node: ts.Node): boolean {
61
+ if (!ts.isCallExpression(node)) {
62
+ return false;
63
+ }
64
+ const callee = node.expression;
65
+ return (ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee)) && fileSystemService(checker, callee.expression);
66
+ }
@@ -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
  });
@@ -0,0 +1,26 @@
1
+ import ts from "typescript";
2
+
3
+ export function promiseParameter(checker: ts.TypeChecker, node: ts.Node): string | undefined {
4
+ if (!ts.isParameter(node)) {
5
+ return undefined;
6
+ }
7
+ const seen = new Set<ts.Type>();
8
+ function carries(type: ts.Type): boolean {
9
+ if (seen.has(type)) {
10
+ return false;
11
+ }
12
+ seen.add(type);
13
+ if (["Promise", "PromiseLike"].includes(type.getSymbol()?.name ?? "")) {
14
+ return true;
15
+ }
16
+ if (type.isUnionOrIntersection()) {
17
+ return type.types.some(carries);
18
+ }
19
+ const constraint = checker.getBaseConstraintOfType(type);
20
+ return (
21
+ (constraint !== undefined && carries(constraint))
22
+ || type.getCallSignatures().some((signature) => carries(checker.getReturnTypeOfSignature(signature)))
23
+ );
24
+ }
25
+ return carries(checker.getTypeAtLocation(node)) ? `Promise-typed parameter (${node.name.getText()})` : undefined;
26
+ }