@shivaedev/quality 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/README.md +127 -1
  4. package/dist/baseline/compare.d.ts +26 -0
  5. package/dist/baseline/compare.d.ts.map +1 -0
  6. package/dist/baseline/compare.js +42 -0
  7. package/dist/baseline/compare.js.map +1 -0
  8. package/dist/baseline/format.d.ts +13 -0
  9. package/dist/baseline/format.d.ts.map +1 -0
  10. package/dist/baseline/format.js +32 -0
  11. package/dist/baseline/format.js.map +1 -0
  12. package/dist/baseline/update.d.ts +24 -0
  13. package/dist/baseline/update.d.ts.map +1 -0
  14. package/dist/baseline/update.js +60 -0
  15. package/dist/baseline/update.js.map +1 -0
  16. package/dist/cli/args.d.ts +25 -0
  17. package/dist/cli/args.d.ts.map +1 -0
  18. package/dist/cli/args.js +64 -0
  19. package/dist/cli/args.js.map +1 -0
  20. package/dist/cli/baseline.d.ts +5 -0
  21. package/dist/cli/baseline.d.ts.map +1 -0
  22. package/dist/cli/baseline.js +37 -0
  23. package/dist/cli/baseline.js.map +1 -0
  24. package/dist/cli/lint.d.ts +5 -0
  25. package/dist/cli/lint.d.ts.map +1 -0
  26. package/dist/cli/lint.js +20 -0
  27. package/dist/cli/lint.js.map +1 -0
  28. package/dist/cli/run-main.d.ts +3 -0
  29. package/dist/cli/run-main.d.ts.map +1 -0
  30. package/dist/cli/run-main.js +24 -0
  31. package/dist/cli/run-main.js.map +1 -0
  32. package/dist/cli.d.ts +3 -0
  33. package/dist/cli.d.ts.map +1 -0
  34. package/dist/cli.js +27 -0
  35. package/dist/cli.js.map +1 -0
  36. package/dist/config/decode.d.ts +19 -0
  37. package/dist/config/decode.d.ts.map +1 -0
  38. package/dist/config/decode.js +25 -0
  39. package/dist/config/decode.js.map +1 -0
  40. package/dist/config/load.d.ts +13 -0
  41. package/dist/config/load.d.ts.map +1 -0
  42. package/dist/config/load.js +47 -0
  43. package/dist/config/load.js.map +1 -0
  44. package/dist/config/resolve.d.ts +11 -0
  45. package/dist/config/resolve.d.ts.map +1 -0
  46. package/dist/config/resolve.js +31 -0
  47. package/dist/config/resolve.js.map +1 -0
  48. package/dist/config.d.ts +31 -0
  49. package/dist/config.d.ts.map +1 -0
  50. package/dist/config.js +2 -0
  51. package/dist/config.js.map +1 -0
  52. package/dist/decoded.d.ts +13 -0
  53. package/dist/decoded.d.ts.map +1 -0
  54. package/dist/decoded.js +11 -0
  55. package/dist/decoded.js.map +1 -0
  56. package/dist/engine/evaluate.d.ts +18 -0
  57. package/dist/engine/evaluate.d.ts.map +1 -0
  58. package/dist/engine/evaluate.js +20 -0
  59. package/dist/engine/evaluate.js.map +1 -0
  60. package/dist/engine/run-rules.d.ts +12 -0
  61. package/dist/engine/run-rules.d.ts.map +1 -0
  62. package/dist/engine/run-rules.js +19 -0
  63. package/dist/engine/run-rules.js.map +1 -0
  64. package/dist/engine/session.d.ts +19 -0
  65. package/dist/engine/session.d.ts.map +1 -0
  66. package/dist/engine/session.js +25 -0
  67. package/dist/engine/session.js.map +1 -0
  68. package/dist/engine/violation.d.ts +12 -0
  69. package/dist/engine/violation.d.ts.map +1 -0
  70. package/dist/engine/violation.js +23 -0
  71. package/dist/engine/violation.js.map +1 -0
  72. package/dist/exceptions/registry.d.ts +24 -0
  73. package/dist/exceptions/registry.d.ts.map +1 -0
  74. package/dist/exceptions/registry.js +33 -0
  75. package/dist/exceptions/registry.js.map +1 -0
  76. package/dist/failure.d.ts +21 -0
  77. package/dist/failure.d.ts.map +1 -0
  78. package/dist/failure.js +12 -0
  79. package/dist/failure.js.map +1 -0
  80. package/dist/index.d.ts +6 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +3 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/inventory/collect.d.ts +15 -0
  85. package/dist/inventory/collect.d.ts.map +1 -0
  86. package/dist/inventory/collect.js +34 -0
  87. package/dist/inventory/collect.js.map +1 -0
  88. package/dist/inventory/filesystem.d.ts +16 -0
  89. package/dist/inventory/filesystem.d.ts.map +1 -0
  90. package/dist/inventory/filesystem.js +26 -0
  91. package/dist/inventory/filesystem.js.map +1 -0
  92. package/dist/inventory/ignore-scope.d.ts +17 -0
  93. package/dist/inventory/ignore-scope.d.ts.map +1 -0
  94. package/dist/inventory/ignore-scope.js +26 -0
  95. package/dist/inventory/ignore-scope.js.map +1 -0
  96. package/dist/inventory/walk.d.ts +8 -0
  97. package/dist/inventory/walk.d.ts.map +1 -0
  98. package/dist/inventory/walk.js +38 -0
  99. package/dist/inventory/walk.js.map +1 -0
  100. package/dist/report/plural.d.ts +2 -0
  101. package/dist/report/plural.d.ts.map +1 -0
  102. package/dist/report/plural.js +2 -0
  103. package/dist/report/plural.js.map +1 -0
  104. package/dist/report/render.d.ts +11 -0
  105. package/dist/report/render.d.ts.map +1 -0
  106. package/dist/report/render.js +55 -0
  107. package/dist/report/render.js.map +1 -0
  108. package/dist/report/stale.d.ts +8 -0
  109. package/dist/report/stale.d.ts.map +1 -0
  110. package/dist/report/stale.js +9 -0
  111. package/dist/report/stale.js.map +1 -0
  112. package/dist/rule.d.ts +56 -0
  113. package/dist/rule.d.ts.map +1 -0
  114. package/dist/rule.js +23 -0
  115. package/dist/rule.js.map +1 -0
  116. package/dist/rules/built-in.d.ts +6 -0
  117. package/dist/rules/built-in.d.ts.map +1 -0
  118. package/dist/rules/built-in.js +3 -0
  119. package/dist/rules/built-in.js.map +1 -0
  120. package/dist/rules/max-lines.d.ts +6 -0
  121. package/dist/rules/max-lines.d.ts.map +1 -0
  122. package/dist/rules/max-lines.js +26 -0
  123. package/dist/rules/max-lines.js.map +1 -0
  124. package/dist/standard-schema.d.ts +25 -0
  125. package/dist/standard-schema.d.ts.map +1 -0
  126. package/dist/standard-schema.js +3 -0
  127. package/dist/standard-schema.js.map +1 -0
  128. package/package.json +53 -4
  129. package/src/baseline/compare.ts +81 -0
  130. package/src/baseline/format.ts +53 -0
  131. package/src/baseline/update.ts +83 -0
  132. package/src/cli/args.ts +81 -0
  133. package/src/cli/baseline.ts +52 -0
  134. package/src/cli/lint.ts +27 -0
  135. package/src/cli/run-main.ts +29 -0
  136. package/src/cli.ts +29 -0
  137. package/src/config/decode.ts +35 -0
  138. package/src/config/load.ts +58 -0
  139. package/src/config/resolve.ts +60 -0
  140. package/src/config.ts +33 -0
  141. package/src/decoded.ts +15 -0
  142. package/src/engine/evaluate.ts +39 -0
  143. package/src/engine/run-rules.ts +40 -0
  144. package/src/engine/session.ts +40 -0
  145. package/src/engine/violation.ts +35 -0
  146. package/src/exceptions/registry.ts +58 -0
  147. package/src/failure.ts +13 -0
  148. package/src/index.ts +5 -0
  149. package/src/inventory/collect.ts +53 -0
  150. package/src/inventory/filesystem.ts +47 -0
  151. package/src/inventory/ignore-scope.ts +44 -0
  152. package/src/inventory/walk.ts +58 -0
  153. package/src/report/plural.ts +1 -0
  154. package/src/report/render.ts +85 -0
  155. package/src/report/stale.ts +30 -0
  156. package/src/rule.ts +90 -0
  157. package/src/rules/built-in.ts +3 -0
  158. package/src/rules/max-lines.ts +31 -0
  159. package/src/standard-schema.ts +22 -0
