Skip to content

Commit ac61379

Browse files
kaiserargclaude
andauthored
Lint: packages import only each other's public entry points (#5) (#38)
New ESLint rule inspa/package-boundaries (scripts/eslint-boundaries.mjs) fails bare imports into a package's source (@inspa/<pkg>/src/..., inspa/src/...) and relative imports that leave the file's workspace folder for another one. It checks import/export-from, import(), require(), TS import types and import-equals, and vi.mock()-family calls. The 16 existing crossings are allow-listed one exact import at a time in eslint.config.js with a comment each; a test fails on any entry whose import is gone, so the list only shrinks. Claude-Session: https://claude.ai/code/session_01V8joVCWcEGQMNZz9JkMJmw Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1f41517 commit ac61379

3 files changed

Lines changed: 357 additions & 0 deletions

File tree

‎eslint.config.js‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,50 @@
22
import js from "@eslint/js";
33
import globals from "globals";
44
import tseslint from "typescript-eslint";
5+
import inspa from "./scripts/eslint-boundaries.mjs";
6+
7+
// Imports that crossed a package boundary when the boundary rule landed (#5). Each is `{ file, import }`, the import
8+
// exactly as written. Only remove entries: a new crossing import fails lint, and scripts/eslint-boundaries.test.mjs
9+
// fails on an entry whose import is gone. Owners: e2e specs belong to their feature's lane, the rest to engine.
10+
const BOUNDARY_ALLOW = [
11+
// e2e specs drive the CLI's proxy and MCP selection tool directly; `inspa` exports neither.
12+
{ file: "e2e/proxy-hmr.spec.ts", import: "../packages/cli/src/proxy/index" },
13+
{ file: "e2e/proxy-webpack-hmr.spec.ts", import: "../packages/cli/src/proxy/index" },
14+
{ file: "e2e/runtime-source.spec.ts", import: "../packages/cli/src/proxy/index" },
15+
{ file: "e2e/selection-agent-loop.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
16+
{ file: "e2e/selection-stale-page.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
17+
{ file: "e2e/selection-sync.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
18+
// The demo app's unit tests stamp JSX from source so they run without a build (`@inspa/vite-plugin/transform`
19+
// resolves to dist/).
20+
{ file: "examples/invoices/vitest.config.ts", import: "../../packages/vite-plugin/src/transform.js" },
21+
// Tests from inplace that cross between the proxy (cli) and the overlay's runtime source (vite-plugin), which
22+
// share code neither package exports. They go away when @inspa/overlay and @inspa/daemon are split out.
23+
{ file: "packages/cli/src/mcp/server.test.ts", import: "../../../vite-plugin/src/transform.js" },
24+
{
25+
file: "packages/cli/src/proxy/react19/react19.test.ts",
26+
import: "../../../../vite-plugin/src/overlay/runtime-source/react19/capture.js",
27+
},
28+
{
29+
file: "packages/cli/src/proxy/webpack-runtime.test.ts",
30+
import: "../../../vite-plugin/src/overlay/runtime-source/bundled.js",
31+
},
32+
{
33+
file: "packages/cli/src/proxy/webpack-runtime.test.ts",
34+
import: "../../../vite-plugin/src/overlay/runtime-source/react19/capture.js",
35+
},
36+
{ file: "packages/cli/test/components-api.integration.test.ts", import: "../../vite-plugin/src/transform.js" },
37+
{ file: "packages/core/src/source-resolve.test.ts", import: "../../vite-plugin/src/overlay/runtime-source/hash.js" },
38+
{
39+
file: "packages/vite-plugin/src/overlay/runtime-source/react19/arguments.test.ts",
40+
import: "../../../../../cli/src/proxy/react19/runtime-uses.js",
41+
},
42+
{
43+
file: "packages/vite-plugin/src/overlay/runtime-source/react19/engines.test.ts",
44+
import: "../../../../../cli/src/proxy/react19/runtime-uses.js",
45+
},
46+
// Checks the plugin's token themes against core's; @inspa/core does not export token-themes.
47+
{ file: "packages/vite-plugin/test/token-themes-parity.test.ts", import: "../../core/src/token-themes.js" },
48+
];
549

650
export default tseslint.config(
751
{
@@ -30,4 +74,9 @@ export default tseslint.config(
3074
],
3175
},
3276
},
77+
// Packages import only each other's public entry points (#5, scripts/eslint-boundaries.mjs).
78+
{
79+
plugins: { inspa },
80+
rules: { "inspa/package-boundaries": ["error", { allow: BOUNDARY_ALLOW }] },
81+
},
3382
);

‎scripts/eslint-boundaries.mjs‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// ESLint rule `inspa/package-boundaries` (#5): packages talk only through each other's public entry points
2+
// (docs/architecture.md, rules for the port: "Cross a boundary only through `@inspa/protocol` and public exports").
3+
//
4+
// It reports two kinds of import:
5+
// - a bare import into another package's source: `@inspa/<pkg>/src/...`, or `<workspace name>/src/...`
6+
// (`inspa/src/...`). Import the package name or one of its `exports` subpaths instead.
7+
// - a relative import that leaves the file's package folder for another one (`../../vite-plugin/src/x.js`
8+
// from `packages/cli`, `../packages/cli/src/...` from `e2e/`). A package folder is a workspace folder
9+
// (`packages/*`, `apps/*`, `examples/*` from the root package.json); everything else is the root.
10+
//
11+
// Every way a module path is written down counts: import/export ... from, `import()`, `require()`, TypeScript
12+
// `import("...")` types and `import x = require()`, and vitest's `vi.mock()`-family calls.
13+
//
14+
// Existing violations are allow-listed one by one in eslint.config.js as `{ file, import }` (file relative to the
15+
// repo root, the import exactly as written), each with a comment saying why it is still there. A new import, even
16+
// in an allow-listed file, fails. scripts/eslint-boundaries.test.mjs fails on an allow-list entry whose import is
17+
// gone, so the list only shrinks.
18+
import { existsSync, readdirSync, readFileSync } from "node:fs";
19+
import { dirname, join, relative, resolve, sep } from "node:path";
20+
import { fileURLToPath } from "node:url";
21+
22+
export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
23+
24+
const toPosix = (p) => p.split(sep).join("/");
25+
26+
/** The root package.json's workspace globs as parent folders: `packages/*` -> `packages`. Only `dir/*` globs. */
27+
export function workspaceParents(root = ROOT) {
28+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
29+
const globs = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? []);
30+
return globs.filter((g) => /^[^*]+\/\*$/.test(g)).map((g) => g.slice(0, -2));
31+
}
32+
33+
/** Workspace folder -> its package name (null when the folder has no package.json, e.g. apps/desktop today). */
34+
export function workspaces(root = ROOT) {
35+
const out = new Map();
36+
for (const parent of workspaceParents(root)) {
37+
const dir = join(root, parent);
38+
if (!existsSync(dir)) continue;
39+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
40+
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
41+
const pj = join(dir, entry.name, "package.json");
42+
const name = existsSync(pj) ? (JSON.parse(readFileSync(pj, "utf8")).name ?? null) : null;
43+
out.set(`${parent}/${entry.name}`, name);
44+
}
45+
}
46+
return out;
47+
}
48+
49+
/** The package folder a repo-relative posix path is in (`packages/core`), or "" for the root. */
50+
export function packageFolder(relPath, parents) {
51+
const parts = relPath.split("/");
52+
if (parts[0] === ".." || parts.length < 2) return "";
53+
return parents.includes(parts[0]) ? `${parts[0]}/${parts[1]}` : "";
54+
}
55+
56+
/** The package name a bare specifier reaches into the source of, or null. `@inspa/core/src/x` -> `@inspa/core`. */
57+
export function deepSourceImport(spec, names) {
58+
const m = /^(@[^/]+\/[^/]+|[^@./][^/]*)\/src(?:\/|$)/.exec(spec);
59+
if (!m) return null;
60+
return m[1].startsWith("@inspa/") || names.has(m[1]) ? m[1] : null;
61+
}
62+
63+
/**
64+
* Why importing `spec` from `filename` (absolute) crosses a package boundary, or null when it doesn't.
65+
* Returns `{ kind: "deep", pkg }` or `{ kind: "relative", from, to, pkg }`.
66+
*/
67+
export function boundaryViolation(filename, spec, { root = ROOT, parents, folders } = {}) {
68+
parents ??= workspaceParents(root);
69+
folders ??= workspaces(root);
70+
if (spec.startsWith(".")) {
71+
const fromRel = toPosix(relative(root, filename));
72+
const toRel = toPosix(relative(root, resolve(dirname(filename), spec)));
73+
const from = packageFolder(fromRel, parents);
74+
const to = packageFolder(toRel, parents);
75+
if (to && to !== from) return { kind: "relative", from: from || "the repo root", to, pkg: folders.get(to) ?? null };
76+
return null;
77+
}
78+
const pkg = deepSourceImport(spec, new Set([...folders.values()].filter(Boolean)));
79+
return pkg ? { kind: "deep", pkg } : null;
80+
}
81+
82+
let layout = null;
83+
/** The repo's workspace layout, read once per lint run. */
84+
function repoLayout() {
85+
layout ??= { parents: workspaceParents(), folders: workspaces() };
86+
return layout;
87+
}
88+
89+
const VI_MODULE_CALLS = new Set(["mock", "doMock", "unmock", "doUnmock", "importActual", "importMock"]);
90+
91+
function stringValue(node) {
92+
if (!node) return null;
93+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
94+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
95+
return null;
96+
}
97+
98+
const rule = {
99+
meta: {
100+
type: "problem",
101+
docs: { description: "Packages import only each other's public entry points" },
102+
schema: [
103+
{
104+
type: "object",
105+
properties: {
106+
allow: {
107+
type: "array",
108+
items: {
109+
type: "object",
110+
properties: { file: { type: "string" }, import: { type: "string" } },
111+
required: ["file", "import"],
112+
additionalProperties: false,
113+
},
114+
},
115+
},
116+
additionalProperties: false,
117+
},
118+
],
119+
messages: {
120+
deep: "`{{spec}}` reaches into the source of {{pkg}}. Import `{{pkg}}` or one of its `exports` subpaths instead (#5).",
121+
relative:
122+
"`{{spec}}` crosses from {{from}} into {{to}}. Import {{target}} through its public entry point instead (#5).",
123+
},
124+
},
125+
create(context) {
126+
const filename = context.filename ?? context.getFilename();
127+
const fileRel = toPosix(relative(ROOT, filename));
128+
const allowed = new Set(
129+
(context.options[0]?.allow ?? []).filter((a) => a.file === fileRel).map((a) => a.import),
130+
);
131+
const { parents, folders } = repoLayout();
132+
133+
function check(node) {
134+
const spec = stringValue(node);
135+
if (spec === null || allowed.has(spec)) return;
136+
const v = boundaryViolation(filename, spec, { parents, folders });
137+
if (!v) return;
138+
if (v.kind === "deep") context.report({ node, messageId: "deep", data: { spec, pkg: v.pkg } });
139+
else
140+
context.report({
141+
node,
142+
messageId: "relative",
143+
data: { spec, from: v.from, to: v.to, target: v.pkg ? `\`${v.pkg}\`` : v.to },
144+
});
145+
}
146+
147+
return {
148+
ImportDeclaration: (n) => check(n.source),
149+
ExportAllDeclaration: (n) => check(n.source),
150+
ExportNamedDeclaration: (n) => n.source && check(n.source),
151+
ImportExpression: (n) => check(n.source),
152+
TSImportType(n) {
153+
// typescript-eslint 8 has `source` (a string literal); older versions wrap it in `argument`.
154+
const arg = n.source ?? n.argument;
155+
check(arg?.type === "TSLiteralType" ? arg.literal : arg);
156+
},
157+
TSExternalModuleReference: (n) => check(n.expression),
158+
CallExpression(n) {
159+
const c = n.callee;
160+
if (c.type === "Identifier" && c.name === "require") return check(n.arguments[0]);
161+
if (
162+
c.type === "MemberExpression" &&
163+
!c.computed &&
164+
c.object.type === "Identifier" &&
165+
c.object.name === "vi" &&
166+
VI_MODULE_CALLS.has(c.property.name)
167+
)
168+
return check(n.arguments[0]);
169+
},
170+
};
171+
},
172+
};
173+
174+
export default { meta: { name: "inspa" }, rules: { "package-boundaries": rule } };

