@shivaedev/quality 0.48.2 → 0.49.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 (95) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +12 -10
  3. package/biome/plugins/ambient-runtime.grit +67 -1
  4. package/biome/plugins/type-re-exports.grit +33 -4
  5. package/dist/adapters/biome/run.js +4 -4
  6. package/dist/adapters/biome/run.js.map +1 -1
  7. package/dist/adapters/knip/configuration.d.ts +5 -2
  8. package/dist/adapters/knip/configuration.d.ts.map +1 -1
  9. package/dist/adapters/knip/configuration.js +12 -5
  10. package/dist/adapters/knip/configuration.js.map +1 -1
  11. package/dist/adapters/knip/run.d.ts +2 -3
  12. package/dist/adapters/knip/run.d.ts.map +1 -1
  13. package/dist/adapters/knip/run.js +25 -7
  14. package/dist/adapters/knip/run.js.map +1 -1
  15. package/dist/adapters/knip/sourceConfig.d.ts.map +1 -1
  16. package/dist/adapters/knip/sourceConfig.js +3 -0
  17. package/dist/adapters/knip/sourceConfig.js.map +1 -1
  18. package/dist/baseline/looseStagedEntries.d.ts +4 -0
  19. package/dist/baseline/looseStagedEntries.d.ts.map +1 -0
  20. package/dist/baseline/looseStagedEntries.js +31 -0
  21. package/dist/baseline/looseStagedEntries.js.map +1 -0
  22. package/dist/baseline/update.d.ts +1 -1
  23. package/dist/baseline/update.d.ts.map +1 -1
  24. package/dist/baseline/update.js +3 -3
  25. package/dist/baseline/update.js.map +1 -1
  26. package/dist/cli/args.d.ts +1 -1
  27. package/dist/cli/args.d.ts.map +1 -1
  28. package/dist/cli/args.js +5 -5
  29. package/dist/cli/args.js.map +1 -1
  30. package/dist/cli/baseline.d.ts +1 -1
  31. package/dist/cli/baseline.d.ts.map +1 -1
  32. package/dist/cli/baseline.js +19 -2
  33. package/dist/cli/baseline.js.map +1 -1
  34. package/dist/cli/lint.d.ts +1 -1
  35. package/dist/cli/lint.d.ts.map +1 -1
  36. package/dist/cli/lint.js +11 -2
  37. package/dist/cli/lint.js.map +1 -1
  38. package/dist/cli/messages.d.ts +1 -1
  39. package/dist/cli/messages.d.ts.map +1 -1
  40. package/dist/cli/messages.js +3 -3
  41. package/dist/cli/program.d.ts.map +1 -1
  42. package/dist/cli/program.js +3 -2
  43. package/dist/cli/program.js.map +1 -1
  44. package/dist/hooks/preCommit.js +1 -1
  45. package/dist/hooks/preCommit.js.map +1 -1
  46. package/dist/inventory/collect.js +3 -3
  47. package/dist/inventory/collect.js.map +1 -1
  48. package/dist/inventory/shadcnFiles.d.ts +4 -0
  49. package/dist/inventory/shadcnFiles.d.ts.map +1 -0
  50. package/dist/inventory/shadcnFiles.js +83 -0
  51. package/dist/inventory/shadcnFiles.js.map +1 -0
  52. package/dist/report/render.d.ts.map +1 -1
  53. package/dist/report/render.js +3 -10
  54. package/dist/report/render.js.map +1 -1
  55. package/dist/report/staleSections.js +1 -1
  56. package/dist/report/staleSections.js.map +1 -1
  57. package/dist/rules/builtIn.d.ts +1 -1
  58. package/dist/rules/importOrigins.d.ts +4 -0
  59. package/dist/rules/importOrigins.d.ts.map +1 -0
  60. package/dist/rules/importOrigins.js +36 -0
  61. package/dist/rules/importOrigins.js.map +1 -0
  62. package/dist/rules/noBarrel.d.ts.map +1 -1
  63. package/dist/rules/noBarrel.js +19 -7
  64. package/dist/rules/noBarrel.js.map +1 -1
  65. package/dist/rules/secondNames.d.ts +7 -0
  66. package/dist/rules/secondNames.d.ts.map +1 -0
  67. package/dist/rules/secondNames.js +98 -0
  68. package/dist/rules/secondNames.js.map +1 -0
  69. package/dist/rules/stories/importBindings.d.ts.map +1 -1
  70. package/dist/rules/stories/importBindings.js +3 -0
  71. package/dist/rules/stories/importBindings.js.map +1 -1
  72. package/dist/rules/unusedCode.d.ts +1 -1
  73. package/dist/rules/unusedCode.d.ts.map +1 -1
  74. package/docs/debt-and-hooks.md +5 -5
  75. package/package.json +3 -3
  76. package/src/adapters/biome/run.ts +4 -4
  77. package/src/adapters/knip/configuration.ts +12 -5
  78. package/src/adapters/knip/run.ts +27 -7
  79. package/src/adapters/knip/sourceConfig.ts +3 -0
  80. package/src/baseline/looseStagedEntries.ts +32 -0
  81. package/src/baseline/update.ts +5 -2
  82. package/src/cli/args.ts +6 -7
  83. package/src/cli/baseline.ts +19 -1
  84. package/src/cli/lint.ts +11 -1
  85. package/src/cli/messages.ts +3 -3
  86. package/src/cli/program.ts +3 -2
  87. package/src/hooks/preCommit.ts +1 -1
  88. package/src/inventory/collect.ts +3 -3
  89. package/src/inventory/shadcnFiles.ts +87 -0
  90. package/src/report/render.ts +3 -10
  91. package/src/report/staleSections.ts +1 -1
  92. package/src/rules/importOrigins.ts +38 -0
  93. package/src/rules/noBarrel.ts +21 -8
  94. package/src/rules/secondNames.ts +121 -0
  95. package/src/rules/stories/importBindings.ts +3 -0