@@ -0,0 +1,58 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { Effect, FileSystem } from "effect";
4
+ import { validOrFail } from "../decoded.ts";
5
+ import { SetupFailure } from "../failure.ts";
6
+ import type { InventoryScope } from "../inventory/collect.ts";
7
+ import { type ConfigInput, decodeConfig } from "./decode.ts";
8
+ import { type ResolvedRules, resolveRules } from "./resolve.ts";
9
+
10
+ export const CONFIG_FILE = "quality.config.ts";
11
+
12
+ const DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
13
+
14
+ export interface ResolvedConfig extends ResolvedRules, InventoryScope {
15
+ readonly root: string;
16
+ readonly file: string;
17
+ readonly registry: string;
18
+ readonly baseline: string;
19
+ }
20
+
21
+ const messageOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
22
+
23
+ const importDefault = (file: string): Effect.Effect<unknown, SetupFailure> =>
24
+ Effect.flatMap(
25
+ Effect.tryPromise({
26
+ try: async (): Promise<unknown> => import(pathToFileURL(file).href),
27
+ catch: (cause) => new SetupFailure({ message: `cannot load ${file}: ${messageOf(cause)}` }),
28
+ }),
29
+ (loaded) =>
30
+ typeof loaded === "object" && loaded !== null && "default" in loaded
31
+ ? Effect.succeed(loaded.default)
32
+ : Effect.fail(new SetupFailure({ message: `${file} has no default export. Export defineConfig({ ... }) as the default.` })),
33
+ );
34
+
35
+ const resolved = (root: string, file: string, config: ConfigInput, rules: ResolvedRules): ResolvedConfig => ({
36
+ ...rules,
37
+ baseline: config.baseline ?? "quality/baseline.json",
38
+ exclude: config.exclude ?? [],
39
+ extensions: config.extensions ?? DEFAULT_EXTENSIONS,
40
+ file,
41
+ registry: config.registry ?? "quality/registry.json",
42
+ root,
43
+ sources: config.sources ?? ["."],
44
+ });
45
+
46
+ export const loadConfig = (cwd: string, path: string | undefined): Effect.Effect<ResolvedConfig, SetupFailure, FileSystem.FileSystem> =>
47
+ Effect.gen(function* () {
48
+ const fs = yield* FileSystem.FileSystem;
49
+ const file = resolve(cwd, path ?? CONFIG_FILE);
50
+ const present = yield* Effect.orElseSucceed(fs.exists(file), () => false);
51
+ if (!present) {
52
+ return yield* new SetupFailure({ message: `no config at ${file}. Create ${CONFIG_FILE} exporting defineConfig({ ... }), or pass --config.` });
53
+ }
54
+ const loaded = yield* importDefault(file);
55
+ const config = yield* validOrFail(file, yield* Effect.promise(() => decodeConfig(loaded)));
56
+ const rules = yield* validOrFail(file, yield* resolveRules(config));
57
+ return resolved(dirname(file), file, config, rules);
58
+ });
@@ -0,0 +1,60 @@
1
+ import { Effect } from "effect";
2
+ import type { Level } from "../config.ts";
3
+ import type { Decoded } from "../decoded.ts";
4
+ import type { ActiveRule } from "../engine/run-rules.ts";
5
+ import type { Rule } from "../rule.ts";
6
+ import { builtInRules } from "../rules/built-in.ts";
7
+ import type { ConfigInput } from "./decode.ts";
8
+
9
+ export interface ResolvedRules {
10
+ readonly active: ReadonlyArray<ActiveRule>;
11
+ readonly levels: ReadonlyMap<string, Level>;
12
+ }
13
+
14
+ type Setting = NonNullable<ConfigInput["rules"]>[string];
15
+
16
+ const messageOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
17
+
18
+ const levelOf = (setting: Setting | undefined): Level => (typeof setting === "string" ? setting : (setting?.level ?? "error"));
19
+
20
+ const optionsOf = (setting: Setting | undefined): unknown => (typeof setting === "object" ? setting.options : undefined);
21
+
22
+ const duplicateIssues = (rules: ReadonlyArray<Rule>): ReadonlyArray<string> =>
23
+ rules.flatMap((rule, index) =>
24
+ rules.findIndex((other) => other.id === rule.id) === index ? [] : [`local: rule id "${rule.id}" is already defined`],
25
+ );
26
+
27
+ const activate = (rule: Rule, setting: Setting | undefined): Effect.Effect<Decoded<ActiveRule | undefined>> => {
28
+ const level = levelOf(setting);
29
+ if (level === "off") {
30
+ return Effect.succeed({ _tag: "Valid", value: undefined });
31
+ }
32
+ return Effect.tryPromise({ catch: messageOf, try: () => rule.configure(optionsOf(setting)) }).pipe(
33
+ Effect.map(
34
+ (configured): Decoded<ActiveRule | undefined> =>
35
+ configured._tag === "Invalid"
36
+ ? { _tag: "Invalid", issues: configured.issues.map((issue) => `rules.${rule.id}.options: ${issue}`) }
37
+ : { _tag: "Valid", value: { check: configured.check, description: rule.description, id: rule.id, level } },
38
+ ),
39
+ Effect.catch((failure: string) =>
40
+ Effect.succeed<Decoded<ActiveRule | undefined>>({ _tag: "Invalid", issues: [`rules.${rule.id}.options: validation threw: ${failure}`] }),
41
+ ),
42
+ );
43
+ };
44
+
45
+ export const resolveRules = (config: ConfigInput): Effect.Effect<Decoded<ResolvedRules>> =>
46
+ Effect.gen(function* () {
47
+ const rules: ReadonlyArray<Rule> = [...builtInRules, ...(config.local ?? [])];
48
+ const settings = config.rules ?? {};
49
+ const known = new Set(rules.map((rule) => rule.id));
50
+ const unknown = Object.keys(settings)
51
+ .filter((id) => !known.has(id))
52
+ .map((id) => `rules.${id}: no built-in or local rule has this id`);
53
+ const activated = yield* Effect.forEach(rules, (rule) => activate(rule, settings[rule.id]));
54
+ const issues = [...duplicateIssues(rules), ...unknown, ...activated.flatMap((result) => (result._tag === "Invalid" ? result.issues : []))];
55
+ if (issues.length > 0) {
56
+ return { _tag: "Invalid", issues };
57
+ }
58
+ const active = activated.flatMap((result) => (result._tag === "Valid" && result.value !== undefined ? [result.value] : []));
59
+ return { _tag: "Valid", value: { active, levels: new Map(rules.map((rule) => [rule.id, levelOf(settings[rule.id])])) } };
60
+ });
package/src/config.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { Rule } from "./rule.ts";
2
+ import type { builtInRules } from "./rules/built-in.ts";
3
+
4
+ /** Every rule defaults to `error`. `warn` is for the transition to a rule and is meant to be temporary. */
5
+ export type Level = "error" | "warn" | "off";
6
+
7
+ export type RuleSetting<Input> = Level | { readonly level?: Level; readonly options?: Input };
8
+
9
+ type InputOf<Candidate> = Candidate extends Rule<string, infer Input> ? Input : never;
10
+
11
+ export type RuleSettings<Rules extends ReadonlyArray<Rule>> = {
12
+ readonly [Candidate in Rules[number] as Candidate["id"]]?: RuleSetting<InputOf<Candidate>>;
13
+ };
14
+
15
+ export type BuiltInRules = typeof builtInRules;
16
+
17
+ export interface QualityConfig<Local extends ReadonlyArray<Rule> = ReadonlyArray<Rule>> {
18
+ /** Directories or files to check, relative to the config file. Defaults to the whole repository. */
19
+ readonly sources?: ReadonlyArray<string>;
20
+ /** Paths never checked, in .gitignore syntax. Ignored files are always skipped. */
21
+ readonly exclude?: ReadonlyArray<string>;
22
+ /** Extensions of the source files rules read. Defaults to TypeScript and JavaScript modules. */
23
+ readonly extensions?: ReadonlyArray<string>;
24
+ /** Permanent exceptions, each with a reason. Defaults to `quality/registry.json`. */
25
+ readonly registry?: string;
26
+ /** Existing violations that may only shrink. Defaults to `quality/baseline.json`. */
27
+ readonly baseline?: string;
28
+ /** Repository rules, reported, registered and baselined like the built-in ones. */
29
+ readonly local?: Local;
30
+ readonly rules?: RuleSettings<readonly [...BuiltInRules, ...Local]>;
31
+ }
32
+
33
+ export const defineConfig = <const Local extends ReadonlyArray<Rule> = readonly []>(config: QualityConfig<Local>): QualityConfig<Local> => config;
package/src/decoded.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Effect } from "effect";
2
+ import { SetupFailure } from "./failure.ts";
3
+ import { describeIssue, type StandardSchemaV1 } from "./standard-schema.ts";
4
+
5
+ export type Decoded<Value> = { readonly _tag: "Valid"; readonly value: Value } | { readonly _tag: "Invalid"; readonly issues: ReadonlyArray<string> };
6
+
7
+ export const decodeWith = async <Output>(schema: StandardSchemaV1<unknown, Output>, value: unknown): Promise<Decoded<Output>> => {
8
+ const result = await schema["~standard"].validate(value);
9
+ return result.issues === undefined ? { _tag: "Valid", value: result.value } : { _tag: "Invalid", issues: result.issues.map(describeIssue) };
10
+ };
11
+
12
+ export const validOrFail = <Value>(file: string, decoded: Decoded<Value>): Effect.Effect<Value, SetupFailure> =>
13
+ decoded._tag === "Valid"
14
+ ? Effect.succeed(decoded.value)
15
+ : Effect.fail(new SetupFailure({ message: `${file} is invalid:\n${decoded.issues.map((issue) => ` - ${issue}`).join("\n")}` }));
@@ -0,0 +1,39 @@
1
+ import { applyBaseline, type Regression, type StaleBaselineEntry } from "../baseline/compare.ts";
2
+ import type { BaselineEntry } from "../baseline/format.ts";
3
+ import type { Level } from "../config.ts";
4
+ import { applyRegistry, type RegistryEntry, type StaleRegistryEntry } from "../exceptions/registry.ts";
5
+ import { byLocation, type Violation } from "./violation.ts";
6
+
7
+ export interface Outcome {
8
+ readonly errors: ReadonlyArray<Violation>;
9
+ readonly warnings: ReadonlyArray<Violation>;
10
+ readonly regressions: ReadonlyArray<Regression>;
11
+ readonly staleBaseline: ReadonlyArray<StaleBaselineEntry>;
12
+ readonly staleRegistry: ReadonlyArray<StaleRegistryEntry>;
13
+ readonly baselined: number;
14
+ readonly registered: number;
15
+ }
16
+
17
+ /** Registered exceptions apply first; the baseline then covers what is left, per rule and file. */
18
+ export const evaluate = (
19
+ violations: ReadonlyArray<Violation>,
20
+ registry: ReadonlyArray<RegistryEntry>,
21
+ baseline: ReadonlyArray<BaselineEntry>,
22
+ levels: ReadonlyMap<string, Level>,
23
+ ): Outcome => {
24
+ const registered = applyRegistry(violations, registry, levels);
25
+ const baselined = applyBaseline(registered.kept, baseline, levels);
26
+ const kept = [...baselined.kept].sort(byLocation);
27
+ return {
28
+ baselined: baselined.baselined,
29
+ errors: kept.filter((violation) => violation.level === "error"),
30
+ regressions: baselined.regressions,
31
+ registered: registered.registered,
32
+ staleBaseline: baselined.stale,
33
+ staleRegistry: registered.stale,
34
+ warnings: kept.filter((violation) => violation.level === "warn"),
35
+ };
36
+ };
37
+
38
+ export const passes = (outcome: Outcome): boolean =>
39
+ outcome.errors.length === 0 && outcome.staleBaseline.length === 0 && outcome.staleRegistry.length === 0;
@@ -0,0 +1,40 @@
1
+ import { isAbsolute, relative } from "node:path";
2
+ import { Effect } from "effect";
3
+ import { SetupFailure } from "../failure.ts";
4
+ import { posix } from "../inventory/ignore-scope.ts";
5
+ import type { Finding, Findings, RuleInputs } from "../rule.ts";
6
+ import type { ActiveLevel, Violation } from "./violation.ts";
7
+
8
+ export interface ActiveRule {
9
+ readonly id: string;
10
+ readonly description: string;
11
+ readonly level: ActiveLevel;
12
+ readonly check: (inputs: RuleInputs) => Promise<Findings>;
13
+ }
14
+
15
+ const messageOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
16
+
17
+ // Registry and baseline entries match on the path, so every finding names its file the same way.
18
+ const repositoryPath = (root: string, file: string): string => posix(isAbsolute(file) ? relative(root, file) : file).replace(/^(\.\/)+/, "");
19
+
20
+ const violationOf = (rule: ActiveRule, root: string, finding: Finding): Violation => ({
21
+ ...finding,
22
+ file: repositoryPath(root, finding.file),
23
+ level: rule.level,
24
+ rule: rule.id,
25
+ });
26
+
27
+ const runRule = (rule: ActiveRule, inputs: RuleInputs): Effect.Effect<ReadonlyArray<Violation>, SetupFailure> =>
28
+ Effect.map(
29
+ Effect.tryPromise({
30
+ try: () => rule.check(inputs),
31
+ catch: (cause) => new SetupFailure({ message: `rule ${rule.id} failed: ${messageOf(cause)}` }),
32
+ }),
33
+ (findings) => findings.map((finding) => violationOf(rule, inputs.root, finding)),
34
+ );
35
+
36
+ export const runRules = (rules: ReadonlyArray<ActiveRule>, inputs: RuleInputs): Effect.Effect<ReadonlyArray<Violation>, SetupFailure> =>
37
+ Effect.map(
38
+ Effect.forEach(rules, (rule) => runRule(rule, inputs), { concurrency: "unbounded" }),
39
+ (results) => results.flat(),
40
+ );
@@ -0,0 +1,40 @@
1
+ import { join, resolve } from "node:path";
2
+ import { Effect, type FileSystem } from "effect";
3
+ import { type BaselineEntry, decodeBaseline } from "../baseline/format.ts";
4
+ import { loadConfig, type ResolvedConfig } from "../config/load.ts";
5
+ import { validOrFail } from "../decoded.ts";
6
+ import { decodeRegistry, type RegistryEntry } from "../exceptions/registry.ts";
7
+ import { SetupFailure } from "../failure.ts";
8
+ import { collectInventory, type Inventory } from "../inventory/collect.ts";
9
+ import { type FilesystemFailure, readOptionalText } from "../inventory/filesystem.ts";
10
+ import { runRules } from "./run-rules.ts";
11
+ import type { Violation } from "./violation.ts";
12
+
13
+ export interface Session {
14
+ readonly config: ResolvedConfig;
15
+ readonly inventory: Inventory;
16
+ readonly violations: ReadonlyArray<Violation>;
17
+ readonly registry: ReadonlyArray<RegistryEntry>;
18
+ readonly baseline: { readonly raw: string | undefined; readonly entries: ReadonlyArray<BaselineEntry> };
19
+ }
20
+
21
+ const setup = <Value, Requirements>(
22
+ effect: Effect.Effect<Value, FilesystemFailure, Requirements>,
23
+ ): Effect.Effect<Value, SetupFailure, Requirements> => Effect.mapError(effect, (failure) => new SetupFailure({ message: failure.message }));
24
+
25
+ const readInput = (root: string, path: string): Effect.Effect<string | undefined, SetupFailure, FileSystem.FileSystem> =>
26
+ setup(readOptionalText(join(root, path)));
27
+
28
+ export const openSession = (cwd: string, configPath: string | undefined): Effect.Effect<Session, SetupFailure, FileSystem.FileSystem> =>
29
+ Effect.gen(function* () {
30
+ const config = yield* loadConfig(cwd, configPath);
31
+ const inventory = yield* setup(collectInventory(config.root, config));
32
+ const registryRaw = yield* readInput(config.root, config.registry);
33
+ const registry = yield* validOrFail(config.registry, yield* Effect.promise(() => decodeRegistry(registryRaw)));
34
+ const baselineRaw = yield* readInput(config.root, config.baseline);
35
+ const baseline = yield* validOrFail(config.baseline, yield* Effect.promise(() => decodeBaseline(baselineRaw)));
36
+ const services = yield* Effect.context<FileSystem.FileSystem>();
37
+ const readText = (path: string): Promise<string | undefined> => Effect.runPromiseWith(services)(readOptionalText(resolve(config.root, path)));
38
+ const violations = yield* runRules(config.active, { files: inventory.files, readText, root: config.root, sources: inventory.sources });
39
+ return { baseline: { entries: baseline, raw: baselineRaw }, config, inventory, registry, violations };
40
+ });
@@ -0,0 +1,35 @@
1
+ import type { Level } from "../config.ts";
2
+ import type { Finding } from "../rule.ts";
3
+
4
+ export type ActiveLevel = "error" | "warn";
5
+
6
+ export interface Violation extends Finding {
7
+ readonly rule: string;
8
+ readonly level: ActiveLevel;
9
+ }
10
+
11
+ export const keyOf = (rule: string, file: string): string => `${rule}\u0000${file}`;
12
+
13
+ export const byLocation = (left: Violation, right: Violation): number =>
14
+ left.rule.localeCompare(right.rule) || left.file.localeCompare(right.file) || (left.line ?? 0) - (right.line ?? 0);
15
+
16
+ export const groupBy = <Item>(items: ReadonlyArray<Item>, key: (item: Item) => string): ReadonlyMap<string, ReadonlyArray<Item>> => {
17
+ const groups = new Map<string, Item[]>();
18
+ for (const item of items) {
19
+ const group = groups.get(key(item));
20
+ if (group === undefined) {
21
+ groups.set(key(item), [item]);
22
+ } else {
23
+ group.push(item);
24
+ }
25
+ }
26
+ return groups;
27
+ };
28
+
29
+ export const unusedEntryProblem = (levels: ReadonlyMap<string, Level>, rule: string, unused: string): string => {
30
+ const level = levels.get(rule);
31
+ if (level === undefined) {
32
+ return "names no known rule";
33
+ }
34
+ return level === "off" ? "names a rule that is off" : unused;
35
+ };
@@ -0,0 +1,58 @@
1
+ import { Schema } from "effect";
2
+ import type { Level } from "../config.ts";
3
+ import { type Decoded, decodeWith } from "../decoded.ts";
4
+ import { unusedEntryProblem, type Violation } from "../engine/violation.ts";
5
+
6
+ const RegistryEntry = Schema.Struct({
7
+ rule: Schema.NonEmptyString,
8
+ file: Schema.NonEmptyString,
9
+ subject: Schema.optionalKey(Schema.NonEmptyString),
10
+ reason: Schema.String.check(Schema.isPattern(/\S/, { expected: "a reason that says why the exception is permanent" })),
11
+ });
12
+
13
+ export type RegistryEntry = typeof RegistryEntry.Type;
14
+
15
+ const standard = Schema.toStandardSchemaV1(Schema.fromJsonString(Schema.Array(RegistryEntry)), {
16
+ parseOptions: { errors: "all", onExcessProperty: "error" },
17
+ });
18
+
19
+ export const decodeRegistry = (raw: string | undefined): Promise<Decoded<ReadonlyArray<RegistryEntry>>> =>
20
+ raw === undefined ? Promise.resolve({ _tag: "Valid", value: [] }) : decodeWith(standard, raw);
21
+
22
+ export interface StaleRegistryEntry {
23
+ readonly entry: RegistryEntry;
24
+ readonly problem: string;
25
+ }
26
+
27
+ export interface RegistryCheck {
28
+ readonly kept: ReadonlyArray<Violation>;
29
+ readonly registered: number;
30
+ readonly stale: ReadonlyArray<StaleRegistryEntry>;
31
+ }
32
+
33
+ const covers = (entry: RegistryEntry, violation: Violation): boolean =>
34
+ entry.rule === violation.rule && entry.file === violation.file && (entry.subject === undefined || entry.subject === violation.subject);
35
+
36
+ const coveringEntry = (entries: ReadonlyArray<RegistryEntry>, violation: Violation): RegistryEntry | undefined => {
37
+ const matching = entries.filter((entry) => covers(entry, violation));
38
+ return matching.find((entry) => entry.subject !== undefined) ?? matching[0];
39
+ };
40
+
41
+ export const applyRegistry = (
42
+ violations: ReadonlyArray<Violation>,
43
+ entries: ReadonlyArray<RegistryEntry>,
44
+ levels: ReadonlyMap<string, Level>,
45
+ ): RegistryCheck => {
46
+ const used = new Set<RegistryEntry>();
47
+ const kept = violations.filter((violation) => {
48
+ const entry = coveringEntry(entries, violation);
49
+ if (entry !== undefined) {
50
+ used.add(entry);
51
+ }
52
+ return entry === undefined;
53
+ });
54
+ const stale = entries
55
+ .filter((entry) => !used.has(entry))
56
+ .map((entry) => ({ entry, problem: unusedEntryProblem(levels, entry.rule, "matches no violation") }));
57
+ return { kept, registered: violations.length - kept.length, stale };
58
+ };
package/src/failure.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Data, Runtime } from "effect";
2
+
3
+ /** The check could not run: invalid configuration, unreadable input or a crashed rule. Exits 2. */
4
+ export class SetupFailure extends Data.TaggedError("SetupFailure")<{ readonly message: string }> {
5
+ override readonly [Runtime.errorReported] = false;
6
+ override readonly [Runtime.errorExitCode] = 2;
7
+ }
8
+
9
+ /** The check ran and the repository fails the gate. The report is already printed. Exits 1. */
10
+ export class GateFailed extends Data.TaggedError("GateFailed") {
11
+ override readonly [Runtime.errorReported] = false;
12
+ override readonly [Runtime.errorExitCode] = 1;
13
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type { BuiltInRules, Level, QualityConfig, RuleSetting, RuleSettings } from "./config.ts";
2
+ export { defineConfig } from "./config.ts";
3
+ export type { Configured, Finding, Findings, Rule, RuleContext, RuleInputs, SourceFile } from "./rule.ts";
4
+ export { defineRule } from "./rule.ts";
5
+ export type { StandardIssue, StandardResult, StandardSchemaV1 } from "./standard-schema.ts";
@@ -0,0 +1,53 @@
1
+ import { join, relative } from "node:path";
2
+ import { Effect, FileSystem } from "effect";
3
+ import ignore from "ignore";
4
+ import type { SourceFile } from "../rule.ts";
5
+ import { FilesystemFailure, orWhenAbsent, readRequiredText } from "./filesystem.ts";
6
+ import { posix } from "./ignore-scope.ts";
7
+ import { scopeAbove, walk } from "./walk.ts";
8
+
9
+ export interface InventoryScope {
10
+ readonly sources: ReadonlyArray<string>;
11
+ readonly exclude: ReadonlyArray<string>;
12
+ readonly extensions: ReadonlyArray<string>;
13
+ }
14
+
15
+ export interface Inventory {
16
+ readonly files: ReadonlyArray<string>;
17
+ readonly sources: ReadonlyArray<SourceFile>;
18
+ }
19
+
20
+ const READ_CONCURRENCY = 16;
21
+
22
+ export const linesOf = (text: string): ReadonlyArray<string> => {
23
+ const lines = text.split("\n");
24
+ return lines.at(-1) === "" ? lines.slice(0, -1) : lines;
25
+ };
26
+
27
+ const zoneFiles = (root: string, zone: string): Effect.Effect<readonly string[], FilesystemFailure, FileSystem.FileSystem> =>
28
+ Effect.gen(function* () {
29
+ const fs = yield* FileSystem.FileSystem;
30
+ const path = join(root, zone);
31
+ if (posix(relative(root, path)).startsWith("..")) {
32
+ return yield* new FilesystemFailure({ message: `source "${zone}" lies outside the repository at ${root}`, path });
33
+ }
34
+ const info = yield* orWhenAbsent<FileSystem.File.Info | undefined>(path, fs.stat(path), undefined);
35
+ if (info === undefined) {
36
+ return yield* new FilesystemFailure({ message: `source "${zone}" does not exist in ${root}`, path });
37
+ }
38
+ return info.type === "Directory" ? yield* walk(path, yield* scopeAbove(root, path)) : [path];
39
+ });
40
+
41
+ const readSource = (root: string, path: string): Effect.Effect<SourceFile, FilesystemFailure, FileSystem.FileSystem> =>
42
+ Effect.map(readRequiredText(join(root, path)), (text) => ({ lines: linesOf(text), path, text }));
43
+
44
+ export const collectInventory = (root: string, scope: InventoryScope): Effect.Effect<Inventory, FilesystemFailure, FileSystem.FileSystem> =>
45
+ Effect.gen(function* () {
46
+ const excluded = ignore().add([...scope.exclude]);
47
+ const zones = yield* Effect.forEach(scope.sources, (zone) => zoneFiles(root, zone), { concurrency: READ_CONCURRENCY });
48
+ const relativePaths = zones.flat().map((absolute) => posix(relative(root, absolute)));
49
+ const files = [...new Set(relativePaths)].filter((path) => !excluded.ignores(path)).sort();
50
+ const sourcePaths = files.filter((path) => scope.extensions.some((extension) => path.endsWith(extension)));
51
+ const sources = yield* Effect.forEach(sourcePaths, (path) => readSource(root, path), { concurrency: READ_CONCURRENCY });
52
+ return { files, sources };
53
+ });
@@ -0,0 +1,47 @@
1
+ import { dirname } from "node:path";
2
+ import { Data, Effect, FileSystem } from "effect";
3
+ import type { PlatformError } from "effect/PlatformError";
4
+
5
+ const ABSENT = new Set(["ENOENT", "ENOTDIR"]);
6
+
7
+ export class FilesystemFailure extends Data.TaggedError("FilesystemFailure")<{
8
+ readonly message: string;
9
+ readonly path: string;
10
+ }> {}
11
+
12
+ // Effect maps ENOTDIR and EISDIR to BadResource; the original errno remains on the cause.
13
+ const errnoOf = (error: PlatformError): string => {
14
+ const cause: unknown = error.reason.cause;
15
+ return typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
16
+ };
17
+
18
+ const failure = (path: string, error: PlatformError): FilesystemFailure =>
19
+ new FilesystemFailure({ message: `cannot read ${path}: ${error.message}`, path });
20
+
21
+ export const orWhenAbsent = <Value>(
22
+ path: string,
23
+ action: Effect.Effect<Value, PlatformError, FileSystem.FileSystem>,
24
+ whenAbsent: Value,
25
+ ): Effect.Effect<Value, FilesystemFailure, FileSystem.FileSystem> =>
26
+ Effect.catchTag(action, "PlatformError", (error) => (ABSENT.has(errnoOf(error)) ? Effect.succeed(whenAbsent) : Effect.fail(failure(path, error))));
27
+
28
+ export const readOptionalText = (path: string): Effect.Effect<string | undefined, FilesystemFailure, FileSystem.FileSystem> =>
29
+ Effect.gen(function* () {
30
+ const fs = yield* FileSystem.FileSystem;
31
+ return yield* orWhenAbsent<string | undefined>(path, fs.readFileString(path), undefined);
32
+ });
33
+
34
+ export const readRequiredText = (path: string): Effect.Effect<string, FilesystemFailure, FileSystem.FileSystem> =>
35
+ Effect.gen(function* () {
36
+ const fs = yield* FileSystem.FileSystem;
37
+ return yield* Effect.mapError(fs.readFileString(path), (error) =>
38
+ ABSENT.has(errnoOf(error)) ? new FilesystemFailure({ message: `required input is missing: ${path}`, path }) : failure(path, error),
39
+ );
40
+ });
41
+
42
+ export const writeText = (path: string, text: string): Effect.Effect<void, FilesystemFailure, FileSystem.FileSystem> =>
43
+ Effect.gen(function* () {
44
+ const fs = yield* FileSystem.FileSystem;
45
+ const written = Effect.andThen(fs.makeDirectory(dirname(path), { recursive: true }), fs.writeFileString(path, text));
46
+ return yield* Effect.mapError(written, (error) => new FilesystemFailure({ message: `cannot write ${path}: ${error.message}`, path }));
47
+ });
@@ -0,0 +1,44 @@
1
+ import { relative } from "node:path";
2
+ import ignore from "ignore";
3
+
4
+ export type Verdict = "ignored" | "kept" | "unknown";
5
+
6
+ interface IgnoreMatcher {
7
+ readonly base: string;
8
+ readonly rules: ReturnType<typeof ignore>;
9
+ }
10
+
11
+ export interface IgnoreScope {
12
+ readonly boundary: string | undefined;
13
+ readonly matchers: readonly IgnoreMatcher[];
14
+ }
15
+
16
+ export const emptyScope: IgnoreScope = { boundary: undefined, matchers: [] };
17
+
18
+ export const posix = (path: string): string => path.replaceAll("\\", "/");
19
+
20
+ export const withIgnoreFile = (scope: IgnoreScope, base: string, contents: string): IgnoreScope => ({
21
+ boundary: scope.boundary,
22
+ matchers: [...scope.matchers, { base, rules: ignore().add(contents) }],
23
+ });
24
+
25
+ // Re-including a directory resets directory rules below that boundary; filename rules still apply.
26
+ export const insideKept = (scope: IgnoreScope, directory: string): IgnoreScope => ({ boundary: directory, matchers: scope.matchers });
27
+
28
+ const matcherVerdict = (matcher: IgnoreMatcher, boundary: string | undefined, path: string, directory: boolean): Verdict => {
29
+ const anchor = boundary !== undefined && boundary.length > matcher.base.length ? boundary : matcher.base;
30
+ const rel = posix(relative(anchor, path));
31
+ if (rel === "" || rel.startsWith("..")) {
32
+ return "unknown";
33
+ }
34
+ // Directory-only patterns match paths with a trailing slash.
35
+ const result = matcher.rules.test(directory ? `${rel}/` : rel);
36
+ if (result.ignored) {
37
+ return "ignored";
38
+ }
39
+ return result.unignored ? "kept" : "unknown";
40
+ };
41
+
42
+ // The deepest ignore file with an opinion wins.
43
+ export const verdictFor = (scope: IgnoreScope, path: string, directory: boolean): Verdict =>
44
+ scope.matchers.map((matcher) => matcherVerdict(matcher, scope.boundary, path, directory)).findLast((verdict) => verdict !== "unknown") ?? "unknown";
@@ -0,0 +1,58 @@
1
+ import { join, relative, sep } from "node:path";
2
+ import { Effect, FileSystem } from "effect";
3
+ import { type FilesystemFailure, orWhenAbsent, readOptionalText } from "./filesystem.ts";
4
+ import { emptyScope, type IgnoreScope, insideKept, verdictFor, withIgnoreFile } from "./ignore-scope.ts";
5
+
6
+ const SKIPPED = new Set([".git", "node_modules"]);
7
+
8
+ export const ignoreScopeAt = (
9
+ dir: string,
10
+ inherited: IgnoreScope = emptyScope,
11
+ ): Effect.Effect<IgnoreScope, FilesystemFailure, FileSystem.FileSystem> =>
12
+ Effect.map(readOptionalText(join(dir, ".gitignore")), (contents) =>
13
+ contents === undefined || contents === "" ? inherited : withIgnoreFile(inherited, dir, contents),
14
+ );
15
+
16
+ /** The ignore files of every directory between the root and a walked directory, which the walk itself does not visit. */
17
+ export const scopeAbove = (root: string, dir: string): Effect.Effect<IgnoreScope, FilesystemFailure, FileSystem.FileSystem> => {
18
+ const parts = relative(root, dir)
19
+ .split(sep)
20
+ .filter((part) => part !== "");
21
+ const ancestors = parts.length === 0 ? [] : [root, ...parts.slice(0, -1).map((_, index) => join(root, ...parts.slice(0, index + 1)))];
22
+ return Effect.reduce(
23
+ ancestors,
24
+ () => emptyScope,
25
+ (scope, ancestor) => ignoreScopeAt(ancestor, scope),
26
+ );
27
+ };
28
+
29
+ export const walk = (dir: string, inherited: IgnoreScope = emptyScope): Effect.Effect<readonly string[], FilesystemFailure, FileSystem.FileSystem> =>
30
+ Effect.gen(function* () {
31
+ const fs = yield* FileSystem.FileSystem;
32
+ const scope = yield* ignoreScopeAt(dir, inherited);
33
+ const entries = yield* orWhenAbsent<readonly string[]>(dir, fs.readDirectory(dir), []);
34
+ const nested = yield* Effect.forEach(
35
+ entries.filter((entry) => !SKIPPED.has(entry)),
36
+ (entry) => walkEntry(join(dir, entry), scope),
37
+ { concurrency: 1 },
38
+ );
39
+ return nested.flat();
40
+ });
41
+
42
+ const walkEntry = (path: string, scope: IgnoreScope): Effect.Effect<readonly string[], FilesystemFailure, FileSystem.FileSystem> =>
43
+ Effect.gen(function* () {
44
+ const fs = yield* FileSystem.FileSystem;
45
+ const info = yield* orWhenAbsent<FileSystem.File.Info | undefined>(path, fs.stat(path), undefined);
46
+ if (info === undefined) {
47
+ return [];
48
+ }
49
+ const directory = info.type === "Directory";
50
+ const verdict = verdictFor(scope, path, directory);
51
+ if (verdict === "ignored") {
52
+ return [];
53
+ }
54
+ if (!directory) {
55
+ return [path];
56
+ }
57
+ return yield* walk(path, verdict === "kept" ? insideKept(scope, path) : scope);
58
+ });
@@ -0,0 +1 @@
1
+ export const plural = (count: number, singular: string, many = `${singular}s`): string => `${count} ${count === 1 ? singular : many}`;