119 lines
5.2 KiB
TypeScript
119 lines
5.2 KiB
TypeScript
import { test, expect, describe } from "bun:test";
|
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
import { dirname, join, relative, resolve } from "node:path";
|
|
|
|
/**
|
|
* src/styles/*.css hold rules that only one lazy overlay panel renders; they
|
|
* ship in that panel's async chunk and exist in the page only after it has been
|
|
* opened. That's safe only if every element that can carry one of those classes
|
|
* is rendered by code that loads the stylesheet. So for each class in a panel
|
|
* stylesheet, every source file mentioning it must be unreachable from the app
|
|
* (entry + every other lazy chunk) without passing through the panel component
|
|
* that imports the stylesheet. A class the board / drawer / another panel also
|
|
* uses belongs in styles.css.
|
|
*/
|
|
|
|
const SRC = resolve(import.meta.dir, "../src");
|
|
|
|
function walk(dir: string, out: string[] = []): string[] {
|
|
for (const e of readdirSync(dir)) {
|
|
const p = join(dir, e);
|
|
if (statSync(p).isDirectory()) walk(p, out);
|
|
else if (/\.tsx?$/.test(e)) out.push(p);
|
|
}
|
|
return out;
|
|
}
|
|
const files = walk(SRC);
|
|
const text = new Map(files.map((f) => [f, readFileSync(f, "utf8")]));
|
|
|
|
function resolveRel(from: string, spec: string): string | null {
|
|
if (!spec.startsWith(".")) return null;
|
|
const base = resolve(dirname(from), spec);
|
|
for (const c of [base, base + ".ts", base + ".tsx", join(base, "index.ts"), join(base, "index.tsx")]) {
|
|
if (existsSync(c) && statSync(c).isFile()) return c;
|
|
}
|
|
return null;
|
|
}
|
|
// Static edges (import … from / export … from / side-effect import), and lazy targets.
|
|
const staticEdges = new Map<string, string[]>();
|
|
const lazyTargets = new Set<string>();
|
|
for (const [f, src] of text) {
|
|
const deps: string[] = [];
|
|
for (const m of src.matchAll(/(?:^|\n)\s*(?:import|export)\s+(?!type\b)(?:[^"';]*?\sfrom\s+)?["']([^"']+)["']/g)) {
|
|
const r = resolveRel(f, m[1]); if (r) deps.push(r);
|
|
}
|
|
staticEdges.set(f, deps);
|
|
for (const m of src.matchAll(/import\(\s*["']([^"']+)["']\s*\)/g)) {
|
|
const r = resolveRel(f, m[1]); if (r) lazyTargets.add(r);
|
|
}
|
|
}
|
|
function reachable(roots: string[], blocked: string): Set<string> {
|
|
const seen = new Set<string>(); const stack = roots.filter((r) => r !== blocked);
|
|
while (stack.length) {
|
|
const f = stack.pop()!;
|
|
if (seen.has(f)) continue;
|
|
seen.add(f);
|
|
for (const d of staticEdges.get(f) ?? []) if (d !== blocked && !seen.has(d)) stack.push(d);
|
|
}
|
|
return seen;
|
|
}
|
|
|
|
/** Each complex selector of the sheet → the classes it requires on some element (ignores :not(...)). */
|
|
function selectorsIn(css: string): { sel: string; classes: string[] }[] {
|
|
const noComments = css.replace(/\/\*[\s\S]*?\*\//g, "");
|
|
const out: { sel: string; classes: string[] }[] = [];
|
|
for (const m of noComments.matchAll(/([^{}]+)\{/g)) {
|
|
const list = m[1].trim();
|
|
if (list.startsWith("@")) continue;
|
|
for (const sel of list.split(/,(?![^(]*\))/).map((s) => s.trim()).filter(Boolean)) {
|
|
const classes = [...sel.replace(/:not\((?:[^()]|\([^()]*\))*\)/g, "").matchAll(/\.([A-Za-z_][\w-]*)/g)].map((c) => c[1]);
|
|
out.push({ sel, classes });
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
/** Files that could put `cls` on an element: literal token, or a `prefix-${…}` / "prefix-" + … builder. */
|
|
function filesUsing(cls: string): string[] {
|
|
const esc = cls.replace(/[-]/g, "\\-");
|
|
const lit = new RegExp(`(^|[^\\w-])${esc}($|[^\\w-])`);
|
|
const out: string[] = [];
|
|
for (const [f, src] of text) {
|
|
if (lit.test(src)) { out.push(f); continue; }
|
|
for (const m of src.matchAll(/([A-Za-z_][\w-]{2,})(?:\$\{|["'`]\s*\+)/g)) {
|
|
if (cls.startsWith(m[1]) && cls !== m[1]) { out.push(f); break; }
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
const styleDir = join(SRC, "styles");
|
|
const sheets = existsSync(styleDir) ? readdirSync(styleDir).filter((f) => f.endsWith(".css")) : [];
|
|
|
|
describe("panel stylesheets only style their own lazy panel", () => {
|
|
test("there are panel stylesheets to check", () => { expect(sheets.length).toBeGreaterThan(0); });
|
|
for (const sheet of sheets) {
|
|
test(sheet, () => {
|
|
const importers = files.filter((f) => new RegExp(`import\\s+["'][./]+styles/${sheet.replace(".", "\\.")}["']`).test(text.get(f)!));
|
|
expect(importers.length).toBe(1);
|
|
const entry = importers[0];
|
|
expect(lazyTargets.has(entry)).toBe(true); // it must be a lazily-loaded component
|
|
const outside = reachable([join(SRC, "main.tsx"), ...lazyTargets], entry);
|
|
// A selector is scoped when at least one class it requires is panel-only:
|
|
// `.lab-row .pill` can only match inside a `.lab-row`, even though `.pill`
|
|
// is global. Unscoped selectors (all classes shared, or none) must stay in styles.css.
|
|
const cache = new Map<string, string[]>();
|
|
const leaksOf = (cls: string) => {
|
|
if (!cache.has(cls)) cache.set(cls, filesUsing(cls).filter((f) => outside.has(f)).map((f) => relative(SRC, f)));
|
|
return cache.get(cls)!;
|
|
};
|
|
const unscoped: string[] = [];
|
|
for (const { sel, classes } of selectorsIn(readFileSync(join(styleDir, sheet), "utf8"))) {
|
|
if (!classes.some((c) => leaksOf(c).length === 0)) {
|
|
unscoped.push(`${sel} (${classes.map((c) => `.${c} ← ${leaksOf(c).slice(0, 2).join(", ") || "?"}`).join("; ")})`);
|
|
}
|
|
}
|
|
expect(unscoped).toEqual([]);
|
|
});
|
|
}
|
|
});
|