‎scripts/eslint-boundaries.test.mjs‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import { existsSync, readFileSync } from "node:fs";
2+
import { join } from "node:path";
3+
import { Linter } from "eslint";
4+
import tseslint from "typescript-eslint";
5+
import { describe, expect, it } from "vitest";
6+
import config from "../eslint.config.js";
7+
import inspa, { deepSourceImport, packageFolder, ROOT, workspaceParents, workspaces } from "./eslint-boundaries.mjs";
8+
9+
const RULE = "inspa/package-boundaries";
10+
11+
function lint(file, code, allow = []) {
12+
const linter = new Linter({ configType: "flat", cwd: ROOT });
13+
const messages = linter.verify(
14+
code,
15+
[
16+
{
17+
files: ["**/*.ts", "**/*.mjs"],
18+
languageOptions: { parser: tseslint.parser, ecmaVersion: 2022, sourceType: "module" },
19+
plugins: { inspa },
20+
rules: { [RULE]: ["error", { allow }] },
21+
},
22+
],
23+
{ filename: join(ROOT, file) },
24+
);
25+
const fatal = messages.filter((m) => m.fatal);
26+
if (fatal.length) throw new Error(fatal.map((m) => m.message).join("\n"));
27+
return messages.map((m) => m.message);
28+
}
29+
30+
describe("package boundaries lint (#5)", () => {
31+
it("reads the workspace folders from the root package.json", () => {
32+
expect(workspaceParents()).toEqual(expect.arrayContaining(["packages", "apps", "examples"]));
33+
const folders = workspaces();
34+
expect(folders.get("packages/core")).toBe("@inspa/core");
35+
expect(folders.get("packages/cli")).toBe("inspa");
36+
});
37+
38+
it("finds the package folder of a path", () => {
39+
const parents = ["packages", "apps", "examples"];
40+
expect(packageFolder("packages/core/src/index.ts", parents)).toBe("packages/core");
41+
expect(packageFolder("apps/desktop/src-tauri/x.rs", parents)).toBe("apps/desktop");
42+
expect(packageFolder("e2e/a.spec.ts", parents)).toBe("");
43+
expect(packageFolder("vitest.config.ts", parents)).toBe("");
44+
expect(packageFolder("../elsewhere/x.ts", parents)).toBe("");
45+
});
46+
47+
it("spots bare imports into a package's source", () => {
48+
const names = new Set(["@inspa/core", "inspa", "invoices"]);
49+
expect(deepSourceImport("@inspa/core/src/edit/index.js", names)).toBe("@inspa/core");
50+
expect(deepSourceImport("@inspa/protocol/src", names)).toBe("@inspa/protocol");
51+
expect(deepSourceImport("inspa/src/proxy/index.js", names)).toBe("inspa");
52+
expect(deepSourceImport("@inspa/core", names)).toBeNull();
53+
expect(deepSourceImport("@inspa/core/guardrails", names)).toBeNull();
54+
expect(deepSourceImport("@inspa/core/srcmaps", names)).toBeNull();
55+
expect(deepSourceImport("react/src/x", names)).toBeNull();
56+
});
57+
58+
it("fails relative imports that leave the package, in every form", () => {
59+
const into = "../../vite-plugin/src/transform.js";
60+
const file = "packages/cli/src/a.ts";
61+
for (const code of [
62+
`import { x } from "${into}";`,
63+
`import "${into}";`,
64+
`import type { X } from "${into}";`,
65+
`export * from "${into}";`,
66+
`export { x } from "${into}";`,
67+
`await import("${into}");`,
68+
`await import(\`${into}\`);`,
69+
`require("${into}");`,
70+
`vi.mock("${into}", () => ({}));`,
71+
`await vi.importActual("${into}");`,
72+
`type T = typeof import("${into}");`,
73+
`import x = require("${into}");`,
74+
]) {
75+
const msgs = lint(file, code);
76+
expect(msgs, code).toHaveLength(1);
77+
expect(msgs[0]).toContain("crosses from packages/cli into packages/vite-plugin");
78+
expect(msgs[0]).toContain("`@inspa/vite-plugin`");
79+
}
80+
});
81+
82+
it("fails root files (e2e, scripts) reaching into a package, and names folders without a package.json", () => {
83+
expect(lint("e2e/a.spec.ts", `import { startProxy } from "../packages/cli/src/proxy/index";`)[0]).toContain(
84+
"crosses from the repo root into packages/cli",
85+
);
86+
expect(lint("scripts/a.mjs", `import "../apps/nothing-here/src/main.js";`)[0]).toContain(
87+
"into apps/nothing-here",
88+
);
89+
});
90+
91+
it("fails deep bare imports", () => {
92+
expect(lint("packages/ui/src/a.ts", `import { x } from "@inspa/core/src/edit/index.js";`)[0]).toContain(
93+
"reaches into the source of @inspa/core",
94+
);
95+
expect(lint("e2e/a.spec.ts", `import "inspa/src/proxy/index.js";`)).toHaveLength(1);
96+
});
97+
98+
it("allows public entry points, imports inside a package, root-to-root imports and plain strings", () => {
99+
const ok = [
100+
`import { x } from "@inspa/core";`,
101+
`import { y } from "@inspa/core/guardrails";`,
102+
`import { z } from "./local.js";`,
103+
`import { w } from "../proxy/index.js";`,
104+
`import { v } from "../test/helpers.js";`,
105+
`const s = "import x from '../../vite-plugin/src/transform.js'";`,
106+
`const t = \`\${dir}/../../core/src/a.ts\`;`,
107+
`foo.mock("../../core/src/a.js");`,
108+
];
109+
for (const code of ok) expect(lint("packages/cli/src/a.ts", code), code).toEqual([]);
110+
expect(lint("e2e/a.spec.ts", `import { h } from "./helpers/app";`)).toEqual([]);
111+
expect(lint("e2e/a.spec.ts", `import { h } from "../scripts/edit-timings.mjs";`)).toEqual([]);
112+
});
113+
114+
it("allow-lists one exact import in one file, not the file", () => {
115+
const allow = [{ file: "packages/cli/src/a.ts", import: "../../core/src/a.js" }];
116+
expect(lint("packages/cli/src/a.ts", `import "../../core/src/a.js";`, allow)).toEqual([]);
117+
expect(lint("packages/cli/src/a.ts", `import "../../core/src/b.js";`, allow)).toHaveLength(1);
118+
expect(lint("packages/cli/src/other.ts", `import "../../core/src/a.js";`, allow)).toHaveLength(1);
119+
});
120+
121+
it("every allow-list entry in eslint.config.js is still a real import (the list only shrinks)", () => {
122+
const entry = config.find((c) => c.rules?.[RULE]);
123+
expect(entry, "eslint.config.js turns the rule on").toBeTruthy();
124+
const allow = entry.rules[RULE][1].allow;
125+
expect(allow.length).toBeGreaterThan(0);
126+
const stale = allow.filter(({ file, import: spec }) => {
127+
const abs = join(ROOT, file);
128+
if (!existsSync(abs)) return true;
129+
const src = readFileSync(abs, "utf8");
130+
return ![`"${spec}"`, `'${spec}'`, `\`${spec}\``].some((q) => src.includes(q));
131+
});
132+
expect(stale, "remove these entries from BOUNDARY_ALLOW in eslint.config.js").toEqual([]);
133+
});
134+
});

0 commit comments

Comments
 (0)