@shivaedev/quality 0.52.0 → 0.53.1

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 (127) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +19 -9
  3. package/biome/declarations.json +0 -5
  4. package/biome/preset.json +1 -1
  5. package/dist/baseline/cleanupMergeFiles.d.ts +4 -0
  6. package/dist/baseline/cleanupMergeFiles.d.ts.map +1 -0
  7. package/dist/baseline/cleanupMergeFiles.js +23 -0
  8. package/dist/baseline/cleanupMergeFiles.js.map +1 -0
  9. package/dist/cli/lint.d.ts +2 -3
  10. package/dist/cli/lint.d.ts.map +1 -1
  11. package/dist/cli/lint.js +4 -2
  12. package/dist/cli/lint.js.map +1 -1
  13. package/dist/cli/program.d.ts.map +1 -1
  14. package/dist/cli/program.js +2 -0
  15. package/dist/cli/program.js.map +1 -1
  16. package/dist/config/globs.d.ts +17 -0
  17. package/dist/config/globs.d.ts.map +1 -0
  18. package/dist/config/globs.js +18 -0
  19. package/dist/config/globs.js.map +1 -0
  20. package/dist/engine/runRules.d.ts +2 -1
  21. package/dist/engine/runRules.d.ts.map +1 -1
  22. package/dist/engine/runRules.js +4 -1
  23. package/dist/engine/runRules.js.map +1 -1
  24. package/dist/engine/session.d.ts +1 -1
  25. package/dist/engine/session.d.ts.map +1 -1
  26. package/dist/engine/session.js +9 -5
  27. package/dist/engine/session.js.map +1 -1
  28. package/dist/hooks/preCommit.d.ts +2 -1
  29. package/dist/hooks/preCommit.d.ts.map +1 -1
  30. package/dist/imports/departures.d.ts.map +1 -1
  31. package/dist/imports/departures.js +13 -0
  32. package/dist/imports/departures.js.map +1 -1
  33. package/dist/rule.d.ts +1 -0
  34. package/dist/rule.d.ts.map +1 -1
  35. package/dist/rule.js +7 -3
  36. package/dist/rule.js.map +1 -1
  37. package/dist/rules/builtIn.d.ts +36 -9
  38. package/dist/rules/builtIn.d.ts.map +1 -1
  39. package/dist/rules/files/folderNames.d.ts +8 -2
  40. package/dist/rules/files/folderNames.d.ts.map +1 -1
  41. package/dist/rules/files/folderNames.js +7 -5
  42. package/dist/rules/files/folderNames.js.map +1 -1
  43. package/dist/rules/files/namedAfterExport.d.ts +4 -1
  44. package/dist/rules/files/namedAfterExport.d.ts.map +1 -1
  45. package/dist/rules/files/namedAfterExport.js +10 -8
  46. package/dist/rules/files/namedAfterExport.js.map +1 -1
  47. package/dist/rules/files/otherNames.d.ts +8 -2
  48. package/dist/rules/files/otherNames.d.ts.map +1 -1
  49. package/dist/rules/files/otherNames.js +7 -5
  50. package/dist/rules/files/otherNames.js.map +1 -1
  51. package/dist/rules/imports/aliased.js +1 -1
  52. package/dist/rules/imports/aliased.js.map +1 -1
  53. package/dist/rules/stories/authSql.d.ts +4 -1
  54. package/dist/rules/stories/authSql.d.ts.map +1 -1
  55. package/dist/rules/stories/authSql.js +6 -3
  56. package/dist/rules/stories/authSql.js.map +1 -1
  57. package/dist/rules/stories/collectionOrigins.d.ts +5 -0
  58. package/dist/rules/stories/collectionOrigins.d.ts.map +1 -0
  59. package/dist/rules/stories/collectionOrigins.js +17 -0
  60. package/dist/rules/stories/collectionOrigins.js.map +1 -0
  61. package/dist/rules/stories/httpStatus.d.ts +4 -1
  62. package/dist/rules/stories/httpStatus.d.ts.map +1 -1
  63. package/dist/rules/stories/httpStatus.js +6 -3
  64. package/dist/rules/stories/httpStatus.js.map +1 -1
  65. package/dist/rules/stories/namedValues.d.ts.map +1 -1
  66. package/dist/rules/stories/namedValues.js +5 -5
  67. package/dist/rules/stories/namedValues.js.map +1 -1
  68. package/dist/rules/stories/noLimitImports.d.ts.map +1 -1
  69. package/dist/rules/stories/noLimitImports.js +4 -2
  70. package/dist/rules/stories/noLimitImports.js.map +1 -1
  71. package/dist/rules/stories/origins.d.ts +1 -2
  72. package/dist/rules/stories/origins.d.ts.map +1 -1
  73. package/dist/rules/stories/origins.js +12 -6
  74. package/dist/rules/stories/origins.js.map +1 -1
  75. package/dist/rules/stories/prerequisites.d.ts.map +1 -1
  76. package/dist/rules/stories/prerequisites.js +6 -24
  77. package/dist/rules/stories/prerequisites.js.map +1 -1
  78. package/dist/rules/stories/program.d.ts.map +1 -1
  79. package/dist/rules/stories/program.js +8 -1
  80. package/dist/rules/stories/program.js.map +1 -1
  81. package/dist/rules/stories/sources.d.ts.map +1 -1
  82. package/dist/rules/stories/sources.js +19 -7
  83. package/dist/rules/stories/sources.js.map +1 -1
  84. package/dist/rules/stories/specHelpers.d.ts.map +1 -1
  85. package/dist/rules/stories/specHelpers.js +4 -2
  86. package/dist/rules/stories/specHelpers.js.map +1 -1
  87. package/dist/rules/stories/specs.js +1 -1
  88. package/dist/rules/stories/specs.js.map +1 -1
  89. package/dist/rules/stories/syntax.d.ts +0 -1
  90. package/dist/rules/stories/syntax.d.ts.map +1 -1
  91. package/dist/rules/stories/syntax.js +0 -4
  92. package/dist/rules/stories/syntax.js.map +1 -1
  93. package/dist/rules/test-names/colocated.d.ts +4 -1
  94. package/dist/rules/test-names/colocated.d.ts.map +1 -1
  95. package/dist/rules/test-names/colocated.js +5 -3
  96. package/dist/rules/test-names/colocated.js.map +1 -1
  97. package/dist/rules/test-names/follow.d.ts +4 -1
  98. package/dist/rules/test-names/follow.d.ts.map +1 -1
  99. package/dist/rules/test-names/follow.js +5 -3
  100. package/dist/rules/test-names/follow.js.map +1 -1
  101. package/package.json +3 -2
  102. package/src/baseline/cleanupMergeFiles.ts +27 -0
  103. package/src/cli/lint.ts +33 -27
  104. package/src/cli/program.ts +2 -0
  105. package/src/config/globs.ts +31 -0
  106. package/src/engine/runRules.ts +7 -2
  107. package/src/engine/session.ts +10 -5
  108. package/src/imports/departures.ts +16 -0
  109. package/src/rule.ts +12 -2
  110. package/src/rules/files/folderNames.ts +7 -5
  111. package/src/rules/files/namedAfterExport.ts +10 -8
  112. package/src/rules/files/otherNames.ts +7 -5
  113. package/src/rules/imports/aliased.ts +1 -1
  114. package/src/rules/stories/authSql.ts +6 -3
  115. package/src/rules/stories/collectionOrigins.ts +20 -0
  116. package/src/rules/stories/httpStatus.ts +6 -3
  117. package/src/rules/stories/namedValues.ts +7 -5
  118. package/src/rules/stories/noLimitImports.ts +4 -2
  119. package/src/rules/stories/origins.ts +12 -8
  120. package/src/rules/stories/prerequisites.ts +6 -25
  121. package/src/rules/stories/program.ts +9 -1
  122. package/src/rules/stories/sources.ts +21 -9
  123. package/src/rules/stories/specHelpers.ts +4 -2
  124. package/src/rules/stories/specs.ts +1 -1
  125. package/src/rules/stories/syntax.ts +0 -5
  126. package/src/rules/test-names/colocated.ts +5 -3
  127. package/src/rules/test-names/follow.ts +5 -3
