|
| 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 } }; |
0 commit comments