package/src/cli/args.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { Result } from "effect";
3
- import { USAGE as COMMAND_USAGE, SUBCOMMANDS } from "./messages.ts";
3
+ import { SUBCOMMANDS } from "./messages.ts";
4
4
 
5
5
  export type Command =
6
6
  | { readonly _tag: "Ci"; readonly coverage: boolean }
@@ -10,7 +10,7 @@ export type Command =
10
10
  | { readonly _tag: "Fix"; readonly config: string | undefined; readonly rules: readonly string[] }
11
11
  | { readonly _tag: "BaselineMerge"; readonly base: string; readonly ours: string; readonly theirs: string }
12
12
  | { readonly _tag: "BaselineInstallDriver" }
13
- | { readonly _tag: "BaselineWrite"; readonly config: string | undefined; readonly rules: readonly string[] }
13
+ | { readonly _tag: "BaselineWrite"; readonly config: string | undefined; readonly rules: readonly string[]; readonly files: readonly string[] }
14
14
  | { readonly _tag: "BaselinePrune"; readonly config: string | undefined; readonly against: string | undefined }
15
15
  | { readonly _tag: "BaselineTighten"; readonly config: string | undefined; readonly staged: boolean }
16
16
  | { readonly _tag: "BaselineMigrate"; readonly config: string | undefined; readonly from: string | undefined }
@@ -22,12 +22,11 @@ export type Command =
22
22
 
23
23
  export type Parsed = { readonly _tag: "Parsed"; readonly command: Command } | { readonly _tag: "Usage"; readonly problem: string };
24
24
 
25
- export const USAGE = COMMAND_USAGE;
26
-
27
25
  const OPTIONS = {
28
26
  against: { type: "string" },
29
27
  config: { type: "string" },
30
28
  coverage: { type: "boolean" },
29
+ file: { multiple: true, type: "string" },
31
30
  force: { type: "boolean" },
32
31
  from: { type: "string" },
33
32
  help: { short: "h", type: "boolean" },
@@ -47,14 +46,14 @@ type Values = ReturnType<typeof parseArgs<{ options: typeof OPTIONS; allowPositi
47
46
 
48
47
  type Option = Exclude<keyof Values, "config" | "help">;
49
48
 
50
- const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "force", "from", "rule", "staged"];
49
+ const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "file", "force", "from", "rule", "staged"];
51
50
 
52
51
  const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
53
52
  "baseline install-driver": [],