@@ -0,0 +1,27 @@
1
+ import { resolve } from "node:path";
2
+ import { Clock, Effect, FileSystem, Option } from "effect";
3
+ import { SetupFailure } from "#failure.ts";
4
+ import { gitOrFail } from "#git/command.ts";
5
+
6
+ const STALE_AFTER_MS = 5 * 60_000;
7
+
8
+ export const cleanupMergeFiles = Effect.fn("Baseline.cleanupMergeFiles")(
9
+ function* (cwd: string, inputs: readonly string[]) {
10
+ const fs = yield* FileSystem.FileSystem;
11
+ const root = (yield* gitOrFail(cwd, ["rev-parse", "--show-toplevel"])).trim();
12
+ const active = new Set(inputs.map((path) => resolve(cwd, path)));
13
+ const untracked = yield* gitOrFail(root, ["ls-files", "--others", "--full-name", "-z", "--", ":(top,glob).merge_file_*"]);
14
+ const cutoff = (yield* Clock.currentTimeMillis) - STALE_AFTER_MS;
15
+ for (const name of untracked.split("\0").filter(Boolean)) {
16
+ const path = resolve(root, name);
17
+ if (active.has(path)) {
18
+ continue;
19
+ }
20
+ const info = yield* fs.stat(path);
21
+ if (info.type === "File" && Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff)) {
22
+ yield* fs.remove(path);
23
+ }
24
+ }
25
+ },
26
+ Effect.mapError((failure) => new SetupFailure({ cause: failure, message: failure.message })),
27
+ );
package/src/cli/lint.ts CHANGED
@@ -1,36 +1,42 @@
1
1
  import { relative } from "node:path";
2
+ import * as NodePath from "@effect/platform-node/NodePath";
2
3
  import { Console, Effect } from "effect";
4
+ import { withHeavyLock } from "@shivaedev/heavy-lock/withHeavyLock.ts";
3
5
  import { looseStagedEntries } from "#baseline/looseStagedEntries.ts";
4
6
  import { evaluate, passes } from "#engine/evaluate.ts";
5
7
  import { openSession } from "#engine/session.ts";
6
8
  import { keyOf } from "#engine/violation.ts";
7
- import { GateFailed, type SetupFailure } from "#failure.ts";
9
+ import { GateFailed, SetupFailure } from "#failure.ts";
8
10
  import { render } from "#report/render.ts";
9
11
  import type { RuleServices } from "#rule.ts";
10
12
 
