From 614bc6376608292d173aac0e150b21c5e6db3e5a Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 18:36:54 -0500 Subject: [PATCH 1/4] Add the Astro rules of W-28, W-30 and W-31 to the plugin, and W-37 on `), + }, + ], + invalid: [ + { + name: "eleven statements, reported at the eleventh", + ...page(statements(11)), + errors: tooLong(10, 12), + }, + { + name: "many more than eleven report once", + ...page(statements(25)), + errors: tooLong(10, 12), + }, + { + name: "nested statements count: a function body", + ...page(`${statements(8)}\nfunction f() {\n const a = 1;\n return a;\n}`), + errors: tooLong(10, 12), + }, + { + name: "nested statements count: a branch", + ...page(`${statements(9)}\nif (s1) {\n run();\n}`), + errors: tooLong(10, 12), + }, + { + name: "imports beside eleven statements", + ...page(`import a from "./a";\n${statements(11)}`), + errors: tooLong(10, 13), + }, + { + name: "a lowered limit", + ...page(statements(3)), + options: [{ max: 2 }], + errors: tooLong(2, 4), + }, + { + name: "a limit of zero", + ...page("const zero = 0;"), + options: [{ max: 0 }], + errors: tooLong(0, 2), + }, + ...COUNTED.map(([name, code]) => ({ + name: `${name} counts`, + ...page(code), + options: [{ max: 0 }], + errors: [{ messageId: "tooLong" as const }], + })), + { + name: "return and throw count", + code: "---\nfunction f() {\n throw e;\n}\nfunction g() {\n return 1;\n}\n---\n

\n", + filename: "page.astro", + options: [{ max: 3 }], + errors: [{ messageId: "tooLong" as const, line: 6 }], + }, + { + name: "break and continue count", + ...page("while (a) {\n if (b) {\n break;\n }\n continue;\n}"), + options: [{ max: 3 }], + errors: [{ messageId: "tooLong" as const, line: 6 }], + }, + ], +}); + +describe("W-31's rule", () => { + it("says which law it judges, and takes a limit", () => { + expect(rule.meta).toEqual({ + type: "suggestion", + docs: { description: "Frontmatter logic beyond 10 statements moves to a .ts module (W-31)" }, + schema: [ + { + type: "object", + properties: { max: { type: "integer", minimum: 0 } }, + additionalProperties: false, + }, + ], + messages: { + tooLong: + "The frontmatter has more than {{ max }} statements. Move the logic into a .ts module and import it, so it can be tested.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts new file mode 100644 index 0000000..16d5555 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts @@ -0,0 +1,69 @@ +import type { Rule } from "eslint"; +import { child } from "../ast.ts"; + +/** + * W-31: frontmatter logic beyond 10 statements moves to a `.ts` module, where it can be tested. + * Every statement counts, nested ones too (the body of a function or a branch); imports and type + * declarations do not, and neither does anything in the template, which starts at `AstroFragment`. + */ + +const MAX = 10; + +const STATEMENTS = [ + "ExpressionStatement", + "VariableDeclaration", + "FunctionDeclaration", + "ClassDeclaration", + "IfStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "WhileStatement", + "DoWhileStatement", + "SwitchStatement", + "ReturnStatement", + "ThrowStatement", + "TryStatement", + "BreakStatement", + "ContinueStatement", + "LabeledStatement", +]; + +const rule: Rule.RuleModule = { + meta: { + type: "suggestion", + docs: { description: "Frontmatter logic beyond 10 statements moves to a .ts module (W-31)" }, + schema: [ + { + type: "object", + properties: { max: { type: "integer", minimum: 0 } }, + additionalProperties: false, + }, + ], + messages: { + tooLong: + "The frontmatter has more than {{ max }} statements. Move the logic into a .ts module and import it, so it can be tested.", + }, + }, + create(context) { + const option: unknown = context.options[0]; + const limit = child(option, "max"); + const max = typeof limit === "number" ? limit : MAX; + let inTemplate = false; + let count = 0; + return { + AstroFragment() { + inTemplate = true; + }, + [STATEMENTS.join(", ")](node: Rule.Node) { + if (inTemplate) return; + count += 1; + if (count === max + 1) { + context.report({ node, messageId: "tooLong", data: { max: String(max) } }); + } + }, + }; + }, +}; + +export default rule; diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 10e47d4..064edbe 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -61,11 +61,36 @@ const TSX = ["**/*.jsx", "**/*.tsx"]; // is in `files`), so an adopter has one dependency and no separate pin. A preset enables exactly the // rules of the laws its class maps (the class-rules test), which is why there are two groups. +const ASTRO = ["**/*.astro"]; +/** eslint-plugin-astro lints each `", + "", + ].join("\n"), + }); + const page = run(bin("eslint"), ["src/page.astro"], dir); + for (const rule of [ + "astro-assets-image", + "astro-client-load-ack", + "astro-frontmatter-size", + ]) { + expect(page.output, rule).toContain(`webtops/${rule}`); + } + expect(page.output.split("webtops/public-env-only")).toHaveLength(2); + expect(page.output).toMatch(/\n\s+21:27\s+error\s+SECRET[^\n]*webtops\/public-env-only/u); + }, + REAL_TOOL_TIMEOUT, + ); + it("exports plain JavaScript and JSON, which Node loads from inside node_modules", () => { const exported: unknown = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); const text = JSON.stringify(exported); @@ -245,28 +292,67 @@ describe("the ESLint preset", () => { } }); + const W36 = "webtops/no-unsanitized-html"; + const W37 = "webtops/public-env-only"; + const W23 = "webtops/complete-tailwind-classes"; + const W28 = "webtops/astro-client-load-ack"; + const W30 = "webtops/astro-assets-image"; + const W31 = "webtops/astro-frontmatter-size"; + const ALL = [W36, W37, W23, W28, W30, W31]; + it.each([ - ["base", ["webtops/no-unsanitized-html"], ["webtops/complete-tailwind-classes"]], - ["react", ["webtops/no-unsanitized-html"], ["webtops/complete-tailwind-classes"]], - ["react-app", ["webtops/no-unsanitized-html", "webtops/complete-tailwind-classes"], []], - ["astro", ["webtops/no-unsanitized-html", "webtops/complete-tailwind-classes"], []], - ] as const)("%s enables the plugin's rules at error: %j", async (variant, has, hasNot) => { + ["base", [W36]], + ["react", [W36, W37]], + ["react-app", [W36, W37, W23, W28]], + ["astro", ALL], + ] as const)("%s enables exactly these plugin rules at error: %j", async (variant, has) => { const config = await presetOf(variant); const rules = errorRules(config); - for (const name of has) expect(rules, name).toContain(name); - for (const name of hasNot) expect(rules, name).not.toContain(name); + for (const name of ALL) { + if (has.some((wanted) => wanted === name)) expect(rules, name).toContain(name); + else expect(rules, name).not.toContain(name); + } expect(pluginNames(config)).toContain("webtops"); }); - it("scopes public-env-only (W-37) to the client modules, in the variants with a UI only", async () => { - const scopes = async (variant: EslintVariant): Promise => - (await presetOf(variant)) - .filter((entry) => Object.hasOwn(entry.rules ?? {}, "webtops/public-env-only")) - .map((entry) => entry.files); - expect(await scopes("base")).toEqual([]); - expect(await scopes("react")).toEqual([["**/*.jsx", "**/*.tsx"]]); - expect(await scopes("react-app")).toEqual([["**/*.jsx", "**/*.tsx"]]); - expect(await scopes("astro")).toEqual([["**/*.jsx", "**/*.tsx"]]); + /** The `files` of each config entry that sets the rule. */ + const scopesOf = async (variant: EslintVariant, rule: string): Promise => + (await presetOf(variant)) + .filter((entry) => Object.hasOwn(entry.rules ?? {}, rule)) + .map((entry) => entry.files); + + it("scopes public-env-only (W-37) to the client modules and the ", + "", + ].join("\n"); + const dir = scratchProject({ + "package.json": manifest(ASTRO), + "web-tops.yaml": "class: web-app\n", + "eslint.config.js": configFor("react"), + "tsconfig.json": TSCONFIG, + "src/page.astro": page, + }); + const result = run(bin("eslint"), ["--format", "json", "src/page.astro"], dir); + const reports: unknown = JSON.parse(result.stdout); + const messages = JSON.stringify(reports); + expect(messages).not.toContain('"fatal":true'); + expect(messages.split("webtops/astro-client-load-ack")).toHaveLength(2); + expect(messages.split("webtops/public-env-only")).toHaveLength(2); + expect(messages).not.toContain("webtops/astro-assets-image"); + expect(messages).not.toContain("webtops/astro-frontmatter-size"); + }, + REAL_TOOL_TIMEOUT, + ); +}); diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts index 21a3903..e56812c 100644 --- a/src/presets/class-rules.test.ts +++ b/src/presets/class-rules.test.ts @@ -1,10 +1,19 @@ -import { readFileSync, readdirSync } from "node:fs"; -import { join, resolve } from "node:path"; -import { describe, expect, it } from "vitest"; +import { readFileSync, readdirSync, realpathSync } from "node:fs"; +import { join, relative, resolve } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; import { parse } from "yaml"; import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; +import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; +import { + TSCONFIG, + bin, + configFor, + removeScratches, + run, + scratchProject, +} from "./test-support-scratch.ts"; const ROOT = resolve(import.meta.dirname, "../.."); const PREFIX = "webtops/"; @@ -81,3 +90,59 @@ describe("R98: a class's preset enables exactly the plugin rules its laws map", expect(withTailwind).toEqual(["astro-site", "web-app"]); }); }); + +afterAll(removeScratches); + +/** One file of each kind a class's rules can match: a module, a React module and an Astro page. */ +const KINDS = { + "src/a.ts": "export const a: number = 1;\n", + "src/c.tsx": "export const c = (): null => null;\n", + "src/page.astro": [ + "---", + "const Widget = (): null => null;", + "---", + "", + "", + ].join("\n"), +}; + +/** ESLint's report for every file under src, as JSON. */ +function lintAll(dir: string): unknown[] { + const parsed: unknown = JSON.parse(run(bin("eslint"), ["--format", "json", "src"], dir).stdout); + return Array.isArray(parsed) ? parsed : []; +} + +function pathOf(dir: string, report: unknown): string { + const path = field(report, "filePath"); + return typeof path === "string" ? relative(realpathSync(dir), path) : ""; +} + +const messagesOf = (report: unknown): unknown[] => list(report, "messages"); + +describe("R105: a class's preset can parse every file kind its rules match", () => { + it.each(CLASSES)( + "%s: its project lints a module, a React module and a page with no parse error", + (cls) => { + const dir = scratchProject({ + "package.json": JSON.stringify({ type: "module", dependencies: { astro: "7.4.12" } }), + "web-tops.yaml": `class: ${cls}\n`, + "eslint.config.js": configFor(variantOf(cls)), + "tsconfig.json": TSCONFIG, + ...KINDS, + }); + const reports = lintAll(dir); + const mapsPages = mappedRules(cls).some((rule) => rule.startsWith(`${PREFIX}astro-`)); + expect(reports.map((report) => pathOf(dir, report)).sort()).toEqual( + mapsPages ? Object.keys(KINDS).sort() : ["src/a.ts", "src/c.tsx"], + ); + for (const report of reports) { + const fatal = messagesOf(report).filter((message) => field(message, "fatal") === true); + expect(fatal, pathOf(dir, report)).toEqual([]); + } + const page = reports.find((report) => pathOf(dir, report) === "src/page.astro"); + const ruleIds = messagesOf(page).map((message) => field(message, "ruleId")); + expect(ruleIds.includes(`${PREFIX}astro-client-load-ack`)).toBe(mapsPages); + }, + REAL_TOOL_TIMEOUT, + ); +}); diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 005daed..05bff82 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -119,6 +119,22 @@ function declaredClass(root) { } } +/** Whether the project's package.json lists astro, so it has .astro files to read. */ +function dependsOnAstro(root) { + try { + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + return ["dependencies", "devDependencies", "peerDependencies"].some( + (field) => manifest[field]?.astro !== undefined, + ); + } catch { + return false; + } +} + +/** Whether the class maps a rule that reads .astro pages, which only the Astro parser can read. */ +const readsAstroPages = (className) => + WEBTOPS_RULES.some((entry) => entry.files === ASTRO && entry.classes.includes(className)); + /** The plugin's rules the class's laws map, each at error. */ function webtopsConfigs(className) { return WEBTOPS_RULES.filter((entry) => entry.classes.includes(className)).map((entry) => ({ @@ -162,16 +178,8 @@ async function reactConfigs() { ]; } -async function astroConfigs(tsconfigRootDir) { - const [astro, a11y] = await Promise.all([ - load("eslint-plugin-astro"), - load("eslint-plugin-jsx-a11y-x"), - ]); +function astroParserOptions(tsconfigRootDir) { return [ - // W-22 semantic elements, alt text, labels (also inside .astro files) - ...astro.configs["flat/recommended"], - ...astro.configs["flat/jsx-a11y-strict"], - { files: TSX, ...a11y.configs.strict }, { // astro-eslint-parser does not take `projectService`; it reads `project` (the file is parsed // as `project: true`, which fails on the template without this) @@ -194,6 +202,26 @@ async function astroConfigs(tsconfigRootDir) { ]; } +async function astroConfigs(tsconfigRootDir) { + const [astro, a11y] = await Promise.all([ + load("eslint-plugin-astro"), + load("eslint-plugin-jsx-a11y-x"), + ]); + return [ + // W-22 semantic elements, alt text, labels (also inside .astro files) + ...astro.configs["flat/recommended"], + ...astro.configs["flat/jsx-a11y-strict"], + { files: TSX, ...a11y.configs.strict }, + ...astroParserOptions(tsconfigRootDir), + ]; +} + +/** The Astro parser alone, for a class whose variant is not astro but whose laws read .astro pages. */ +async function astroParserConfigs(tsconfigRootDir) { + const astro = await load("eslint-plugin-astro"); + return [...astro.configs["flat/base"], ...astroParserOptions(tsconfigRootDir)]; +} + const PLUGIN_CONFIGS = { base: async () => [], react: reactConfigs, astro: astroConfigs }; /** The variants a class can name: the plugin set added on top of the base law rules. */ @@ -206,6 +234,16 @@ export const PACKAGES = { astro: [...BASE_PACKAGES, "eslint-plugin-astro", "eslint-plugin-jsx-a11y-x"], }; +/** + * The variant's plugin set. A class that maps an .astro-scoped rule also gets the Astro parser when + * the project depends on astro, whatever its variant, or ESLint could not read its pages. + */ +async function pluginConfigs(variant, className, root) { + const plugins = await PLUGIN_CONFIGS[variant](root); + const needsParser = variant !== "astro" && readsAstroPages(className) && dependsOnAstro(root); + return needsParser ? [...plugins, ...(await astroParserConfigs(root))] : plugins; +} + /** * The flat config for one class: the base law rules plus the plugin set the variant adds. * `tsconfigRootDir` is the project root, so type-aware rules find its tsconfig. `class` names the @@ -215,8 +253,9 @@ export async function eslintPreset({ variant, tsconfigRootDir, class: className if (!Object.hasOwn(PLUGIN_CONFIGS, variant)) { throw new RangeError(`web-tops/eslint has no variant "${variant}"; use ${VARIANTS.join(", ")}`); } - const plugins = await PLUGIN_CONFIGS[variant](tsconfigRootDir); - const laws = webtopsConfigs(className ?? declaredClass(tsconfigRootDir) ?? DEFAULT_CLASS); + const resolved = className ?? declaredClass(tsconfigRootDir) ?? DEFAULT_CLASS; + const plugins = await pluginConfigs(variant, resolved, tsconfigRootDir); + const laws = webtopsConfigs(resolved); return defineConfig( { ignores: IGNORES }, js.configs.recommended, diff --git a/src/presets/presets.test.ts b/src/presets/presets.test.ts index ca5f348..6f7bf12 100644 --- a/src/presets/presets.test.ts +++ b/src/presets/presets.test.ts @@ -1,37 +1,11 @@ -import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import type { Linter } from "eslint"; import { afterAll, describe, expect, it } from "vitest"; import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { PACKAGES, VARIANTS, eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; - -const ROOT = resolve(import.meta.dirname, "../.."); -const scratches: string[] = []; - -/** - * A project outside the kit that reaches it only as `node_modules/web-tops`, the way an inited - * project does. `files` are written relative to the project; it is an ES module project. - */ -function scratchProject(files: Readonly> = {}): string { - const dir = mkdtempSync(join(tmpdir(), "wt-preset-")); - scratches.push(dir); - mkdirSync(join(dir, "node_modules")); - symlinkSync(ROOT, join(dir, "node_modules", "web-tops")); - // eslint-plugin-astro finds the TypeScript parser from the project it lints, as an adopter has it. - symlinkSync( - join(ROOT, "node_modules", "typescript-eslint"), - join(dir, "node_modules", "typescript-eslint"), - ); - const all = { "package.json": '{ "type": "module" }\n', ...files }; - for (const [path, text] of Object.entries(all)) { - mkdirSync(dirname(join(dir, path)), { recursive: true }); - writeFileSync(join(dir, path), text); - } - return dir; -} +import { ROOT, bin, removeScratches, run, scratchProject } from "./test-support-scratch.ts"; const presetOf = (variant: EslintVariant): Promise => eslintPreset({ variant, tsconfigRootDir: "" }); @@ -53,9 +27,7 @@ function errorRules(config: readonly Linter.Config[]): ReadonlySet { const pluginNames = (config: readonly Linter.Config[]): ReadonlySet => new Set(config.flatMap((entry) => Object.keys(entry.plugins ?? {}))); -afterAll(() => { - for (const dir of scratches) rmSync(dir, { recursive: true, force: true }); -}); +afterAll(removeScratches); const PRESET_SOURCE = readFileSync(join(ROOT, "src/presets/eslint.js"), "utf8"); const KIT_CONFIG = readFileSync(join(ROOT, "eslint.config.js"), "utf8"); @@ -68,17 +40,6 @@ const writtenRules = (source: string): ReadonlySet => ), ); -function run( - command: string, - args: readonly string[], - cwd: string, -): { status: number | null; output: string } { - const result = spawnSync(command, args, { cwd, encoding: "utf8" }); - return { status: result.status, output: `${result.stdout}${result.stderr}` }; -} - -const bin = (name: string): string => join(ROOT, "node_modules", ".bin", name); - describe("G2a: each preset imports from a scratch project", () => { it( "web-tops/eslint, web-tops/stylelint and web-tops/depcruise load under Node", diff --git a/src/presets/test-support-scratch.ts b/src/presets/test-support-scratch.ts new file mode 100644 index 0000000..81c8ab7 --- /dev/null +++ b/src/presets/test-support-scratch.ts @@ -0,0 +1,59 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +export const ROOT = resolve(import.meta.dirname, "../.."); +const scratches: string[] = []; + +/** + * A project outside the kit that reaches it only as `node_modules/web-tops`, the way an inited + * project does. `files` are written relative to the project; it is an ES module project. + */ +export function scratchProject(files: Readonly> = {}): string { + const dir = mkdtempSync(join(tmpdir(), "wt-preset-")); + scratches.push(dir); + mkdirSync(join(dir, "node_modules")); + symlinkSync(ROOT, join(dir, "node_modules", "web-tops")); + // eslint-plugin-astro finds the TypeScript parser from the project it lints, as an adopter has it. + symlinkSync( + join(ROOT, "node_modules", "typescript-eslint"), + join(dir, "node_modules", "typescript-eslint"), + ); + const all = { "package.json": '{ "type": "module" }\n', ...files }; + for (const [path, text] of Object.entries(all)) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), text); + } + return dir; +} + +/** Removes every project scratchProject() made. */ +export function removeScratches(): void { + for (const dir of scratches) rmSync(dir, { recursive: true, force: true }); +} + +export interface Ran { + readonly status: number | null; + /** Standard output and standard error together. */ + readonly output: string; + readonly stdout: string; +} + +export function run(command: string, args: readonly string[], cwd: string): Ran { + const result = spawnSync(command, args, { cwd, encoding: "utf8" }); + return { + status: result.status, + output: `${result.stdout}${result.stderr}`, + stdout: result.stdout, + }; +} + +export const bin = (name: string): string => join(ROOT, "node_modules", ".bin", name); + +/** The one-line eslint.config.js `webtops init` writes, for a variant. */ +export const configFor = (variant: string): string => + `import { eslintPreset } from "web-tops/eslint";\nexport default await eslintPreset({\n variant: "${variant}",\n tsconfigRootDir: import.meta.dirname,\n});\n`; + +export const TSCONFIG = + '{ "extends": "web-tops/tsconfig/strict.json", "compilerOptions": { "noEmit": true }, "include": ["src"] }\n'; From b23ee0feef096719b7fed938ef21858fe55594cb Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Fri, 20 Nov 2026 06:54:58 -0500 Subject: [PATCH 4/4] Make the scratch-project helper stateless and test it (G7) The helper cleans up through onTestFinished instead of a module-level list, so there is no state to leave unobserved, and its prefix, cleanup and tsconfig text are pinned by tests. Co-Authored-By: Claude Sonnet 5.5 --- src/presets/astro-parser.test.ts | 13 ++------- src/presets/class-rules.test.ts | 13 ++------- src/presets/presets.test.ts | 6 ++-- src/presets/test-support-scratch.test.ts | 36 ++++++++++++++++++++++++ src/presets/test-support-scratch.ts | 14 ++++----- 5 files changed, 48 insertions(+), 34 deletions(-) create mode 100644 src/presets/test-support-scratch.test.ts diff --git a/src/presets/astro-parser.test.ts b/src/presets/astro-parser.test.ts index e054283..1a60189 100644 --- a/src/presets/astro-parser.test.ts +++ b/src/presets/astro-parser.test.ts @@ -1,18 +1,9 @@ import type { Linter } from "eslint"; -import { afterAll, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; -import { - TSCONFIG, - bin, - configFor, - removeScratches, - run, - scratchProject, -} from "./test-support-scratch.ts"; - -afterAll(removeScratches); +import { TSCONFIG, bin, configFor, run, scratchProject } from "./test-support-scratch.ts"; const ASTRO = { dependencies: { astro: "7.4.12" } }; const manifest = (extra: object): string => JSON.stringify({ type: "module", ...extra }); diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts index e56812c..4a923bb 100644 --- a/src/presets/class-rules.test.ts +++ b/src/presets/class-rules.test.ts @@ -1,19 +1,12 @@ import { readFileSync, readdirSync, realpathSync } from "node:fs"; import { join, relative, resolve } from "node:path"; -import { afterAll, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import { parse } from "yaml"; import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; -import { - TSCONFIG, - bin, - configFor, - removeScratches, - run, - scratchProject, -} from "./test-support-scratch.ts"; +import { TSCONFIG, bin, configFor, run, scratchProject } from "./test-support-scratch.ts"; const ROOT = resolve(import.meta.dirname, "../.."); const PREFIX = "webtops/"; @@ -91,8 +84,6 @@ describe("R98: a class's preset enables exactly the plugin rules its laws map", }); }); -afterAll(removeScratches); - /** One file of each kind a class's rules can match: a module, a React module and an Astro page. */ const KINDS = { "src/a.ts": "export const a: number = 1;\n", diff --git a/src/presets/presets.test.ts b/src/presets/presets.test.ts index fb697c2..c6b69b7 100644 --- a/src/presets/presets.test.ts +++ b/src/presets/presets.test.ts @@ -1,11 +1,11 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import type { Linter } from "eslint"; -import { afterAll, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { PACKAGES, VARIANTS, eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; -import { ROOT, bin, removeScratches, run, scratchProject } from "./test-support-scratch.ts"; +import { ROOT, bin, run, scratchProject } from "./test-support-scratch.ts"; const presetOf = (variant: EslintVariant): Promise => eslintPreset({ variant, tsconfigRootDir: "" }); @@ -27,8 +27,6 @@ function errorRules(config: readonly Linter.Config[]): ReadonlySet { const pluginNames = (config: readonly Linter.Config[]): ReadonlySet => new Set(config.flatMap((entry) => Object.keys(entry.plugins ?? {}))); -afterAll(removeScratches); - const PRESET_SOURCE = readFileSync(join(ROOT, "src/presets/eslint.js"), "utf8"); const KIT_CONFIG = readFileSync(join(ROOT, "eslint.config.js"), "utf8"); diff --git a/src/presets/test-support-scratch.test.ts b/src/presets/test-support-scratch.test.ts new file mode 100644 index 0000000..3803658 --- /dev/null +++ b/src/presets/test-support-scratch.test.ts @@ -0,0 +1,36 @@ +import { existsSync, lstatSync, readFileSync, readlinkSync } from "node:fs"; +import { basename, join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { ROOT, TSCONFIG, scratchProject } from "./test-support-scratch.ts"; + +const made: string[] = []; + +afterAll(() => { + expect(made.length).toBeGreaterThan(0); + for (const dir of made) expect(existsSync(dir), dir).toBe(false); +}); + +describe("the scratch project helper", () => { + it("makes a project that reaches the kit as node_modules/web-tops, with the files it is given", () => { + const dir = scratchProject({ "src/a.ts": "export {};\n" }); + made.push(dir); + expect(basename(dir)).toMatch(/^wt-preset-/u); + expect(readFileSync(join(dir, "package.json"), "utf8")).toBe('{ "type": "module" }\n'); + expect(readFileSync(join(dir, "src/a.ts"), "utf8")).toBe("export {};\n"); + expect(lstatSync(join(dir, "node_modules", "web-tops")).isSymbolicLink()).toBe(true); + expect(existsSync(join(dir, "node_modules", "web-tops", "package.json"))).toBe(true); + expect(readlinkSync(join(dir, "node_modules", "web-tops"))).toBe(ROOT); + }); + + it("removes each project when its test finishes, even one that holds files", () => { + made.push(scratchProject({ "deep/er/file.txt": "x" })); + }); + + it("writes a tsconfig that extends the kit's strict one over src", () => { + expect(JSON.parse(TSCONFIG)).toEqual({ + extends: "web-tops/tsconfig/strict.json", + compilerOptions: { noEmit: true }, + include: ["src"], + }); + }); +}); diff --git a/src/presets/test-support-scratch.ts b/src/presets/test-support-scratch.ts index 81c8ab7..25d2fb3 100644 --- a/src/presets/test-support-scratch.ts +++ b/src/presets/test-support-scratch.ts @@ -2,17 +2,20 @@ import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; +import { onTestFinished } from "vitest"; export const ROOT = resolve(import.meta.dirname, "../.."); -const scratches: string[] = []; /** * A project outside the kit that reaches it only as `node_modules/web-tops`, the way an inited - * project does. `files` are written relative to the project; it is an ES module project. + * project does. `files` are written relative to the project; it is an ES module project. Call it + * from inside a test: the project is removed when that test finishes. */ export function scratchProject(files: Readonly> = {}): string { const dir = mkdtempSync(join(tmpdir(), "wt-preset-")); - scratches.push(dir); + onTestFinished(() => { + rmSync(dir, { recursive: true }); + }); mkdirSync(join(dir, "node_modules")); symlinkSync(ROOT, join(dir, "node_modules", "web-tops")); // eslint-plugin-astro finds the TypeScript parser from the project it lints, as an adopter has it. @@ -28,11 +31,6 @@ export function scratchProject(files: Readonly> = {}): st return dir; } -/** Removes every project scratchProject() made. */ -export function removeScratches(): void { - for (const dir of scratches) rmSync(dir, { recursive: true, force: true }); -} - export interface Ran { readonly status: number | null; /** Standard output and standard error together. */