54
53
  "baseline migrate": ["from"],
55
54
  "baseline prune": ["against"],
56
55
  "baseline tighten": ["staged"],
57
- "baseline write": ["rule"],
56
+ "baseline write": ["rule", "file"],
58
57
  ci: ["coverage"],
59
58
  "exceptions migrate": ["from"],
60
59
  fix: ["rule"],
@@ -92,7 +91,7 @@ function commandFor(name: string, values: Values): Parsed {
92
91
  case "baseline install-driver":
93
92
  return parsed({ _tag: "BaselineInstallDriver" });
94
93
  case "baseline write":
95
- return parsed({ _tag: "BaselineWrite", config, rules: values.rule ?? [] });
94
+ return parsed({ _tag: "BaselineWrite", config, files: values.file ?? [], rules: values.rule ?? [] });
96
95
  case "baseline prune":
97
96
  return ref(values.against, { _tag: "BaselinePrune", against: values.against, config });
98
97
  case "baseline tighten":
@@ -1,3 +1,4 @@
1
+ import { relative, resolve } from "node:path";
1
2
  import { Console, Effect, type FileSystem } from "effect";
2
3
  import type { BaselineEntry } from "#baseline/format.ts";
3
4
  import { saveShards } from "#baseline/shards.ts";
@@ -5,6 +6,7 @@ import { adopt, type Pruned, prune, type Scope } from "#baseline/update.ts";
5
6
  import { openSession, type Session } from "#engine/session.ts";
6
7
  import { applyRegistry } from "#exceptions/registry.ts";
7
8
  import { SetupFailure } from "#failure.ts";
9
+ import { changesSince } from "#git/history.ts";
8
10
  import { plural } from "#report/plural.ts";
9
11
  import type { RuleServices } from "#rule.ts";
10
12
 
@@ -20,10 +22,26 @@ export const writeBaseline = Effect.fn("Cli.writeBaseline")(function* (
20
22
  cwd: string,
21
23
  config: string | undefined,
22
24
  rules: readonly string[],
25
+ files: readonly string[],
23
26
  ): Effect.fn.Return<void, SetupFailure, RuleServices> {
24
27
  const session = yield* openSession(cwd, config);
25
28
  const existing = session.baseline.files.size === 0 ? undefined : session.baseline.entries;
26
- const adoption = adopt(existing, rules, unregistered(session), session.config);
29
+ if (existing !== undefined && files.length === 0) {
30
+ return yield* new SetupFailure({
31
+ message: "baseline write refused: a baseline exists. Record a rule with --rule <id> and --file <path>; use prune for moved or fixed debt.",
32
+ });
33
+ }
34
+ const selected = files.length === 0 ? undefined : new Set(files.map((file) => relative(session.config.root, resolve(session.config.root, file))));
35
+ if (selected !== undefined) {
36
+ const changed = yield* changesSince(session.config.root, ["HEAD"]);
37
+ const outside = [...selected].filter((file) => !changed.files.has(file));
38
+ if (outside.length > 0) {
39
+ return yield* new SetupFailure({
40
+ message: `baseline write refused: outside the current change set: ${outside.join(", ")}. Stage new files with git add first.`,
41
+ });
42
+ }
43
+ }
44
+ const adoption = adopt(existing, rules, unregistered(session), session.config, selected);
27
45
  if (adoption._tag === "Refused") {
28
46
  return yield* new SetupFailure({ message: `baseline write refused:\n${adoption.reasons.map((reason) => ` - ${reason}`).join("\n")}` });
29
47
  }
package/src/cli/lint.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { relative } from "node:path";
2
2
  import { Console, Effect } from "effect";
3
+ import { looseStagedEntries } from "#baseline/looseStagedEntries.ts";
3
4
  import { evaluate, passes } from "#engine/evaluate.ts";
4
5
  import { openSession } from "#engine/session.ts";
6
+ import { keyOf } from "#engine/violation.ts";
5
7
  import { GateFailed, type SetupFailure } from "#failure.ts";
6
8
  import { render } from "#report/render.ts";
7
9
  import type { RuleServices } from "#rule.ts";
@@ -9,9 +11,17 @@ import type { RuleServices } from "#rule.ts";
9
11
  export const lint = Effect.fn("Cli.lint")(function* (
10
12
  cwd: string,
11
13
  config: string | undefined,
14
+ staged = false,
12
15
  ): Effect.fn.Return<void, SetupFailure | GateFailed, RuleServices> {
13
16
  const session = yield* openSession(cwd, config);
14
- const outcome = evaluate(session.violations, session.registry, session.baseline.entries, session.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
+ };
15
25
  yield* Console.log(
16
26
  render(outcome, {
17
27
  baseline: session.config.baseline,
@@ -6,7 +6,7 @@ export const USAGE = `Usage:
6
6
  quality exceptions migrate [--config <file>] [--from <registry>]
7
7
  quality baseline merge <ancestor> <current> <other>
8
8
  quality baseline install-driver
9
- quality baseline write [--config <file>] [--rule <id>]...
9
+ quality baseline write [--config <file>] [--rule <id>]... [--file <path>]...
10
10
  quality baseline prune [--config <file>] [--against <ref>]
11
11
  quality baseline tighten [--config <file>] [--staged]
12
12
  quality baseline migrate [--config <file>] [--from <file>]
@@ -24,7 +24,7 @@ fix Sort every package.json, apply Biome's lint fixes, unsafe ones
24
24
  exceptions migrate Move legacy registry entries and Biome declarations into quality.config.ts exceptions and remove matching root overrides.
25
25
  baseline merge Merge Git baseline versions into <current>: deletions win and counts take the minimum.
26
26
  baseline install-driver Configure only the repository-local merge.quality-baseline.driver setting.
27
- baseline write Record current error-level violations. Creates the baseline, or records the named rules again, replacing their entries.
27
+ baseline write Adopt initial debt once, or record named rules only for --file paths changed since HEAD. Stage new files first.
28
28
  baseline prune Drop fixed debt, lower entries to what is left and carry entries to files git saw move. Never adds or raises an entry.
29
29
  baseline tighten Prune only the entries of files changed since HEAD, or with --staged, in the index.
30
30
  baseline migrate Move a JSON or JSON Lines baseline (--from, quality/baseline.json by default) into root and package shards.
@@ -32,7 +32,7 @@ hooks install Install the git pre-commit hook, shared by every worktree, tha
32
32
  unless --force replaces it.
33
33
  hooks uninstall Remove quality's pre-commit hook. Keeps a hook that is not quality's.
34
34
  hooks status Check that git's effective hooks path runs Quality's pre-commit hook and report global chaining.
35
- hooks pre-commit What the hook runs: lint, then package.json scripts typecheck and quality:commit when present.
35
+ hooks pre-commit Check lint and staged baseline counts, then package.json scripts typecheck and quality:commit when present.
36
36
 
37
37
  --config <file> Config file; its directory is the repository root. Without this option, uses ./quality.config.ts when present, otherwise defaults.
38
38
  --against <ref> The branch the work merges into, whose merge base prune follows moves from. Defaults to origin/HEAD, then origin/main, then origin/master.
@@ -1,7 +1,7 @@
1
1
  import { Console, Effect } from "effect";
2
2
  import { installDriver } from "#baseline/installDriver.ts";
3
3
  import { mergeBaseline } from "#baseline/merge.ts";
4
- import { parseCommand, USAGE } from "#cli/args.ts";
4
+ import { parseCommand } from "#cli/args.ts";
5
5
  import { writeBaseline } from "#cli/baseline.ts";
6
6
  import { ci } from "#cli/ci.ts";
7
7
  import { fix } from "#cli/fix.ts";
@@ -17,6 +17,7 @@ import { preCommitHook } from "#hooks/preCommit.ts";
17
17
  import { setupHook } from "#hooks/setup.ts";
18
18
  import { hookStatus } from "#hooks/status.ts";
19
19
  import { uninstallHook } from "#hooks/uninstall.ts";
20
+ import { USAGE } from "./messages.ts";
20
21
 
21
22
  export interface Invocation {
22
23
  readonly cwd: string;
@@ -45,7 +46,7 @@ export const program = Effect.fn("Cli.program")(function* (args: readonly string
45
46
  case "BaselineInstallDriver":
46
47
  return yield* installDriver(cwd, launch);
47
48
  case "BaselineWrite":
48
- return yield* writeBaseline(cwd, command.config, command.rules);
49
+ return yield* writeBaseline(cwd, command.config, command.rules, command.files);
49
50
  case "BaselinePrune":
50
51
  return yield* pruneBaseline(cwd, command.config, command.against);
51
52
  case "BaselineTighten":
@@ -42,7 +42,7 @@ const runScript = Effect.fnUntraced(
42
42
  export const preCommitHook = Effect.fn("Hooks.preCommitHook")(function* (cwd: string, path: string | undefined) {
43
43
  const config = yield* loadConfig(cwd, path);
44
44
  const { manager, scripts } = yield* commitScripts(config.root);
45
- const linted = yield* lint(cwd, path).pipe(
45
+ const linted = yield* lint(cwd, path, true).pipe(
46
46
  Effect.as(true),
47
47
  Effect.catchTag("GateFailed", () => Effect.succeed(false)),
48
48
  );
@@ -7,7 +7,7 @@ import type { RuleServices, SourceFile } from "#rule.ts";
7
7
  import { FilesystemFailure, orWhenAbsent, readRequiredText } from "./filesystem.ts";
8
8
  import { posix } from "./ignoreScope.ts";
9
9
  import { linesOf } from "./linesOf.ts";
10
- import { shadcnFolders } from "./shadcnFolders.ts";
10
+ import { shadcnFiles } from "./shadcnFiles.ts";
11
11
  import { scopeAbove, walk } from "./walk.ts";
12
12
 
13
13
  export interface InventoryScope {
@@ -49,12 +49,12 @@ export const collectInventory = Effect.fn("Inventory.collectInventory")(function
49
49
  scope: InventoryScope,
50
50
  ): Effect.fn.Return<Inventory, FilesystemFailure | SetupFailure, RuleServices> {
51
51
  const excluded = ignore().add([...scope.exclude]);
52
- const toolOwned = yield* shadcnFolders(root);
52
+ const toolOwned = new Set(yield* shadcnFiles(root));
53
53
  const zones = yield* Effect.forEach(scope.sources, (zone) => zoneFiles(root, zone), { concurrency: READ_CONCURRENCY });
54
54
  const relativePaths = zones.flat().map((absolute) => posix(relative(root, absolute)));
55
55
  const files = [...new Set(relativePaths)]
56
56
  .filter((path) => !excluded.ignores(path))
57
- .filter((path) => !toolOwned.some((folder) => path.startsWith(`${folder}/`)))
57
+ .filter((path) => !toolOwned.has(path))
58
58
  .sort((left, right) => {
59
59
  if (left === right) {
60
60
  return 0;
@@ -0,0 +1,87 @@
1
+ import { basename, join, matchesGlob, relative } from "node:path";
2
+ import { Effect } from "effect";
3
+ import { posix } from "./ignoreScope.ts";
4
+ import { shadcnFolders } from "./shadcnFolders.ts";
5
+ import { walk } from "./walk.ts";
6
+
7
+ // Registry item names are the CLI ownership convention; custom names stay authored.
8
+ const COMPONENTS = [
9
+ "accordion",
10
+ "alert",
11
+ "alert-dialog",
12
+ "aspect-ratio",
13
+ "attachment",
14
+ "avatar",
15
+ "badge",
16
+ "breadcrumb",
17
+ "bubble",
18
+ "button",
19
+ "button-group",
20
+ "calendar",
21
+ "card",
22
+ "carousel",
23
+ "chart",
24
+ "checkbox",
25
+ "collapsible",
26
+ "combobox",
27
+ "command",
28
+ "context-menu",
29
+ "dialog",
30
+ "direction",
31
+ "drawer",
32
+ "dropdown-menu",
33
+ "empty",
34
+ "field",
35
+ "form",
36
+ "hover-card",
37
+ "input",
38
+ "input-group",
39
+ "input-otp",
40
+ "item",
41
+ "kbd",
42
+ "label",
43
+ "marker",
44
+ "menubar",
45
+ "message",
46
+ "message-scroller",
47
+ "native-select",
48
+ "navigation-menu",
49
+ "pagination",
50
+ "popover",
51
+ "progress",
52
+ "radio-group",
53
+ "resizable",
54
+ "scroll-area",
55
+ "select",
56
+ "separator",
57
+ "sheet",
58
+ "sidebar",
59
+ "skeleton",
60
+ "slider",
61
+ "sonner",
62
+ "spinner",
63
+ "switch",
64
+ "table",
65
+ "tabs",
66
+ "textarea",
67
+ "toast",
68
+ "toaster",
69
+ "toggle",
70
+ "toggle-group",
71
+ "tooltip",
72
+ ];
73
+
74
+ export const SHADCN_FILE_GLOB = `{${COMPONENTS.join(",")}}.{ts,tsx,js,jsx}`;
75
+
76
+ export const shadcnFiles = Effect.fn("Inventory.shadcnFiles")(function* (root: string) {
77
+ const folders = yield* shadcnFolders(root);
78
+ const files = yield* Effect.forEach(folders, (folder) => walk(join(root, folder)));
79
+ return [
80
+ ...new Set(
81
+ files
82
+ .flat()
83
+ .filter((path) => matchesGlob(basename(path), SHADCN_FILE_GLOB))
84
+ .map((path) => posix(relative(root, path))),
85
+ ),
86
+ ];
87
+ });
@@ -60,15 +60,8 @@ function summary(outcome: Outcome, context: ReportContext): string {
60
60
  return `${verdict}. ${plural(context.checked, "source file")} checked${suppressed}.`;
61
61
  }
62
62
 
63
- function rerecord(outcome: Outcome): readonly string[] {
64
- const rules = [...new Set(outcome.errors.map((violation) => violation.rule))].sort((left, right) => left.localeCompare(right));
65
- if (rules.length === 0) {
66
- return [];
67
- }
68
- const command = ["quality baseline write", ...rules.map((rule) => `--rule ${rule}`)].join(" ");
69
- return [
70
- `If the baseline should keep these findings, such as the debt of a moved or renamed file, record them again with \`${command}\` and call out the baseline growth in the pull request description.`,
71
- ];
63
+ function movedDebt(outcome: Outcome): readonly string[] {
64
+ return passes(outcome) ? [] : ["For moved files, carry their existing debt with `quality baseline prune --against <base>`."];
72
65
  }
73
66
 
74
67
  export function render(outcome: Outcome, context: ReportContext): string {
@@ -77,6 +70,6 @@ export function render(outcome: Outcome, context: ReportContext): string {
77
70
  ...ruleSections(outcome.errors, context, regressions),
78
71
  ...staleSections(outcome, context),
79
72
  summary(outcome, context),
80
- ...rerecord(outcome),
73
+ ...movedDebt(outcome),
81
74
  ].join("\n\n");
82
75
  }
@@ -27,7 +27,7 @@ export function staleSections(outcome: Outcome, files: StaleFiles): readonly str
27
27
  ...section(
28
28
  "error",
29
29
  files.baseline,
30
- "An entry for an unknown rule covers nothing. Run `quality baseline prune` to drop it.",
30
+ "Drop unknown rules with `quality baseline prune`. Lower staged counts with `quality baseline tighten --staged`, then stage the baseline.",
31
31
  outcome.staleBaseline.map(baselineLine),
32
32
  ),
33
33
  ...section(
@@ -0,0 +1,38 @@
1
+ import ts from "typescript";
2
+ import { importBindings } from "#rules/stories/importBindings.ts";
3
+
4
+ function constantOrigins(source: ts.SourceFile, origins: Map<string, string>): void {
5
+ for (const statement of source.statements) {
6
+ if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0) {
7
+ continue;
8
+ }
9
+ for (const declaration of statement.declarationList.declarations) {
10
+ if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) {
11
+ continue;
12
+ }
13
+ const origin = originOf(declaration.initializer, origins);
14
+ if (origin !== undefined) {
15
+ origins.set(declaration.name.text, origin);
16
+ }
17
+ }
18
+ }
19
+ }
20
+
21
+ export function importOrigins(source: ts.SourceFile): ReadonlyMap<string, string> {
22
+ const origins = new Map([...importBindings(source)].map(([name, binding]) => [name, binding.module]));
23
+ constantOrigins(source, origins);
24
+ return origins;
25
+ }
26
+
27
+ export function originOf(node: ts.Node, origins: ReadonlyMap<string, string>): string | undefined {
28
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
29
+ return originOf(node.expression, origins);
30
+ }
31
+ if (ts.isIdentifier(node)) {
32
+ return origins.get(node.text);
33
+ }
34
+ if (ts.isPropertyAccessExpression(node)) {
35
+ return originOf(node.expression, origins);
36
+ }
37
+ return undefined;
38
+ }
@@ -1,16 +1,29 @@
1
1
  import { posix } from "node:path";
2
- import { defineRule } from "#rule.ts";
2
+ import { defineRule, type Finding } from "#rule.ts";
3
+ import { parse } from "./parse.ts";
4
+ import { secondNames } from "./secondNames.ts";
3
5
 
4
6
  const BARREL_FILE = /^index\.tsx?$/u;
5
7
 
6
8
  export const noBarrel = defineRule({
7
9
  check: ({ sources }) =>
8
- sources
9
- .filter((file) => BARREL_FILE.test(posix.basename(file.path)))
10
- .map((file) => ({
11
- file: file.path,
12
- message: "index.ts and index.tsx modules are banned. Name the module after its purpose and import it directly.",
13
- })),
14
- description: "Name TypeScript modules after their purpose instead of index.ts or index.tsx.",
10
+ sources.flatMap((file) => {
11
+ const findings: Finding[] = BARREL_FILE.test(posix.basename(file.path))
12
+ ? [{ file: file.path, message: "index.ts and index.tsx modules are banned. Name the module after its purpose and import it directly." }]
13
+ : [];
14
+ const source = parse(file);
15
+ if (source !== undefined) {
16
+ for (const { modules, node } of secondNames(source)) {
17
+ findings.push({
18
+ file: file.path,
19
+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
20
+ message: `An exported alias, facade or forwarding function gives an import a second name.\nHelp: Import directly from ${modules.map((module) => `"${module}"`).join(", ")} and remove the second name.`,
21
+ });
22
+ }
23
+ }
24
+ return findings;
25
+ }),
26
+ description:
27
+ "Name modules after their purpose; import values from their defining module instead of exporting aliases, facades or unchanged forwarding calls.",
15
28
  id: "structure/no-barrel",
16
29
  });
@@ -0,0 +1,121 @@
1
+ import ts from "typescript";
2
+ import { importOrigins, originOf } from "./importOrigins.ts";
3
+
4
+ function returned(body: ts.ConciseBody): ts.Expression | undefined {
5
+ if (!ts.isBlock(body)) {
6
+ return body;
7
+ }
8
+ const statement = body.statements.length === 1 ? body.statements[0] : undefined;
9
+ return statement !== undefined && ts.isReturnStatement(statement) ? statement.expression : undefined;
10
+ }
11
+
12
+ function forwarding(node: ts.FunctionLikeDeclaration, origins: ReadonlyMap<string, string>): string | undefined {
13
+ if (
14
+ node.body === undefined
15
+ || node.asteriskToken !== undefined
16
+ || node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)
17
+ ) {
18
+ return undefined;
19
+ }
20
+ const call = returned(node.body);
21
+ if (call === undefined || !ts.isCallExpression(call) || call.questionDotToken !== undefined || call.arguments.length !== node.parameters.length) {
22
+ return undefined;
23
+ }
24
+ const visible = new Map(origins);
25
+ for (const [index, parameter] of node.parameters.entries()) {
26
+ const argument = call.arguments[index];
27
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer !== undefined || argument === undefined) {
28
+ return undefined;
29
+ }
30
+ const value = ts.isSpreadElement(argument) ? argument.expression : argument;
31
+ if (!ts.isIdentifier(value) || value.text !== parameter.name.text || Boolean(parameter.dotDotDotToken) !== ts.isSpreadElement(argument)) {
32
+ return undefined;
33
+ }
34
+ visible.delete(parameter.name.text);
35
+ }
36
+ return originOf(call.expression, visible);
37
+ }
38
+
39
+ function valueOrigins(node: ts.Expression, origins: ReadonlyMap<string, string>): readonly string[] {
40
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
41
+ return valueOrigins(node.expression, origins);
42
+ }
43
+ const origin = originOf(node, origins);
44
+ if (origin !== undefined) {
45
+ return [origin];
46
+ }
47
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
48
+ const module = forwarding(node, origins);
49
+ return module === undefined ? [] : [module];
50
+ }
51
+ if (ts.isObjectLiteralExpression(node)) {
52
+ const modules = node.properties.map((property) => {
53
+ if (ts.isShorthandPropertyAssignment(property)) {
54
+ return valueOrigins(property.name, origins);
55
+ }
56
+ if (ts.isPropertyAssignment(property)) {
57
+ return valueOrigins(property.initializer, origins);
58
+ }
59
+ if (ts.isSpreadAssignment(property)) {
60
+ return valueOrigins(property.expression, origins);
61
+ }
62
+ return [];
63
+ });
64
+ return modules.length > 0 && modules.every((module) => module.length > 0) ? modules.flat() : [];
65
+ }
66
+ return [];
67
+ }
68
+
69
+ export interface SecondName {
70
+ readonly modules: readonly string[];
71
+ readonly node: ts.Node;
72
+ }
73
+
74
+ function exportedNames(source: ts.SourceFile): ReadonlySet<string> {
75
+ return new Set(
76
+ source.statements.flatMap((statement) =>
77
+ ts.isExportDeclaration(statement)
78
+ && statement.moduleSpecifier === undefined
79
+ && statement.exportClause !== undefined
80
+ && ts.isNamedExports(statement.exportClause)
81
+ ? statement.exportClause.elements.map((element) => (element.propertyName ?? element.name).text)
82
+ : [],
83
+ ),
84
+ );
85
+ }
86
+
87
+ function declarations(statement: ts.Statement, exported: ReadonlySet<string>): readonly (ts.VariableDeclaration | ts.FunctionDeclaration)[] {
88
+ const publicStatement =
89
+ ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
90
+ let nodes: readonly (ts.VariableDeclaration | ts.FunctionDeclaration)[] = [];
91
+ if (ts.isVariableStatement(statement)) {
92
+ nodes = statement.declarationList.declarations;
93
+ } else if (ts.isFunctionDeclaration(statement)) {
94
+ nodes = [statement];
95
+ }
96
+ return nodes.filter((node) => node.name !== undefined && ts.isIdentifier(node.name) && (publicStatement || exported.has(node.name.text)));
97
+ }
98
+
99
+ function declarationOrigins(
100
+ node: ts.VariableDeclaration | ts.FunctionDeclaration,
101
+ origins: ReadonlyMap<string, string>,
102
+ source: ts.SourceFile,
103
+ ): readonly string[] {
104
+ if (ts.isVariableDeclaration(node)) {
105
+ return node.initializer === undefined ? [] : valueOrigins(node.initializer, origins);
106
+ }
107
+ const overloaded = source.statements.some((other) => ts.isFunctionDeclaration(other) && other !== node && other.name?.text === node.name?.text);
108
+ const module = overloaded ? undefined : forwarding(node, origins);
109
+ return module === undefined ? [] : [module];
110
+ }
111
+
112
+ export function secondNames(source: ts.SourceFile): readonly SecondName[] {
113
+ const origins = importOrigins(source);
114
+ const exported = exportedNames(source);
115
+ return source.statements.flatMap((statement) =>
116
+ declarations(statement, exported).flatMap((node) => {
117
+ const modules = declarationOrigins(node, origins, source);
118
+ return modules.length === 0 ? [] : [{ modules: [...new Set(modules)], node }];
119
+ }),
120
+ );
121
+ }
@@ -15,6 +15,9 @@ export function importBindings(source: ts.SourceFile): ReadonlyMap<string, Impor
15
15
  }
16
16
  const module = statement.moduleSpecifier.text;
17
17
  const clause = statement.importClause;
18
+ if (clause?.name !== undefined) {
19
+ bindings.set(clause.name.text, { imported: "default", module });
20
+ }
18
21
  const named = clause?.namedBindings;
19
22
  if (named !== undefined && ts.isNamespaceImport(named)) {
20
23
  bindings.set(named.name.text, { imported: NAMESPACE, module });