11
- export const lint = Effect.fn("Cli.lint")(function* (
12
- cwd: string,
13
- config: string | undefined,
14
- staged = false,
15
- ): Effect.fn.Return<void, SetupFailure | GateFailed, RuleServices> {
16
- const session = yield* openSession(cwd, config);
17
- const evaluated = evaluate(session.violations, session.registry, session.baseline.entries, session.config);
18
- const loose = staged ? yield* looseStagedEntries(session) : [];
19
- const rejected = new Set(loose.map(({ entry }) => keyOf(entry.rule, entry.file)));
20
- const outcome = {
21
- ...evaluated,
22
- looseBaseline: evaluated.looseBaseline.filter(({ entry }) => !rejected.has(keyOf(entry.rule, entry.file))),
23
- staleBaseline: [...evaluated.staleBaseline, ...loose],
24
- };
25
- yield* Console.log(
26
- render(outcome, {
27
- baseline: session.config.baseline,
28
- checked: session.inventory.sources.length,
29
- descriptions: new Map(session.config.active.map((rule) => [rule.id, rule.description])),
30
- registry: session.config.exceptions.length === 0 ? session.config.registry : `${relative(session.config.root, session.config.file)} exceptions`,
31
- }),
32
- );
33
- if (!passes(outcome)) {
34
- return yield* new GateFailed();
35
- }
36
- });
13
+ export const lint = Effect.fn("Cli.lint")(
14
+ function* (cwd: string, config: string | undefined, staged = false): Effect.fn.Return<void, SetupFailure | GateFailed, RuleServices> {
15
+ const session = yield* openSession(cwd, config);
16
+ const evaluated = evaluate(session.violations, session.registry, session.baseline.entries, session.config);
17
+ const loose = staged ? yield* looseStagedEntries(session) : [];
18
+ const rejected = new Set(loose.map(({ entry }) => keyOf(entry.rule, entry.file)));
19
+ const outcome = {
20
+ ...evaluated,
21
+ looseBaseline: evaluated.looseBaseline.filter(({ entry }) => !rejected.has(keyOf(entry.rule, entry.file))),
22
+ staleBaseline: [...evaluated.staleBaseline, ...loose],
23
+ };
24
+ yield* Console.log(
25
+ render(outcome, {
26
+ baseline: session.config.baseline,
27
+ checked: session.inventory.sources.length,
28
+ descriptions: new Map(session.config.active.map((rule) => [rule.id, rule.description])),
29
+ registry:
30
+ session.config.exceptions.length === 0 ? session.config.registry : `${relative(session.config.root, session.config.file)} exceptions`,
31
+ }),
32
+ );
33
+ if (!passes(outcome)) {
34
+ return yield* new GateFailed();
35
+ }
36
+ },
37
+ (effect) =>
38
+ withHeavyLock(effect, { command: "quality lint" }).pipe(
39
+ Effect.catchTag("HeavyLockError", (cause) => new SetupFailure({ cause, message: cause.message })),
40
+ Effect.provide(NodePath.layer),
41
+ ),
42
+ );
@@ -1,4 +1,5 @@
1
1
  import { Console, Effect } from "effect";
2
+ import { cleanupMergeFiles } from "#baseline/cleanupMergeFiles.ts";
2
3
  import { installDriver } from "#baseline/installDriver.ts";
3
4
  import { mergeBaseline } from "#baseline/merge.ts";
4
5
  import { parseCommand } from "#cli/args.ts";
@@ -42,6 +43,7 @@ export const program = Effect.fn("Cli.program")(function* (args: readonly string
42
43
  case "Fix":
43
44
  return yield* command.rules.length === 0 ? fix(cwd, command.config) : fixRule(cwd, command.config, command.rules);
44
45
  case "BaselineMerge":
46
+ yield* cleanupMergeFiles(cwd, [command.base, command.ours, command.theirs]);
45
47
  return yield* mergeBaseline(command.base, command.ours, command.theirs);
46
48
  case "BaselineInstallDriver":
47
49
  return yield* installDriver(cwd, launch);
@@ -0,0 +1,31 @@
1
+ import { Effect, Schema } from "effect";
2
+ import ignore from "ignore";
3
+
4
+ const GlobDeclaration = Schema.Struct({
5
+ glob: Schema.NonEmptyString,
6
+ reason: Schema.String.check(Schema.isPattern(/\S/u, { expected: "a reason for this glob" })),
7
+ });
8
+
9
+ export const GlobDeclarations = Schema.Array(GlobDeclaration).pipe(Schema.withDecodingDefaultKey(Effect.succeed([])));
10
+
11
+ type GlobOptions = Readonly<Record<string, readonly (typeof GlobDeclaration.Type)[]>>;
12
+
13
+ export function globPatterns(declarations: readonly (typeof GlobDeclaration.Type)[]): readonly string[] {
14
+ return declarations.map(({ glob }) => glob);
15
+ }
16
+
17
+ function matchesIgnorePattern(file: string, glob: string): boolean {
18
+ const result = ignore().add(glob).test(file);
19
+ return result.ignored || result.unignored;
20
+ }
21
+
22
+ export function validateGlobs(
23
+ { files, options }: { readonly files: readonly string[]; readonly options: GlobOptions },
24
+ matches: (file: string, glob: string) => boolean = matchesIgnorePattern,
25
+ ): readonly string[] {
26
+ return Object.entries(options).flatMap(([option, declarations]) =>
27
+ declarations.flatMap(({ glob }, index) =>
28
+ files.some((file) => matches(file, glob)) ? [] : [`${option}.${index}.glob: "${glob}" matches no current file. Remove the stale glob.`],
29
+ ),
30
+ );
31
+ }
@@ -1,6 +1,7 @@
1
1
  import { isAbsolute, relative } from "node:path";
2
2
  import { Effect } from "effect";
3
3
  import { ManifestFailure } from "#adapters/manifestInventory.ts";
4
+ import { SetupFailure } from "#failure.ts";
4
5
  import { posix } from "#inventory/ignoreScope.ts";
5
6
  import type { Finding, RuleCheck, RuleInputs, RuleServices } from "#rule.ts";
6
7
  import type { ActiveLevel, Violation } from "./violation.ts";
@@ -48,9 +49,13 @@ function violationOf(rule: ActiveRule, root: string, finding: Finding, exception
48
49
  };
49
50
  }
50
51
 
51
- function runRule(rule: ActiveRule, inputs: RuleInputs, exceptionFile: string): Effect.Effect<readonly Violation[], never, RuleServices> {
52
+ function runRule(rule: ActiveRule, inputs: RuleInputs, exceptionFile: string): Effect.Effect<readonly Violation[], SetupFailure, RuleServices> {
52
53
  return Effect.suspend(() => rule.check(inputs)).pipe(
53
- Effect.orDie,
54
+ Effect.catch((cause) =>
55
+ cause instanceof SetupFailure
56
+ ? Effect.fail(new SetupFailure({ cause, message: `rule ${rule.id} failed: ${cause.message}` }))
57
+ : Effect.die(cause),
58
+ ),
54
59
  Effect.map((findings) => findings.map((finding) => violationOf(rule, inputs.root, finding, exceptionFile))),
55
60
  Effect.catchDefect((cause) =>
56
61
  cause instanceof ManifestFailure
@@ -3,8 +3,7 @@ import { Effect } from "effect";
3
3
  import { setManifestFiles } from "#adapters/manifestInventory.ts";
4
4
  import { manifestReader } from "#adapters/manifestReader.ts";
5
5
  import { loadConfig, type ResolvedConfig } from "#config/load.ts";
6
- import { validOrFail } from "#decoded.ts";
7
- import { decodeRegistry, type RegistryEntry } from "#exceptions/registry.ts";
6
+ import type { RegistryEntry } from "#exceptions/registry.ts";
8
7
  import { registryEntries } from "#exceptions/registryEntries.ts";
9
8
  import { SetupFailure } from "#failure.ts";
10
9
  import { collectInventory, type Inventory } from "#inventory/collect.ts";
@@ -52,9 +51,15 @@ export const openSession = Effect.fn("Engine.openSession")(function* (
52
51
  configPath: string | undefined,
53
52
  ): Effect.fn.Return<Session, SetupFailure, RuleServices> {
54
53
  const config = yield* loadConfig(cwd, configPath);
55
- const registryRaw = yield* readInput(config.root, config.registry);
56
- const registry = yield* validOrFail(config.registry, yield* Effect.promise(() => decodeRegistry(registryRaw)));
54
+ const selection = configPath === undefined ? "" : ` --config ${configPath}`;
55
+ for (const path of new Set([config.registry, "quality/registry.json"])) {
56
+ if ((yield* readInput(config.root, path)) !== undefined) {
57
+ return yield* new SetupFailure({
58
+ message: `${path} holds legacy exceptions. Run \`quality exceptions migrate${selection} --from ${path}\` to move them into ${config.file}.`,
59
+ });
60
+ }
61
+ }
57
62
  const baseline = yield* readBaseline(config);
58
63
  const { inventory, violations } = yield* scan(config);
59
- return { baseline, config, inventory, registry: [...registry, ...registryEntries(config.exceptions)], violations };
64
+ return { baseline, config, inventory, registry: registryEntries(config.exceptions), violations };
60
65
  });
@@ -1,5 +1,6 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { posix } from "node:path";
3
+ import { moduleRoot } from "#naming/moduleRoot.ts";
3
4
  import type { RuleInputs } from "#rule.ts";
4
5
  import { parse } from "#rules/parse.ts";
5
6
  import type { ImportRequest } from "./extract.ts";
@@ -39,6 +40,18 @@ interface FileContext {
39
40
  readonly root: string;
40
41
  }
41
42
 
43
+ function registersAdmin(from: string, specifier: string, target: string | undefined): boolean {
44
+ const root = moduleRoot(from);
45
+ const folder = posix.dirname(from);
46
+ return (
47
+ root !== undefined
48
+ && (folder === `${root}/client` || folder === `${root}/server`)
49
+ && /^registration\.[cm]?[jt]sx?$/u.test(posix.basename(from))
50
+ && specifier.startsWith("./admin/")
51
+ && target?.startsWith(`${folder}/admin/`) === true
52
+ );
53
+ }
54
+
42
55
  // A relative import leaves its folder when its path climbs or descends, or when it names a folder whose index file lies below.
43
56
  function departureAt(context: FileContext, site: SpecifierSite): Departure | undefined {
44
57
  const path = site.specifier.replace(QUERY, "");
@@ -48,6 +61,9 @@ function departureAt(context: FileContext, site: SpecifierSite): Departure | und
48
61
  const request: ImportRequest = { kind: "import", line: site.line, specifier: site.specifier, type: site.type };
49
62
  const target = resolveImport(context.root, noAmbient, request, context.from, context.project);
50
63
  const local = target?.kind === "file" ? target.path : undefined;
64
+ if (registersAdmin(context.path, path, local)) {
65
+ return undefined;
66
+ }
51
67
  if (!(leavesLexically(path) || (local !== undefined && posix.dirname(local) !== posix.dirname(context.path)))) {
52
68
  return undefined;
53
69
  }
package/src/rule.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Effect, type FileSystem } from "effect";
2
2
  import type { ChildProcessSpawner } from "effect/process";
3
3
  import type { Bivariant } from "@shivaedev/types/Bivariant.ts";
4
+ import { validOrFail } from "#decoded.ts";
4
5
  import type { ExceptionDeclaration } from "#exceptions/declaration.ts";
5
6
  import { describeIssue, type StandardSchemaV1 } from "./standardSchema.ts";
6
7
 
@@ -57,6 +58,7 @@ interface RuleDefinition<TId extends string, TOptions, TServices> {
57
58
  readonly description: string;
58
59
  readonly id: TId;
59
60
  readonly registrable?: false;
61
+ readonly validate?: (context: RuleContext<TOptions>) => readonly string[];
60
62
  }
61
63
 
62
64
  interface RuleDefinitionWithOptions<TId extends string, TInput, TOptions, TServices> extends RuleDefinition<TId, TOptions, TServices> {
@@ -78,7 +80,9 @@ const noOptions: StandardSchemaV1<undefined, undefined> = {
78
80
  function configureWith<TInput, TOptions, TServices>(
79
81
  schema: StandardSchemaV1<TInput, TOptions>,
80
82
  check: RuleDefinition<string, TOptions, TServices>["check"],
83
+ id: string,
81
84
  absent: unknown,
85
+ validate?: RuleDefinition<string, TOptions, TServices>["validate"],
82
86
  ) {
83
87
  return async (options: unknown): Promise<Configured<TServices>> => {
84
88
  const result = await schema["~standard"].validate(options ?? absent);
@@ -91,6 +95,12 @@ function configureWith<TInput, TOptions, TServices>(
91
95
  check: (inputs) =>
92
96
  Effect.scoped(
93
97
  Effect.gen(function* () {
98
+ const context = { ...inputs, options: value };
99
+ const issues = validate?.(context).map((issue) => `rules.${id}.options: ${issue}`) ?? [];
100
+ yield* validOrFail(
101
+ inputs.configFile ?? "quality.config.ts",
102
+ issues.length === 0 ? { _tag: "Valid", value: undefined } : { _tag: "Invalid", issues },
103
+ );
94
104
  const signal = yield* Effect.abortSignal;
95
105
  const checked = check({ ...inputs, options: value, signal });
96
106
  return yield* Effect.isEffect(checked) ? checked : Effect.promise(() => Promise.resolve(checked));
@@ -111,7 +121,7 @@ export function defineRule<const TId extends string, TInput, TOptions, TServices
111
121
  ): Rule<TId, TInput, TServices> | Rule<TId, undefined, TServices> {
112
122
  const configure =
113
123
  definition.options === undefined
114
- ? configureWith(noOptions, definition.check, undefined)
115
- : configureWith(definition.options, definition.check, {});
124
+ ? configureWith(noOptions, definition.check, definition.id, undefined, definition.validate)
125
+ : configureWith(definition.options, definition.check, definition.id, {}, definition.validate);
116
126
  return { configure, description: definition.description, id: definition.id, registrable: definition.registrable ?? true };
117
127
  }
@@ -1,6 +1,7 @@
1
1
  import { posix } from "node:path";
2
- import { Effect, Order, Schema } from "effect";
2
+ import { Order, Schema } from "effect";
3
3
  import ignore, { type Ignore } from "ignore";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
5
  import { nativeNames } from "#naming/nativeNames.ts";
5
6
  import { packageLayout } from "#naming/packageLayout.ts";
6
7
  import { KEBAB, PASCAL } from "#naming/words.ts";
@@ -11,8 +12,8 @@ const SNAKE = /^[a-z0-9]+(?:_[a-z0-9]+)*$/u;
11
12
  const CODE = /\.[cm]?[jt]sx?$/u;
12
13
 
13
14
  const FolderNamesOptions = Schema.Struct({
14
- content: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
15
- toolOwned: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
15
+ content: GlobDeclarations,
16
+ toolOwned: GlobDeclarations,
16
17
  });
17
18
 
18
19
  function foldersIn(files: readonly string[]): readonly string[] {
@@ -75,11 +76,11 @@ export const folderNames = defineRule({
75
76
  check: async ({ files, options, readText }) => {
76
77
  const layout = await packageLayout({ files, readText });
77
78
  const context: Context = {
78
- content: ignore().add([...options.content]),
79
+ content: ignore().add([...globPatterns(options.content)]),
79
80
  names: layout.names,
80
81
  native: nativeNames(files).folders,
81
82
  stems: stemsIn(files),
82
- toolOwned: ignore().add([...options.toolOwned]),
83
+ toolOwned: ignore().add([...globPatterns(options.toolOwned)]),
83
84
  };
84
85
  return foldersIn(files).flatMap((folder): readonly Finding[] => {
85
86
  const message = messageFor(folder, context);
@@ -90,4 +91,5 @@ export const folderNames = defineRule({
90
91
  "A package folder is named after its package, a module folder after its main file, a content folder in snake_case and every other folder in kebab-case.",
91
92
  id: "files/folder-names",
92
93
  options: Schema.toStandardSchemaV1(FolderNamesOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
94
+ validate: validateGlobs,
93
95
  });
@@ -1,9 +1,11 @@
1
1
  import { posix } from "node:path";
2
- import { Effect, Schema } from "effect";
2
+ import { Schema } from "effect";
3
3
  import ignore from "ignore";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
5
  import { exportFits } from "#naming/exportFits.ts";
5
6
  import { mainExport } from "#naming/mainExport.ts";
6
7
  import { isMigrationFile } from "#naming/migrationFile.ts";
8
+ import { moduleRoot } from "#naming/moduleRoot.ts";
7
9
  import { ownExports } from "#naming/ownExports.ts";
8
10
  import { type PackageLayout, packageLayout } from "#naming/packageLayout.ts";
9
11
  import { CAMEL, KEBAB, sameWord, wordsOf } from "#naming/words.ts";
@@ -28,7 +30,7 @@ const SHAPES =
28
30
  "The file name and the names of its folders spell the export, in any order, and the file's first letter follows the export's case: listItems in items/ is items/list.ts, ItemPanel is ItemPanel.tsx or item/Panel.tsx.";
29
31
 
30
32
  const NamedAfterExportOptions = Schema.Struct({
31
- toolOwned: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
33
+ toolOwned: GlobDeclarations,
32
34
  });
33
35
 
34
36
  function stemOf(path: string): string {
@@ -52,9 +54,6 @@ function nameFinding(file: SourceFile, stem: string, folders: readonly string[])
52
54
  ? undefined
53
55
  : `"${stem}" exports nothing, so it is named in camelCase, such as setupTests.ts. A file that a package.json script or bin runs is kebab-case.`;
54
56
  }
55
- if (exports.length === 1 && only.constant) {
56
- return `"${stem}" exports only the constant ${only.name}. Constants live in a topic file with related constants, such as limits.ts holding MAX_ITEMS and MAX_DEPTH.`;
57
- }
58
57
  if (exports.some((entry) => exportFits(entry.name, stem, folders))) {
59
58
  return undefined;
60
59
  }
@@ -75,7 +74,9 @@ function findingsOf(file: SourceFile, layout: PackageLayout): readonly Finding[]
75
74
  ? []
76
75
  : [{ file: file.path, message: `"${stem}" is run as a script, so it is named in kebab-case, such as build-docs.ts.` }];
77
76
  }
78
- const folder = repeated(stem, folders);
77
+ const root = moduleRoot(file.path);
78
+ const admin = root === undefined ? undefined : /^(?:client|server)\/(?<path>admin\/.+)$/u.exec(file.path.slice(root.length + 1))?.groups?.path;
79
+ const folder = repeated(stem, admin === undefined ? folders : posix.dirname(admin).split("/"));
79
80
  const messages = [
80
81
  nameFinding(file, stem, folders),
81
82
  folder === undefined ? undefined : `"${stem}" repeats its folder "${folder}". The folder is the prefix: items/listItems.ts is items/list.ts.`,
@@ -86,13 +87,14 @@ function findingsOf(file: SourceFile, layout: PackageLayout): readonly Finding[]
86
87
  export const namedAfterExport = defineRule({
87
88
  check: async ({ files, options, readText, sources }) => {
88
89
  const layout = await packageLayout({ files, readText });
89
- const toolOwned = ignore().add([...DEFAULT_TOOL_OWNED, ...options.toolOwned]);
90
+ const toolOwned = ignore().add([...DEFAULT_TOOL_OWNED, ...globPatterns(options.toolOwned)]);
90
91
  return sources
91
92
  .filter((file) => !(TEST.test(file.path) || isMigrationFile(file.path) || toolOwned.ignores(file.path)))
92
93
  .flatMap((file) => findingsOf(file, layout));
93
94
  },
94
95
  description:
95
- "A file is named after its main export, with its folders as the prefix; a file of several exports is a camelCase topic file, and a script is kebab-case. Rename the file or the export; nothing renames them for you.",
96
+ "A file is named after its main export, including a single constant, with its folders as the prefix; module client/admin and server/admin files may repeat names from above the admin folder. A file of several exports is a camelCase topic file, and a script is kebab-case. Rename the file or the export; nothing renames them for you.",
96
97
  id: "files/named-after-export",
97
98
  options: Schema.toStandardSchemaV1(NamedAfterExportOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
99
+ validate: validateGlobs,
98
100
  });
@@ -1,6 +1,7 @@
1
1
  import { posix } from "node:path";
2
- import { Effect, Schema } from "effect";
2
+ import { Schema } from "effect";
3
3
  import ignore, { type Ignore } from "ignore";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
5
  import { nativeNames } from "#naming/nativeNames.ts";
5
6
  import { CAMEL, KEBAB } from "#naming/words.ts";
6
7
  import { defineRule, type Finding } from "#rule.ts";
@@ -39,8 +40,8 @@ const SNAKE = /^[a-z0-9]+(?:__?[a-z0-9]+)*$/u;
39
40
  const CODE = /\.[cm]?[jt]sx?$/u;
40
41
 
41
42
  const OtherNamesOptions = Schema.Struct({
42
- content: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
43
- toolOwned: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
43
+ content: GlobDeclarations,
44
+ toolOwned: GlobDeclarations,
44
45
  });
45
46
 
46
47
  function stylesheetMessage(path: string, stem: string, importedBy: readonly string[]): string | undefined {
@@ -88,10 +89,10 @@ function messageFor(path: string, context: Context): string | undefined {
88
89
  export const otherNames = defineRule({
89
90
  check: async ({ files, options, readText, sources }) => {
90
91
  const context: Context = {
91
- content: ignore().add([...options.content]),
92
+ content: ignore().add([...globPatterns(options.content)]),
92
93
  native: nativeNames(files),
93
94
  stylesheets: await stylesheetImporters({ files, readText, sources }),
94
- toolOwned: ignore().add([...DEFAULT_TOOL_OWNED, ...options.toolOwned]),
95
+ toolOwned: ignore().add([...DEFAULT_TOOL_OWNED, ...globPatterns(options.toolOwned)]),
95
96
  };
96
97
  return files.flatMap((path): readonly Finding[] => {
97
98
  const message = messageFor(path, context);
@@ -102,4 +103,5 @@ export const otherNames = defineRule({
102
103
  "Documents, data, assets and GritQL files are kebab-case, a stylesheet that one component imports is named after it, a Prisma schema is camelCase and content is snake_case.",
103
104
  id: "files/other-names",
104
105
  options: Schema.toStandardSchemaV1(OtherNamesOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
106
+ validate: validateGlobs,
105
107
  });
@@ -21,6 +21,6 @@ export const importsAliased = defineRule({
21
21
  subject: departure.specifier,
22
22
  })),
23
23
  description:
24
- "A relative import names only a file in its own folder. Every other import goes through an alias: the package.json `imports` of its package or another workspace package's name.",
24
+ "A relative import names only a file in its own folder, except a module's client or server registration may import its own ./admin/ subtree. Every other import goes through an alias: the package.json `imports` of its package or another workspace package's name.",
25
25
  id: "imports/aliased",
26
26
  });
@@ -1,10 +1,12 @@
1
- import { Effect, Schema } from "effect";
1
+ import { matchesGlob } from "node:path";
2
+ import { Schema } from "effect";
3
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
2
4
  import { defineRule } from "#rule.ts";
3
5
  import { matchesAny } from "./matchesAny.ts";
4
6
  import { sqlTexts } from "./sqlText.ts";
5
7
 
6
8
  const AuthSqlOptions = Schema.Struct({
7
- owners: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
9
+ owners: GlobDeclarations,
8
10
  });
9
11
 
10
12
  const TOKENS = /--[^\n]*|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|[\w$]+|[.,;()]/gu;
@@ -126,7 +128,7 @@ function authTableIn(text: string): boolean {
126
128
  export const authSql = defineRule({
127
129
  check: async ({ options, ...inputs }) =>
128
130
  (await sqlTexts(inputs))
129
- .filter((query) => !matchesAny(query.file, options.owners) && authTableIn(query.text))
131
+ .filter((query) => !matchesAny(query.file, globPatterns(options.owners)) && authTableIn(query.text))
130
132
  .map((query) => ({
131
133
  file: query.file,
132
134
  line: query.line,
@@ -136,4 +138,5 @@ export const authSql = defineRule({
136
138
  description: "Apps reference user IDs by foreign key and use identity for account data.",
137
139
  id: "boundaries/auth-sql",
138
140
  options: Schema.toStandardSchemaV1(AuthSqlOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
141
+ validate: (context) => validateGlobs(context, matchesGlob),
139
142
  });
@@ -0,0 +1,20 @@
1
+ import ts from "typescript";
2
+
3
+ export type Origin = "factory" | "kit" | "story" | "plain" | "suite" | "vitest" | "stories" | "function" | readonly Origin[] | undefined;
4
+
5
+ export function commonOrigin(values: readonly Origin[]): Origin {
6
+ const first = values[0];
7
+ if (values.length === 0 || values.every((value) => value === first)) {
8
+ return first;
9
+ }
10
+ if (typeof first !== "object" || !values.every((value) => typeof value === "object" && value.length === first.length)) {
11
+ return undefined;
12
+ }
13
+ return first.map((_, index) => commonOrigin(values.map((value) => (typeof value === "object" ? value[index] : undefined))));
14
+ }
15
+
16
+ export function iterationOrigin(node: ts.Node, origin: (node: ts.Node) => Origin): Origin {
17
+ const loop = node.parent.parent;
18
+ const values = ts.isForOfStatement(loop) ? origin(loop.expression) : undefined;
19
+ return typeof values === "object" ? commonOrigin(values) : undefined;
20
+ }
@@ -1,5 +1,7 @@
1
- import { Effect, Schema } from "effect";
1
+ import { matchesGlob } from "node:path";
2
+ import { Schema } from "effect";
2
3
  import ts from "typescript";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
3
5
  import { defineRule } from "#rule.ts";
4
6
  import { matchesAny } from "./matchesAny.ts";
5
7
  import { memberName, nodesWhere, numericValue, syntaxFindings, unwrapped } from "./syntax.ts";
@@ -8,7 +10,7 @@ const MESSAGE =
8
10
  "Branches on an HTTP error status outside the HTTP edge. Handle the typed domain error here and translate it to an HTTP status in the configured edge module.";
9
11
 
10
12
  const HttpStatusOptions = Schema.Struct({
11
- edge: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
13
+ edge: GlobDeclarations,
12
14
  });
13
15
 
14
16
  const COMPARISONS = new Set([
@@ -48,9 +50,10 @@ function statusBranch(node: ts.Node): boolean {
48
50
  export const httpStatus = defineRule({
49
51
  check: ({ sources, options }) =>
50
52
  sources
51
- .filter((file) => !matchesAny(file.path, options.edge))
53
+ .filter((file) => !matchesAny(file.path, globPatterns(options.edge)))
52
54
  .flatMap((file) => syntaxFindings(file, (source) => nodesWhere(source, statusBranch), MESSAGE)),
53
55
  description: "HTTP status numbers belong at the repository's HTTP edge; domain code handles typed errors.",
54
56
  id: "boundaries/http-status",
55
57
  options: Schema.toStandardSchemaV1(HttpStatusOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
58
+ validate: (context) => validateGlobs(context, matchesGlob),
56
59
  });
@@ -1,6 +1,8 @@
1
+ import { Effect } from "effect";
1
2
  import ts from "typescript";
2
3
  import { defineRule } from "#rule.ts";
3
- import { isSpec, memberName, nodesWhere, numericValue, syntaxFindings, unwrapped } from "./syntax.ts";
4
+ import { storySources } from "./sources.ts";
5
+ import { memberName, nodesWhere, numericValue, syntaxFindings, unwrapped } from "./syntax.ts";
4
6
 
5
7
  const MESSAGE =
6
8
  'Passes a numeric literal or a matcher-only spec-local numeric const to toBe or toHaveLength. Assert the observed items, write the literal where accepted (zero or a process exitCode), or derive the value from the story\'s inputs. For HTTP statuses, import * as HttpStatus from "effect/http/HttpStatus" and use HttpStatus.fromLiteral("NotFound"), for example.';
@@ -87,10 +89,9 @@ function numericAssertion(node: ts.Node): boolean {
87
89
  }
88
90
 
89
91
  export const namedValues = defineRule({
90
- check: ({ sources }) =>
91
- sources
92
- .filter((file) => isSpec(file.path))
93
- .flatMap((file) =>
92
+ check: (inputs) =>
93
+ Effect.map(storySources(inputs), (stories) =>
94
+ stories.flatMap((file) =>
94
95
  syntaxFindings(
95
96
  file,
96
97
  (source) => {
@@ -100,6 +101,7 @@ export const namedValues = defineRule({
100
101
  MESSAGE,
101
102
  ),
102
103
  ),
104
+ ),
103
105
  description: "Stories assert observed items or named values instead of bare counts and numbers.",
104
106
  id: "tests/named-values",
105
107
  });
@@ -1,6 +1,8 @@
1
+ import { Effect } from "effect";
1
2
  import ts from "typescript";
2
3
  import { defineRule } from "#rule.ts";
3
- import { isSpec, memberName, nodesWhere, syntaxFindings, unwrapped } from "./syntax.ts";
4
+ import { storySources } from "./sources.ts";
5
+ import { memberName, nodesWhere, syntaxFindings, unwrapped } from "./syntax.ts";
4
6
 
5
7
  const MESSAGE =
6
8
  "Imports a MAX_* constant from a limits module. Tell a story about the observed behavior instead of asserting a copy of the implementation's cap.";
@@ -74,7 +76,7 @@ function capImports(source: ts.SourceFile): readonly ts.Node[] {
74
76
  }
75
77
 
76
78
  export const noLimitImports = defineRule({
77
- check: ({ sources }) => sources.filter((file) => isSpec(file.path)).flatMap((file) => syntaxFindings(file, capImports, MESSAGE)),
79
+ check: (inputs) => Effect.map(storySources(inputs), (stories) => stories.flatMap((file) => syntaxFindings(file, capImports, MESSAGE))),
78
80
  description: "Stories prove behavior instead of importing implementation caps from limits modules.",
79
81
  id: "tests/no-limit-imports",
80
82
  });
@@ -2,12 +2,11 @@ import { join } from "node:path";
2
2
  import ts from "typescript";
3
3
  import type { ImportGraph } from "#imports/graph.ts";
4
4
  import type { RuleInputs } from "#rule.ts";
5
+ import { iterationOrigin, type Origin } from "./collectionOrigins.ts";
5
6
  import { importOrigin } from "./importOrigin.ts";
6
7
  import { storyProgram } from "./program.ts";
7
8
  import { returnValues } from "./returnValues.ts";
8
9
 
9
- type Origin = "factory" | "kit" | "story" | "plain" | "suite" | "vitest" | "stories" | "function" | undefined;
10
-
11
10
  function importFrom(node: ts.Node): string | undefined {
12
11
  for (let current: ts.Node | undefined = node; current !== undefined; current = current.parent) {
13
12
  if (ts.isImportDeclaration(current) && ts.isStringLiteral(current.moduleSpecifier)) {
@@ -27,9 +26,12 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
27
26
  if (!ts.isVariableDeclaration(node.parent.parent)) {
28
27
  return undefined;
29
28
  }
30
- const value = node.parent.parent.initializer;
29
+ const value = visit(node.parent.parent);
30
+ if (ts.isArrayBindingPattern(node.parent)) {
31
+ return typeof value === "object" ? value[node.parent.elements.indexOf(node)] : undefined;
32
+ }
31
33
  const name = node.propertyName ?? node.name;
32
- return value !== undefined && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? member(value, name.text) : undefined;
34
+ return ts.isIdentifier(name) || ts.isStringLiteral(name) ? member(value, name.text) : undefined;
33
35
  }
34
36
 
35
37
  function declaration(node: ts.Node): Origin {
@@ -40,7 +42,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
40
42
  return importOrigin(importFrom(node));
41
43
  }
42
44
  if (ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)) {
43
- return node.initializer === undefined ? undefined : origin(node.initializer);
45
+ return node.initializer === undefined ? iterationOrigin(node, visit) : visit(node.initializer);
44
46
  }
45
47
  return localBinding(node);
46
48
  }
@@ -72,8 +74,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
72
74
  return undefined;
73
75
  }
74
76
 
75
- function member(value: ts.Expression, name: string): Origin {
76
- const receiver = visit(value);
77
+ function member(receiver: Origin, name: string): Origin {
77
78
  if (receiver === "kit" && name === "it") {
78
79
  return "story";
79
80
  }
@@ -99,6 +100,9 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
99
100
  if (ts.isObjectLiteralExpression(node)) {
100
101
  return object(node);
101
102
  }
103
+ if (ts.isArrayLiteralExpression(node)) {
104
+ return node.elements.map(visit);
105
+ }
102
106
  return expression(node);
103
107
  }
104
108
 
@@ -119,7 +123,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
119
123
  return call(node);
120
124
  }
121
125
  if (ts.isPropertyAccessExpression(node)) {
122
- return member(node.expression, node.name.text) ?? symbol(checker.getSymbolAtLocation(node.name));
126
+ return member(visit(node.expression), node.name.text) ?? symbol(checker.getSymbolAtLocation(node.name));
123
127
  }
124
128
  return ts.isIdentifier(node) ? identifier(node) : declaration(node);
125
129
  }