From 5d299ab9907395e6be0489d7efd5830bb5e29ef7 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 10:17:18 -0500 Subject: [PATCH 1/8] Add eslint-plugin-webtops with W-23, W-36 and W-37 (G6a, G6b) packages/eslint-plugin-webtops holds three rules, each tested with ESLint's RuleTester under Vitest, with valid and invalid cases: - complete-tailwind-classes (W-23): a class token built by interpolation (`bg-${c}-500`, `${a}${b}`) or concatenation ("bg-" + c, "bg-".concat(c)) in className, class and the arguments of clsx, cn, twMerge, cva and the like. Whole tokens chosen by a condition or a lookup stay valid. - no-unsanitized-html (W-36): set:html, dangerouslySetInnerHTML, innerHTML, outerHTML, insertAdjacentHTML and document.write take a literal or the result of a sanitizer. - public-env-only (W-37): process.env and import.meta.env reads of a name that is not public, computed reads, the whole object, and astro:env/server. The rules read nodes by shape, because ESLint's typings leave out JSX. The package builds with tsc and loads under Node. Enabling the rules in the presets (G6c) waits for the presets to merge. Declared exceptions: WEB_TOPS.md section 17 (packages/ is in the tree) and src/cli/layout.test.ts. Co-Authored-By: Claude Sonnet 5.5 --- WEB_TOPS.md | 3 +- packages/eslint-plugin-webtops/package.json | 26 +++ packages/eslint-plugin-webtops/src/ast.ts | 101 +++++++++++ .../eslint-plugin-webtops/src/index.test.ts | 87 +++++++++ packages/eslint-plugin-webtops/src/index.ts | 16 ++ .../rules/complete-tailwind-classes.test.ts | 169 ++++++++++++++++++ .../src/rules/complete-tailwind-classes.ts | 143 +++++++++++++++ .../src/rules/no-unsanitized-html.test.ts | 165 +++++++++++++++++ .../src/rules/no-unsanitized-html.ts | 131 ++++++++++++++ .../src/rules/public-env-only.test.ts | 132 ++++++++++++++ .../src/rules/public-env-only.ts | 97 ++++++++++ .../eslint-plugin-webtops/tsconfig.build.json | 13 ++ src/cli/layout.test.ts | 1 - 13 files changed, 1082 insertions(+), 2 deletions(-) create mode 100644 packages/eslint-plugin-webtops/package.json create mode 100644 packages/eslint-plugin-webtops/src/ast.ts create mode 100644 packages/eslint-plugin-webtops/src/index.test.ts create mode 100644 packages/eslint-plugin-webtops/src/index.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts create mode 100644 packages/eslint-plugin-webtops/src/rules/public-env-only.ts create mode 100644 packages/eslint-plugin-webtops/tsconfig.build.json diff --git a/WEB_TOPS.md b/WEB_TOPS.md index 2c1d6c2..8e49524 100644 --- a/WEB_TOPS.md +++ b/WEB_TOPS.md @@ -1130,6 +1130,7 @@ web-tops/ │ ├── report/ # report writing, text and JSON rendering │ └── survivors/ # the survivor key (section 6.4), and the ledger when it lands ├── profiles/ # one profile per launch class: the data init renders from +├── packages/ # eslint-plugin-webtops: the custom ESLint rules behind W-23, W-36 and W-37 ├── laws/ # one W-NN.yaml per law (§8.3): the source of the §8.2 tables ├── schema/ # web-tops, gate-report, baseline, core (verdicts, modes) and law schemas ├── config/ # drop-in templates, AGENTS.md.tmpl @@ -1143,7 +1144,7 @@ web-tops/ └── LICENSE · LICENSE-MIT · LICENSE-APACHE ``` -Not yet in the tree: `src/budgets/` (the `dist/` byte reader, M4) and the M3 paths: `fixtures/laws/W-NN/{bad,clean}/` (a bad and a clean twin per law), `packages/eslint-plugin-webtops/`, `examples/node-service/`, `src/layers/laws/`, `src/acks/` and `src/lawdiff/`. The kit's tools already cover them: the M3 source paths and the plugin are linted, type-checked, formatted, cruised and tested like the rest of the source; the law fixtures are data, skipped like the probe fixtures; `examples/node-service` gates itself. +Not yet in the tree: `src/budgets/` (the `dist/` byte reader, M4) and the M3 paths: `fixtures/laws/W-NN/{bad,clean}/` (a bad and a clean twin per law), `examples/node-service/`, `src/layers/laws/`, `src/acks/` and `src/lawdiff/`. The kit's tools already cover them: the M3 source paths and the plugin are linted, type-checked, formatted, cruised and tested like the rest of the source; the law fixtures are data, skipped like the probe fixtures; `examples/node-service` gates itself. Self-hosting: the kit runs `hard` and passes its own tier-1 gate before any release. diff --git a/packages/eslint-plugin-webtops/package.json b/packages/eslint-plugin-webtops/package.json new file mode 100644 index 0000000..7fa27d5 --- /dev/null +++ b/packages/eslint-plugin-webtops/package.json @@ -0,0 +1,26 @@ +{ + "name": "eslint-plugin-webtops", + "version": "0.3.0", + "private": true, + "description": "ESLint rules behind Web-TOPS laws W-23, W-36 and W-37 (complete Tailwind classes, no unsanitized HTML, public env only in client code)", + "license": "MIT OR Apache-2.0", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "peerDependencies": { + "eslint": ">=10.15.0" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + } +} diff --git a/packages/eslint-plugin-webtops/src/ast.ts b/packages/eslint-plugin-webtops/src/ast.ts new file mode 100644 index 0000000..e1eeb18 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ast.ts @@ -0,0 +1,101 @@ +/** + * A syntax node as the parser hands it over. ESLint's typings leave out JSX and Astro nodes, so the + * rules read every node by its shape: `type`, then the fields they care about. + */ +export type Loose = Readonly>; + +const isLoose = (value: unknown): value is Loose => typeof value === "object" && value !== null; + +/** The node's `type`, or undefined for anything that is not a node. */ +export function kind(node: unknown): string | undefined { + const type = isLoose(node) ? node["type"] : undefined; + return typeof type === "string" ? type : undefined; +} + +/** One field of a node, or undefined. */ +export const child = (node: unknown, key: string): unknown => + isLoose(node) ? node[key] : undefined; + +/** A list field of a node: empty when the field is absent or not a list. */ +export function children(node: unknown, key: string): readonly unknown[] { + const value = child(node, key); + return Array.isArray(value) ? value : []; +} + +/** The cooked text of a template element. */ +const cooked = (quasi: unknown): string | undefined => { + const text = child(child(quasi, "value"), "cooked"); + return typeof text === "string" ? text : undefined; +}; + +/** The static text of a template literal's parts: one string per quasi, `""` for a part the parser could not cook. */ +export const quasisOf = (template: unknown): readonly string[] => + children(template, "quasis").map((quasi) => cooked(quasi) ?? ""); + +const literalText = (node: unknown): string | undefined => { + const value = child(node, "value"); + return typeof value === "string" ? value : undefined; +}; + +const plainTemplateText = (node: unknown): string | undefined => + children(node, "expressions").length === 0 ? quasisOf(node)[0] : undefined; + +const TEXT = new Map string | undefined>([ + ["Literal", literalText], + ["TemplateLiteral", plainTemplateText], +]); + +/** The entry of a table keyed by node type, for the node's own type. */ +export function byKind(table: ReadonlyMap, node: unknown): T | undefined { + const type = kind(node); + return type === undefined ? undefined : table.get(type); +} + +/** The text of a string literal or of a template literal with no interpolation; undefined for anything else. */ +export const staticText = (node: unknown): string | undefined => byKind(TEXT, node)?.(node); + +const joined = (object: string | undefined, property: string | undefined): string | undefined => + object !== undefined && property !== undefined ? `${object}.${property}` : undefined; + +const memberName = (node: unknown): string | undefined => + kind(node) === "MemberExpression" && child(node, "computed") !== true + ? joined(dottedName(child(node, "object")), nameOf(child(node, "property"))) + : undefined; + +/** `name` for an identifier, `a.b.c` for a chain of member accesses, else undefined. */ +export const dottedName = (node: unknown): string | undefined => + kind(node) === "Identifier" ? nameOf(node) : memberName(node); + +/** The `name` field of an identifier-like node. */ +export function nameOf(node: unknown): string | undefined { + const name = child(node, "name"); + return typeof name === "string" ? name : undefined; +} + +/** The name a property is read by: `a.b` and `a["b"]`; undefined for a computed key that is not a string literal. */ +export const propertyName = (member: unknown): string | undefined => + child(member, "computed") === true + ? staticText(child(member, "property")) + : nameOf(child(member, "property")); + +const namespaced = (name: unknown): string => + `${nameOf(child(name, "namespace")) ?? ""}:${nameOf(child(name, "name")) ?? ""}`; + +/** The attribute's name: `className`, or `set:html` for a namespaced one. */ +export function attributeName(attribute: unknown): string | undefined { + const name = child(attribute, "name"); + return kind(name) === "JSXNamespacedName" ? namespaced(name) : nameOf(name); +} + +/** The expression inside `attr={...}`, or the literal of `attr="..."`. */ +export function attributeValue(attribute: unknown): unknown { + const value = child(attribute, "value"); + return kind(value) === "JSXExpressionContainer" ? child(value, "expression") : value; +} + +/** Strings from a rule option that should be a list of them: anything else is dropped. */ +export function stringList(option: unknown, key: string, fallback: readonly string[]): string[] { + const value = child(option, key); + if (!Array.isArray(value)) return [...fallback]; + return value.filter((entry): entry is string => typeof entry === "string"); +} diff --git a/packages/eslint-plugin-webtops/src/index.test.ts b/packages/eslint-plugin-webtops/src/index.test.ts new file mode 100644 index 0000000..1c1e29b --- /dev/null +++ b/packages/eslint-plugin-webtops/src/index.test.ts @@ -0,0 +1,87 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { ESLint } from "eslint"; +import { afterAll, describe, expect, it } from "vitest"; +import plugin from "./index.ts"; + +const root = resolve(import.meta.dirname, ".."); +const made: string[] = []; +afterAll(() => { + for (const dir of made) rmSync(dir, { recursive: true, force: true }); +}); + +/** A value the test needs to be there. */ +function need(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} + +const RULES = ["complete-tailwind-classes", "no-unsanitized-html", "public-env-only"]; + +describe("G6a: eslint-plugin-webtops", () => { + it("names itself and holds the three rules of W-23, W-36 and W-37", () => { + expect(plugin.meta).toEqual({ name: "eslint-plugin-webtops" }); + expect(Object.keys(plugin.rules ?? {}).sort()).toEqual(RULES); + }); + + it.each(RULES)("%s says which law it judges, and has a message and a schema", (name) => { + const meta = need(need(need(plugin.rules)[name]).meta); + expect(need(meta.docs).description).toMatch(/\(W-\d+\)$/u); + expect(Object.keys(need(meta.messages))).not.toHaveLength(0); + expect(need(meta.schema)).toBeDefined(); + }); + + it("has a manifest that exports the built entry and asks for ESLint 10", () => { + const manifest: unknown = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + expect(manifest).toMatchObject({ + name: "eslint-plugin-webtops", + type: "module", + exports: { ".": { default: "./dist/index.js" } }, + peerDependencies: { eslint: ">=10.15.0" }, + }); + }); + + it("is live in ESLint: a flat config that names the rules gets each of them reported", async () => { + const eslint = new ESLint({ + overrideConfigFile: true, + overrideConfig: { + files: ["**/*.jsx"], + plugins: { webtops: plugin }, + languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } }, + rules: { + "webtops/complete-tailwind-classes": "error", + "webtops/no-unsanitized-html": "error", + "webtops/public-env-only": "error", + }, + }, + }); + const code = [ + "export const A = ({ c, h }) =>
;", + "export const B = import.meta.env.SECRET;", + ].join("\n"); + const [result] = await eslint.lintText(code, { filePath: "a.jsx" }); + expect(result?.messages.map((message) => message.ruleId).sort()).toEqual( + RULES.map((name) => `webtops/${name}`), + ); + }); + + it("builds with tsc, and the built package loads under Node with the same three rules", () => { + const out = mkdtempSync(join(tmpdir(), "wt-plugin-")); + made.push(out); + const tsc = resolve(root, "../../node_modules/.bin/tsc"); + const build = spawnSync(tsc, ["-p", "tsconfig.build.json", "--outDir", out], { + cwd: root, + encoding: "utf8", + }); + expect(build.status, build.stdout + build.stderr).toBe(0); + const entry = JSON.stringify(join(out, "index.js")); + const script = `const p = (await import(${entry})).default; console.log(Object.keys(p.rules).sort().join());`; + const load = spawnSync("node", ["--input-type=module", "--eval", script], { + encoding: "utf8", + }); + expect(load.status, load.stderr).toBe(0); + expect(load.stdout.trim()).toBe(RULES.join()); + }, 60_000); +}); diff --git a/packages/eslint-plugin-webtops/src/index.ts b/packages/eslint-plugin-webtops/src/index.ts new file mode 100644 index 0000000..831ecb3 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/index.ts @@ -0,0 +1,16 @@ +import type { ESLint } from "eslint"; +import completeTailwindClasses from "./rules/complete-tailwind-classes.ts"; +import noUnsanitizedHtml from "./rules/no-unsanitized-html.ts"; +import publicEnvOnly from "./rules/public-env-only.ts"; + +/** The rules behind Web-TOPS laws W-23, W-36 and W-37, under the `webtops` namespace. */ +const plugin: ESLint.Plugin = { + meta: { name: "eslint-plugin-webtops" }, + rules: { + "complete-tailwind-classes": completeTailwindClasses, + "no-unsanitized-html": noUnsanitizedHtml, + "public-env-only": publicEnvOnly, + }, +}; + +export default plugin; diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts new file mode 100644 index 0000000..d973d92 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts @@ -0,0 +1,169 @@ +import { RuleTester } from "eslint"; +import { describe, it } from "vitest"; +import rule from "./complete-tailwind-classes.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + parserOptions: { ecmaFeatures: { jsx: true } }, + }, +}); + +const incomplete = [{ messageId: "incomplete" as const }]; + +tester.run("complete-tailwind-classes", rule, { + valid: [ + { name: "a whole class string", code: '
' }, + { name: "a lookup of complete strings", code: "
" }, + { + name: "whole tokens chosen by a condition", + code: '
', + }, + { name: "interpolated tokens are whole", code: "
" }, + { name: "an interpolation at the edges", code: "
" }, + { name: "a single interpolation", code: "
" }, + { + name: "a concatenation that keeps tokens whole", + code: '
', + }, + { name: "two static strings", code: '
' }, + { name: "the class attribute", code: '
' }, + { name: "an attribute that is not a class list", code: "
" }, + { name: "a name built outside a class list", code: "const id = `bg-${color}-500`;" }, + { name: "a call that is not a class helper", code: "other(`bg-${color}-500`);" }, + { + name: "a helper given whole strings", + code: 'clsx("flex", on && "bg-red-500", { "p-2": big });', + }, + { name: "a helper given a spread", code: "cn(...list);" }, + { name: "a member callee that is not a helper", code: "styles.pick(`bg-${c}`);" }, + { name: "a concat that keeps tokens whole", code: 'const a = "flex ".concat(extra);' }, + { + name: "an object key that is a plain string", + code: 'clsx({ "bg-red-500": on, [name]: off });', + }, + { + name: "a custom helper list leaves clsx alone", + code: "clsx(`bg-${c}`);", + options: [{ functions: ["tw"] }], + }, + { name: "a numeric addition", code: "
" }, + { name: "a template in a computed member", code: "
" }, + ], + invalid: [ + { + name: "interpolation inside a token", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation that ends a token", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation that starts a token", + code: "
", + errors: incomplete, + }, + { + name: "two interpolations glued", + code: "
", + errors: incomplete, + }, + { + name: "interpolation in the class attribute", + code: "
", + errors: incomplete, + }, + { + name: "concatenation of a prefix", + code: '
', + errors: incomplete, + }, + { + name: "concatenation of a suffix", + code: '
', + errors: incomplete, + }, + { + name: "concatenation in the middle of a chain", + code: '
', + errors: incomplete, + }, + { + name: "concatenation with a template prefix", + code: "
", + errors: incomplete, + }, + { + name: "interpolation in one branch", + code: '
', + errors: incomplete, + }, + { + name: "interpolation in the other branch", + code: '
', + errors: incomplete, + }, + { + name: "interpolation after &&", + code: "
", + errors: incomplete, + }, + { + name: "interpolation before ||", + code: '
', + errors: incomplete, + }, + { + name: "interpolation in an array", + code: '
', + errors: incomplete, + }, + { + name: "interpolation nested in an interpolation", + code: "
", + errors: incomplete, + }, + { + name: "concatenation inside an interpolation", + code: '
', + errors: incomplete, + }, + { name: "a concat call", code: '
', errors: incomplete }, + { + name: "a concat call with a suffix", + code: '
', + errors: incomplete, + }, + { + name: "clsx with an interpolated token", + code: "clsx(`bg-${color}-500`);", + errors: incomplete, + }, + { + name: "cn with a concatenated token", + code: 'cn("flex", "bg-" + color);', + errors: incomplete, + }, + { name: "an array argument", code: "cva([`bg-${c}`]);", errors: incomplete }, + { + name: "an object key built by interpolation", + code: "clsx({ [`bg-${c}`]: on });", + errors: incomplete, + }, + { name: "a nested helper call", code: "twMerge(clsx(`bg-${c}`));", errors: incomplete }, + { + name: "a member helper from the options", + code: "ui.tw(`bg-${c}`);", + options: [{ functions: ["ui.tw"] }], + errors: incomplete, + }, + { name: "a conditional argument", code: "cn(on ? `bg-${c}` : null);", errors: incomplete }, + ], +}); diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts new file mode 100644 index 0000000..c7405c8 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts @@ -0,0 +1,143 @@ +import type { Rule } from "eslint"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + kind, + propertyName, + quasisOf, + staticText, + stringList, +} from "../ast.ts"; + +/** W-23: a Tailwind class name is a complete string, never built by interpolation or concatenation. */ + +const CLASS_ATTRIBUTES = new Set(["className", "class"]); +const HELPERS = ["clsx", "cn", "classnames", "classNames", "twMerge", "twJoin", "cva", "tv"]; + +const endsInToken = (text: string | undefined): boolean => text !== undefined && /\S$/u.test(text); +const startsInToken = (text: string | undefined): boolean => + text !== undefined && /^\S/u.test(text); + +/** Text before or after an interpolation touches it: it holds a character, or an interpolation sits on that side. */ +const glued = (text: string, neighbour: boolean, edge: RegExp): boolean => + text === "" ? neighbour : edge.test(text); + +/** Whether the interpolation at `index` shares a token with static text, or with another interpolation. */ +function touches(quasis: readonly string[], index: number, count: number): boolean { + return ( + glued(quasis[index] ?? "", index > 0, /\S$/u) || + glued(quasis[index + 1] ?? "", index + 1 < count, /^\S/u) + ); +} + +function templateBuildsToken(template: unknown): boolean { + const quasis = quasisOf(template); + const expressions = children(template, "expressions"); + return ( + expressions.some((_, index) => touches(quasis, index, expressions.length)) || + expressions.some(buildsToken) + ); +} + +/** Static text meets a computed part with no space between: `"bg-" + color`, `color + "-500"`. */ +function pairGlued(left: unknown, right: unknown): boolean { + const before = staticText(left); + const after = staticText(right); + return ( + (after === undefined && endsInToken(before)) || (before === undefined && startsInToken(after)) + ); +} + +/** The operands of a chain of `+`, left to right. */ +function operands(node: unknown): readonly unknown[] { + const plus = kind(node) === "BinaryExpression" && child(node, "operator") === "+"; + return plus ? [...operands(child(node, "left")), ...operands(child(node, "right"))] : [node]; +} + +function partsBuildToken(parts: readonly unknown[]): boolean { + return ( + parts.slice(0, -1).some((part, index) => pairGlued(part, parts[index + 1])) || + parts.some(buildsToken) + ); +} + +/** Method calls that build a class string: `"bg-".concat(color)` joins like `+`, and `[...].join(" ")` builds from its items. */ +const METHODS = new Map boolean>([ + ["concat", (object, args) => partsBuildToken([object, ...args])], + ["join", (object) => buildsToken(object)], +]); + +function methodBuildsToken(call: unknown): boolean { + const callee = child(call, "callee"); + const method = METHODS.get( + kind(callee) === "MemberExpression" ? (propertyName(callee) ?? "") : "", + ); + return method?.(child(callee, "object"), children(call, "arguments")) === true; +} + +const keyBuildsToken = (property: unknown): boolean => + child(property, "computed") === true && buildsToken(child(property, "key")); + +const CHECKS = new Map boolean>([ + ["TemplateLiteral", templateBuildsToken], + ["BinaryExpression", (node) => partsBuildToken(operands(node))], + ["CallExpression", methodBuildsToken], + [ + "ConditionalExpression", + (node) => buildsToken(child(node, "consequent")) || buildsToken(child(node, "alternate")), + ], + [ + "LogicalExpression", + (node) => buildsToken(child(node, "left")) || buildsToken(child(node, "right")), + ], + ["ArrayExpression", (node) => children(node, "elements").some(buildsToken)], + ["ObjectExpression", (node) => children(node, "properties").some(keyBuildsToken)], +]); + +/** Whether an expression that ends up in a class list builds a class token at run time. */ +export const buildsToken = (node: unknown): boolean => byKind(CHECKS, node)?.(node) === true; + +const rule: Rule.RuleModule = { + meta: { + type: "problem", + docs: { + description: + "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", + }, + schema: [ + { + type: "object", + properties: { functions: { type: "array", items: { type: "string" }, uniqueItems: true } }, + additionalProperties: false, + }, + ], + messages: { + incomplete: + "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", + }, + }, + create(context) { + const option: unknown = context.options[0]; + const helpers = new Set(stringList(option, "functions", HELPERS)); + return { + JSXAttribute(node: Rule.Node) { + const name = attributeName(node); + if (name !== undefined && CLASS_ATTRIBUTES.has(name) && buildsToken(attributeValue(node))) { + context.report({ node, messageId: "incomplete" }); + } + }, + CallExpression(node) { + const callee = dottedName(node.callee); + if (helpers.has(callee ?? "") && node.arguments.some(buildsToken)) { + context.report({ node, messageId: "incomplete" }); + } + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts new file mode 100644 index 0000000..f9c8894 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts @@ -0,0 +1,165 @@ +import { RuleTester } from "eslint"; +import { describe, it } from "vitest"; +import rule from "./no-unsanitized-html.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + parserOptions: { ecmaFeatures: { jsx: true } }, + }, +}); + +const DEFAULT = "sanitize, sanitizeHtml, DOMPurify.sanitize"; +const unsanitized = (sink: string, sanitizers = DEFAULT) => [ + { messageId: "unsanitized" as const, data: { sink, sanitizers } }, +]; + +tester.run("no-unsanitized-html", rule, { + valid: [ + { + name: "a static HTML object", + code: '
x" }} />', + }, + { + name: "a template with no interpolation", + code: "
x` }} />", + }, + { + name: "a sanitized value", + code: "
", + }, + { + name: "DOMPurify", + code: "
", + }, + { + name: "sanitizeHtml", + code: "
", + }, + { name: "an empty object sets nothing", code: "
" }, + { + name: "an object with only another key", + code: "
", + }, + { name: "a static set:html", code: '
' }, + { name: "a sanitized set:html", code: "
" }, + { name: "both branches safe", code: '
"} />' }, + { name: "textContent is not a sink", code: "el.textContent = value;" }, + { name: "a static innerHTML", code: 'el.innerHTML = "x";' }, + { name: "a sanitized innerHTML", code: "el.innerHTML = sanitize(html);" }, + { name: "a sanitized outerHTML", code: "el.outerHTML = DOMPurify.sanitize(html);" }, + { + name: "a sanitized insertAdjacentHTML", + code: 'el.insertAdjacentHTML("beforeend", sanitize(html));', + }, + { name: "a static document.write", code: 'document.write("

");' }, + { name: "a call that is not a sink", code: "el.append(html);" }, + { name: "a plain call", code: "run(html);" }, + { name: "an attribute that is not a sink", code: "
" }, + { name: "a computed property that is not a sink", code: "el[name] = html;" }, + { + name: "a custom sanitizer", + code: "el.innerHTML = clean(html);", + options: [{ sanitizers: ["clean"] }], + }, + { name: "an assignment to a variable", code: "let x; x = html;" }, + { name: "a computed innerHTML with a literal", code: 'el["innerHTML"] = "";' }, + ], + invalid: [ + { + name: "a variable in dangerouslySetInnerHTML", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a template with interpolation", + code: "
${x}` }} />", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a props object that is not a literal", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a call that is not a sanitizer", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a member call that is not a sanitizer", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "one unsafe branch", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a variable in set:html", + code: "
", + errors: unsanitized("set:html"), + }, + { + name: "set:html with an attribute string that is an expression", + code: "
${x}`} />", + errors: unsanitized("set:html"), + }, + { + name: "innerHTML with a variable", + code: "el.innerHTML = html;", + errors: unsanitized("innerHTML"), + }, + { + name: "innerHTML appended to", + code: "el.innerHTML += html;", + errors: unsanitized("innerHTML"), + }, + { + name: "outerHTML with a variable", + code: "el.outerHTML = html;", + errors: unsanitized("outerHTML"), + }, + { + name: "innerHTML set by a computed string key", + code: 'el["innerHTML"] = html;', + errors: unsanitized("innerHTML"), + }, + { + name: "innerHTML with a template", + code: "el.innerHTML = `${x}`;", + errors: unsanitized("innerHTML"), + }, + { + name: "insertAdjacentHTML with a variable", + code: 'el.insertAdjacentHTML("beforeend", html);', + errors: unsanitized("insertAdjacentHTML"), + }, + { + name: "insertAdjacentHTML with no markup argument", + code: 'el.insertAdjacentHTML("beforeend");', + errors: unsanitized("insertAdjacentHTML"), + }, + { + name: "document.write with a variable", + code: "document.write(html);", + errors: unsanitized("document.write"), + }, + { + name: "document.writeln with a variable", + code: "document.writeln(html);", + errors: unsanitized("document.writeln"), + }, + { + name: "a sanitizer the options replaced", + code: "el.innerHTML = sanitize(html);", + options: [{ sanitizers: ["clean"] }], + errors: unsanitized("innerHTML", "clean"), + }, + ], +}); diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts new file mode 100644 index 0000000..ac185fe --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts @@ -0,0 +1,131 @@ +import type { Rule } from "eslint"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + kind, + nameOf, + propertyName, + staticText, + stringList, +} from "../ast.ts"; + +/** W-36: HTML reaches `set:html`, `dangerouslySetInnerHTML` or `innerHTML` only as a literal or through a sanitizer. */ + +const SANITIZERS = ["sanitize", "sanitizeHtml", "DOMPurify.sanitize"]; +const ASSIGNED_SINKS = new Set(["innerHTML", "outerHTML"]); +const WRITERS = new Set(["document.write", "document.writeln"]); + +/** Where markup goes in, and what is put there. */ +interface Sink { + readonly sink: string; + readonly html: unknown; +} + +type Safe = (node: unknown, sanitizers: ReadonlySet) => boolean; + +const SAFE = new Map([ + ["CallExpression", (node, sanitizers) => sanitizers.has(dottedName(child(node, "callee")) ?? "")], + [ + "ConditionalExpression", + (node, sanitizers) => + isSafe(child(node, "consequent"), sanitizers) && isSafe(child(node, "alternate"), sanitizers), + ], +]); + +/** A literal, or the result of a sanitizer; a conditional is safe when both branches are. */ +export const isSafe = (node: unknown, sanitizers: ReadonlySet): boolean => + staticText(node) !== undefined || byKind(SAFE, node)?.(node, sanitizers) === true; + +/** What `dangerouslySetInnerHTML={{ __html: x }}` sets: `x`; a value that is not an object literal is its own payload. */ +function htmlPayload(value: unknown): unknown { + if (kind(value) !== "ObjectExpression") return value; + const entry = children(value, "properties").find( + (property) => nameOf(child(property, "key")) === "__html", + ); + return entry === undefined ? { type: "Literal", value: "" } : child(entry, "value"); +} + +const ATTRIBUTE_SINKS = new Map unknown>([ + ["dangerouslySetInnerHTML", htmlPayload], + ["set:html", (value) => value], +]); + +function attributeSink(attribute: unknown): Sink | undefined { + const name = attributeName(attribute) ?? ""; + const payload = ATTRIBUTE_SINKS.get(name); + return payload === undefined + ? undefined + : { sink: name, html: payload(attributeValue(attribute)) }; +} + +function assignedSink(assignment: unknown): Sink | undefined { + const left = child(assignment, "left"); + const sink = kind(left) === "MemberExpression" ? propertyName(left) : undefined; + return sink !== undefined && ASSIGNED_SINKS.has(sink) + ? { sink, html: child(assignment, "right") } + : undefined; +} + +function insertedSink(call: unknown): Sink | undefined { + const callee = child(call, "callee"); + const inserts = + kind(callee) === "MemberExpression" && propertyName(callee) === "insertAdjacentHTML"; + return inserts ? { sink: "insertAdjacentHTML", html: children(call, "arguments")[1] } : undefined; +} + +function writtenSink(call: unknown): Sink | undefined { + const name = dottedName(child(call, "callee")); + return name !== undefined && WRITERS.has(name) + ? { sink: name, html: children(call, "arguments")[0] } + : undefined; +} + +const callSink = (call: unknown): Sink | undefined => insertedSink(call) ?? writtenSink(call); + +const rule: Rule.RuleModule = { + meta: { + type: "problem", + docs: { + description: + "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", + }, + schema: [ + { + type: "object", + properties: { sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true } }, + additionalProperties: false, + }, + ], + messages: { + unsanitized: + "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", + }, + }, + create(context) { + const option: unknown = context.options[0]; + const list = stringList(option, "sanitizers", SANITIZERS); + const sanitizers = new Set(list); + const inspect = (node: Rule.Node, found: Sink | undefined): void => { + if (found === undefined || isSafe(found.html, sanitizers)) return; + const data = { sink: found.sink, sanitizers: list.join(", ") }; + context.report({ node, messageId: "unsanitized", data }); + }; + return { + JSXAttribute: (node: Rule.Node) => { + inspect(node, attributeSink(node)); + }, + AssignmentExpression: (node) => { + inspect(node, assignedSink(node)); + }, + CallExpression: (node) => { + inspect(node, callSink(node)); + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts new file mode 100644 index 0000000..dbf58f7 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts @@ -0,0 +1,132 @@ +import { RuleTester } from "eslint"; +import { describe, it } from "vitest"; +import rule from "./public-env-only.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { ecmaVersion: "latest", sourceType: "module" }, +}); + +const privateName = (name: string) => [ + { messageId: "private" as const, data: { name, prefixes: "PUBLIC_" } }, +]; + +tester.run("public-env-only", rule, { + valid: [ + { + name: "a public import.meta.env variable", + code: "const a = import.meta.env.PUBLIC_API_URL;", + }, + { name: "a public process.env variable", code: "const a = process.env.PUBLIC_API_URL;" }, + { name: "a built-in", code: "const a = import.meta.env.MODE + import.meta.env.BASE_URL;" }, + { + name: "every built-in", + code: "const a = [import.meta.env.DEV, import.meta.env.PROD, import.meta.env.SSR, import.meta.env.SITE];", + }, + { name: "a computed public name", code: 'const a = import.meta.env["PUBLIC_KEY"];' }, + { + name: "a destructured public variable", + code: "const { PUBLIC_KEY, MODE } = import.meta.env;", + }, + { + name: "a renamed destructured public variable", + code: "const { PUBLIC_KEY: key } = process.env;", + }, + { name: "the client module", code: 'import { PUBLIC_X } from "astro:env/client";' }, + { name: "another import", code: 'import { x } from "./x";' }, + { name: "another object named env", code: "const a = config.env.SECRET;" }, + { name: "another meta property", code: "const a = import.meta.url;" }, + { name: "another process property", code: "const a = process.argv;" }, + { + name: "a custom prefix", + code: "const a = process.env.NEXT_PUBLIC_KEY;", + options: [{ prefixes: ["NEXT_PUBLIC_"] }], + }, + { + name: "a custom allowed name", + code: "const a = process.env.NODE_ENV;", + options: [{ allowed: ["NODE_ENV"] }], + }, + { name: "a member of another object", code: "const a = other.SECRET;" }, + { + name: "a nested access on a public value", + code: "const a = process.env.PUBLIC_LIST.length;", + }, + ], + invalid: [ + { + name: "a private import.meta.env variable", + code: "const a = import.meta.env.SECRET_KEY;", + errors: privateName("SECRET_KEY"), + }, + { + name: "a private process.env variable", + code: "const a = process.env.DATABASE_URL;", + errors: privateName("DATABASE_URL"), + }, + { + name: "a private variable by string key", + code: 'const a = process.env["DATABASE_URL"];', + errors: privateName("DATABASE_URL"), + }, + { + name: "a computed name", + code: "const a = import.meta.env[name];", + errors: [{ messageId: "dynamic" }], + }, + { + name: "a destructured private variable", + code: "const { SECRET } = import.meta.env;", + errors: privateName("SECRET"), + }, + { + name: "a renamed destructured private variable", + code: "const { SECRET: s } = process.env;", + errors: privateName("SECRET"), + }, + { + name: "a rest element", + code: "const { ...all } = process.env;", + errors: [{ messageId: "dynamic" }], + }, + { + name: "a computed pattern key", + code: "const { [name]: v } = process.env;", + errors: [{ messageId: "dynamic" }], + }, + { + name: "the whole object passed on", + code: "send(import.meta.env);", + errors: [{ messageId: "whole" }], + }, + { + name: "the whole process.env spread", + code: "const a = { ...process.env };", + errors: [{ messageId: "whole" }], + }, + { + name: "the server module", + code: 'import { SECRET } from "astro:env/server";', + errors: [{ messageId: "server", data: { name: "astro:env/server" } }], + }, + { + name: "a prefix the options replaced", + code: "const a = process.env.PUBLIC_KEY;", + options: [{ prefixes: ["NEXT_PUBLIC_"] }], + errors: [{ messageId: "private", data: { name: "PUBLIC_KEY", prefixes: "NEXT_PUBLIC_" } }], + }, + { + name: "a built-in the options removed", + code: "const a = import.meta.env.MODE;", + options: [{ allowed: [] }], + errors: privateName("MODE"), + }, + { + name: "two private variables", + code: "const a = [process.env.A, process.env.B];", + errors: [{ messageId: "private" }, { messageId: "private" }], + }, + ], +}); diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts new file mode 100644 index 0000000..38d1de9 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts @@ -0,0 +1,97 @@ +import type { Rule } from "eslint"; +import { child, children, dottedName, kind, nameOf, propertyName, stringList } from "../ast.ts"; + +/** W-37: client code reads only public env: `PUBLIC_` variables, and `astro:env/client` fields. */ + +const PREFIXES = ["PUBLIC_"]; +/** What Vite and Astro define for every build, and none of it is a secret. */ +const BUILT_IN = ["MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE"]; + +/** `process.env` or `import.meta.env`. */ +function isEnvObject(node: unknown): boolean { + if (kind(node) !== "MemberExpression") return false; + const meta = kind(child(node, "object")) === "MetaProperty"; + return dottedName(node) === "process.env" || (meta && propertyName(node) === "env"); +} + +/** The key of a pattern property: `{ KEY }` and `{ KEY: alias }`; undefined for a computed or rest entry. */ +const patternKey = (property: unknown): string | undefined => + kind(property) === "Property" && child(property, "computed") !== true + ? nameOf(child(property, "key")) + : undefined; + +const isChildOf = (parent: unknown, type: string, field: string, node: unknown): boolean => + kind(parent) === type && child(parent, field) === node; + +/** How an env object is used: read by member (checked at that member), destructured, or handed over whole. */ +function usage(parent: unknown, node: unknown): "read" | "destructured" | "whole" { + if (isChildOf(parent, "MemberExpression", "object", node)) return "read"; + return isChildOf(parent, "VariableDeclarator", "init", node) ? "destructured" : "whole"; +} + +const rule: Rule.RuleModule = { + meta: { + type: "problem", + docs: { description: "Only public env reaches client code (W-37)" }, + schema: [ + { + type: "object", + properties: { + prefixes: { type: "array", items: { type: "string" }, uniqueItems: true }, + allowed: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + private: + "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", + dynamic: + "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", + whole: + "The whole env object reaches client code. Read the public variables you need, by name.", + server: + "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", + }, + }, + create(context) { + const option: unknown = context.options[0]; + const prefixes = stringList(option, "prefixes", PREFIXES); + const allowed = new Set(stringList(option, "allowed", BUILT_IN)); + const isPublic = (name: string): boolean => + allowed.has(name) || prefixes.some((prefix) => name.startsWith(prefix)); + const reportName = (node: Rule.Node, name: string | undefined): void => { + if (name === undefined) context.report({ node, messageId: "dynamic" }); + else if (!isPublic(name)) { + context.report({ + node, + messageId: "private", + data: { name, prefixes: prefixes.join(", ") }, + }); + } + }; + const inspectEnv = (node: Rule.Node): void => { + const parent: unknown = node.parent; + const use = usage(parent, node); + if (use === "whole") context.report({ node, messageId: "whole" }); + if (use === "destructured") { + for (const property of children(child(parent, "id"), "properties")) { + reportName(node, patternKey(property)); + } + } + }; + return { + ImportDeclaration(node) { + if (node.source.value === "astro:env/server") { + context.report({ node, messageId: "server", data: { name: "astro:env/server" } }); + } + }, + MemberExpression(node) { + if (isEnvObject(node.object)) reportName(node, propertyName(node)); + else if (isEnvObject(node)) inspectEnv(node); + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/tsconfig.build.json b/packages/eslint-plugin-webtops/tsconfig.build.json new file mode 100644 index 0000000..317d713 --- /dev/null +++ b/packages/eslint-plugin-webtops/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": false, + "outDir": "dist", + "rootDir": "src", + "declaration": true, + "rewriteRelativeImportExtensions": true, + "types": [] + }, + "include": ["src"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/src/cli/layout.test.ts b/src/cli/layout.test.ts index cf6b5a6..dc36e30 100644 --- a/src/cli/layout.test.ts +++ b/src/cli/layout.test.ts @@ -59,7 +59,6 @@ describe("G10a: section 17 matches the tree", () => { expect(paths).toEqual( expect.arrayContaining([ "src/budgets/", - "packages/eslint-plugin-webtops/", "fixtures/laws/W-NN/{bad,clean}/", "examples/node-service/", ]), From b3058c854c401dd486040985c194ae318572c513 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 10:44:45 -0500 Subject: [PATCH 2/8] Build the plugin without type checks inside the mutation sandbox Stryker instruments the sources in its sandbox, so a build that type checks them fails there. The test builds with --noCheck; the types are checked by the gate's own tsc run on the same files. Co-Authored-By: Claude Sonnet 5.5 --- packages/eslint-plugin-webtops/src/index.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/eslint-plugin-webtops/src/index.test.ts b/packages/eslint-plugin-webtops/src/index.test.ts index 1c1e29b..7fa69ca 100644 --- a/packages/eslint-plugin-webtops/src/index.test.ts +++ b/packages/eslint-plugin-webtops/src/index.test.ts @@ -67,11 +67,11 @@ describe("G6a: eslint-plugin-webtops", () => { ); }); - it("builds with tsc, and the built package loads under Node with the same three rules", () => { + it("builds with tsc (types are checked by the gate's own tsc run), and the built package loads under Node", () => { const out = mkdtempSync(join(tmpdir(), "wt-plugin-")); made.push(out); const tsc = resolve(root, "../../node_modules/.bin/tsc"); - const build = spawnSync(tsc, ["-p", "tsconfig.build.json", "--outDir", out], { + const build = spawnSync(tsc, ["-p", "tsconfig.build.json", "--noCheck", "--outDir", out], { cwd: root, encoding: "utf8", }); From 9bbfe1430299ebe8181a3bd5b4d35658930f015d Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 12:18:14 -0500 Subject: [PATCH 3/8] Kill the plugin's mutation survivors, and stop a non-plus sum from recursing A binary expression with an operator other than + (`"bg-" - c`) sent the W-23 rule into endless recursion; only plus chains are joined now. Tests: direct tests of the node-reading helpers, each rule's meta stated in full, and cases for each helper name, each side of a glued interpolation, and the env object in unusual positions. Branches that no input could tell apart are gone: the kind checks a member lookup already makes, the computed-key test, and the placeholder payload of an empty dangerouslySetInnerHTML. Co-Authored-By: Claude Sonnet 5.5 --- .../eslint-plugin-webtops/src/ast.test.ts | 112 ++++++++++++++++++ packages/eslint-plugin-webtops/src/ast.ts | 6 + .../rules/complete-tailwind-classes.test.ts | 83 ++++++++++++- .../src/rules/complete-tailwind-classes.ts | 35 +++--- .../src/rules/no-unsanitized-html.test.ts | 29 ++++- .../src/rules/no-unsanitized-html.ts | 35 +++--- .../src/rules/public-env-only.test.ts | 53 ++++++++- .../src/rules/public-env-only.ts | 21 +--- 8 files changed, 320 insertions(+), 54 deletions(-) create mode 100644 packages/eslint-plugin-webtops/src/ast.test.ts diff --git a/packages/eslint-plugin-webtops/src/ast.test.ts b/packages/eslint-plugin-webtops/src/ast.test.ts new file mode 100644 index 0000000..cc97d09 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ast.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "vitest"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + kind, + lookup, + propertyName, + quasisOf, + staticText, + stringList, +} from "./ast.ts"; + +const id = (name: string) => ({ type: "Identifier", name }); +const member = (object: unknown, property: unknown, computed = false) => ({ + type: "MemberExpression", + object, + property, + computed, +}); +const literal = (value: unknown) => ({ type: "Literal", value }); + +describe("reading nodes by shape", () => { + it("takes a node's type and fields, and nothing from a value that is not a node", () => { + expect(kind(id("a"))).toBe("Identifier"); + expect(kind(null)).toBeUndefined(); + expect(kind("Identifier")).toBeUndefined(); + expect(kind({ type: 5 })).toBeUndefined(); + expect(child(null, "x")).toBeUndefined(); + expect(child({ x: 1 }, "x")).toBe(1); + }); + + it("reads a list field, and an empty list when it is absent or not a list", () => { + expect(children({ list: [1, 2] }, "list")).toEqual([1, 2]); + expect(children({}, "list")).toEqual([]); + expect(children({ list: "no" }, "list")).toEqual([]); + }); + + it("looks a node type or a name up in a table", () => { + const table = new Map([["Identifier", 1]]); + expect(byKind(table, id("a"))).toBe(1); + expect(byKind(table, literal("a"))).toBeUndefined(); + expect(byKind(table, null)).toBeUndefined(); + expect(lookup(table, "Identifier")).toBe(1); + expect(lookup(table, undefined)).toBeUndefined(); + }); + + it("gives the cooked text of each template part, and nothing for a part that cannot be cooked", () => { + const template = { + type: "TemplateLiteral", + quasis: [{ value: { cooked: "a" } }, { value: { cooked: null } }, { value: {} }], + expressions: [], + }; + expect(quasisOf(template)).toEqual(["a", "", ""]); + }); + + it("gives static text for a string literal and a template with no interpolation only", () => { + const plain = { + type: "TemplateLiteral", + quasis: [{ value: { cooked: "t" } }], + expressions: [], + }; + expect(staticText(literal("s"))).toBe("s"); + expect(staticText(literal(5))).toBeUndefined(); + expect(staticText(plain)).toBe("t"); + expect(staticText({ ...plain, expressions: [id("x")] })).toBeUndefined(); + expect(staticText(id("x"))).toBeUndefined(); + }); + + it("names an identifier, and a chain of plain member accesses", () => { + expect(dottedName(id("a"))).toBe("a"); + expect(dottedName(member(member(id("a"), id("b")), id("c")))).toBe("a.b.c"); + expect(dottedName(member(id("a"), literal("b"), true))).toBeUndefined(); + expect(dottedName(member(id("a"), id("b"), true))).toBeUndefined(); + expect(dottedName(member({ type: "ThisExpression" }, id("x")))).toBeUndefined(); + expect(dottedName(member(id("a"), { type: "PrivateIdentifier" }))).toBeUndefined(); + expect(dottedName(literal("a"))).toBeUndefined(); + }); + + it("names a property by identifier or by string key, and not by another computed key", () => { + expect(propertyName(member(id("a"), id("b")))).toBe("b"); + expect(propertyName(member(id("a"), literal("b"), true))).toBe("b"); + expect(propertyName(member(id("a"), id("b"), true))).toBeUndefined(); + }); + + it("names a JSX attribute, plain or namespaced, and reads its value", () => { + const plain = { type: "JSXAttribute", name: { type: "JSXIdentifier", name: "className" } }; + const spaced = { + type: "JSXAttribute", + name: { + type: "JSXNamespacedName", + namespace: { name: "set" }, + name: { name: "html" }, + }, + value: { type: "JSXExpressionContainer", expression: id("x") }, + }; + expect(attributeName(plain)).toBe("className"); + expect(attributeName(spaced)).toBe("set:html"); + expect(attributeName({ name: { type: "JSXNamespacedName" } })).toBe(":"); + expect(attributeValue(spaced)).toEqual(id("x")); + expect(attributeValue({ value: literal("a b") })).toEqual(literal("a b")); + }); + + it("takes only the strings of a list option, and the fallback when there is no list", () => { + expect(stringList({ names: ["a", 1, "b"] }, "names", ["z"])).toEqual(["a", "b"]); + expect(stringList({}, "names", ["z"])).toEqual(["z"]); + expect(stringList(undefined, "names", ["z"])).toEqual(["z"]); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/ast.ts b/packages/eslint-plugin-webtops/src/ast.ts index e1eeb18..6bf2088 100644 --- a/packages/eslint-plugin-webtops/src/ast.ts +++ b/packages/eslint-plugin-webtops/src/ast.ts @@ -51,6 +51,12 @@ export function byKind(table: ReadonlyMap, node: unknown): T | und return type === undefined ? undefined : table.get(type); } +/** The entry of a table for a name that may be missing. */ +export const lookup = ( + table: ReadonlyMap, + name: string | undefined, +): T | undefined => (name === undefined ? undefined : table.get(name)); + /** The text of a string literal or of a template literal with no interpolation; undefined for anything else. */ export const staticText = (node: unknown): string | undefined => byKind(TEXT, node)?.(node); diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts index d973d92..6403a07 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts @@ -1,5 +1,5 @@ import { RuleTester } from "eslint"; -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; import rule from "./complete-tailwind-classes.ts"; RuleTester.describe = describe; @@ -17,6 +17,12 @@ const incomplete = [{ messageId: "incomplete" as const }]; tester.run("complete-tailwind-classes", rule, { valid: [ + { name: "a subtraction is not a join", code: '
' }, + { + name: "an object with whole keys beside a plain one", + code: 'clsx({ "p-2": big, "m-2": small });', + }, + { name: "a template joined to a template", code: "
" }, { name: "a whole class string", code: '
' }, { name: "a lookup of complete strings", code: "
" }, { @@ -55,6 +61,56 @@ tester.run("complete-tailwind-classes", rule, { { name: "a template in a computed member", code: "
" }, ], invalid: [ + { name: "classnames", code: "classnames(`bg-${c}`);", errors: incomplete }, + { name: "classNames", code: "classNames(`bg-${c}`);", errors: incomplete }, + { name: "twMerge", code: "twMerge(`bg-${c}`);", errors: incomplete }, + { name: "twJoin", code: "twJoin(`bg-${c}`);", errors: incomplete }, + { name: "tv", code: "tv(`bg-${c}`);", errors: incomplete }, + { + name: "one offending interpolation among whole ones", + code: "
", + errors: incomplete, + }, + { + name: "one offending part among whole ones in a sum", + code: '
', + errors: incomplete, + }, + { + name: "an offending key beside a plain one", + code: 'clsx({ [`bg-${c}`]: on, "p-2": off });', + errors: incomplete, + }, + { + name: "an offending key after a plain one", + code: 'clsx({ "p-2": off, [`bg-${c}`]: on });', + errors: incomplete, + }, + { + name: "a prefix joined with a sum", + code: '
', + errors: incomplete, + }, + { + name: "a glued suffix after an interpolation", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation glued to a later one only", + code: "
", + errors: incomplete, + }, + { + name: "three interpolations, the last two glued", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation glued to the one before it", + code: "
", + errors: incomplete, + }, { name: "interpolation inside a token", code: "
", @@ -167,3 +223,28 @@ tester.run("complete-tailwind-classes", rule, { { name: "a conditional argument", code: "cn(on ? `bg-${c}` : null);", errors: incomplete }, ], }); + +describe("the rule's own description", () => { + it("states what it judges, its option and its message", () => { + expect(rule.meta).toEqual({ + type: "problem", + docs: { + description: + "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", + }, + schema: [ + { + type: "object", + properties: { + functions: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + incomplete: + "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts index c7405c8..41a97f0 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts @@ -7,6 +7,7 @@ import { children, dottedName, kind, + lookup, propertyName, quasisOf, staticText, @@ -22,23 +23,16 @@ const endsInToken = (text: string | undefined): boolean => text !== undefined && const startsInToken = (text: string | undefined): boolean => text !== undefined && /^\S/u.test(text); -/** Text before or after an interpolation touches it: it holds a character, or an interpolation sits on that side. */ -const glued = (text: string, neighbour: boolean, edge: RegExp): boolean => - text === "" ? neighbour : edge.test(text); - -/** Whether the interpolation at `index` shares a token with static text, or with another interpolation. */ -function touches(quasis: readonly string[], index: number, count: number): boolean { - return ( - glued(quasis[index] ?? "", index > 0, /\S$/u) || - glued(quasis[index + 1] ?? "", index + 1 < count, /^\S/u) - ); -} - function templateBuildsToken(template: unknown): boolean { const quasis = quasisOf(template); const expressions = children(template, "expressions"); + const count = expressions.length; + // Static text ends in a token character before an interpolation, or starts with one after it, + // or two interpolations sit side by side (an empty text between them). return ( - expressions.some((_, index) => touches(quasis, index, expressions.length)) || + quasis.slice(0, count).some(endsInToken) || + quasis.slice(1, count + 1).some(startsInToken) || + quasis.slice(1, count).includes("") || expressions.some(buildsToken) ); } @@ -73,18 +67,19 @@ const METHODS = new Map b function methodBuildsToken(call: unknown): boolean { const callee = child(call, "callee"); - const method = METHODS.get( - kind(callee) === "MemberExpression" ? (propertyName(callee) ?? "") : "", - ); + const method = lookup(METHODS, propertyName(callee)); return method?.(child(callee, "object"), children(call, "arguments")) === true; } -const keyBuildsToken = (property: unknown): boolean => - child(property, "computed") === true && buildsToken(child(property, "key")); +/** A key that is not computed is an identifier or a literal, which cannot build a token. */ +const keyBuildsToken = (property: unknown): boolean => buildsToken(child(property, "key")); const CHECKS = new Map boolean>([ ["TemplateLiteral", templateBuildsToken], - ["BinaryExpression", (node) => partsBuildToken(operands(node))], + [ + "BinaryExpression", + (node) => child(node, "operator") === "+" && partsBuildToken(operands(node)), + ], ["CallExpression", methodBuildsToken], [ "ConditionalExpression", @@ -132,7 +127,7 @@ const rule: Rule.RuleModule = { }, CallExpression(node) { const callee = dottedName(node.callee); - if (helpers.has(callee ?? "") && node.arguments.some(buildsToken)) { + if (callee !== undefined && helpers.has(callee) && node.arguments.some(buildsToken)) { context.report({ node, messageId: "incomplete" }); } }, diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts index f9c8894..d266bb4 100644 --- a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts @@ -1,5 +1,5 @@ import { RuleTester } from "eslint"; -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; import rule from "./no-unsanitized-html.ts"; RuleTester.describe = describe; @@ -20,6 +20,8 @@ const unsanitized = (sink: string, sanitizers = DEFAULT) => [ tester.run("no-unsanitized-html", rule, { valid: [ + { name: "a member that is not a sink, assigned a variable", code: "a.b = html;" }, + { name: "an identifier callee named like a sink", code: "insertAdjacentHTML(a, html);" }, { name: "a static HTML object", code: '
x" }} />', @@ -163,3 +165,28 @@ tester.run("no-unsanitized-html", rule, { }, ], }); + +describe("the rule's own description", () => { + it("states what it judges, its option and its message", () => { + expect(rule.meta).toEqual({ + type: "problem", + docs: { + description: + "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", + }, + schema: [ + { + type: "object", + properties: { + sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + unsanitized: + "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts index ac185fe..600c0fc 100644 --- a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts @@ -7,6 +7,7 @@ import { children, dottedName, kind, + lookup, nameOf, propertyName, staticText, @@ -28,7 +29,13 @@ interface Sink { type Safe = (node: unknown, sanitizers: ReadonlySet) => boolean; const SAFE = new Map([ - ["CallExpression", (node, sanitizers) => sanitizers.has(dottedName(child(node, "callee")) ?? "")], + [ + "CallExpression", + (node, sanitizers) => { + const callee = dottedName(child(node, "callee")); + return callee !== undefined && sanitizers.has(callee); + }, + ], [ "ConditionalExpression", (node, sanitizers) => @@ -40,31 +47,28 @@ const SAFE = new Map([ export const isSafe = (node: unknown, sanitizers: ReadonlySet): boolean => staticText(node) !== undefined || byKind(SAFE, node)?.(node, sanitizers) === true; -/** What `dangerouslySetInnerHTML={{ __html: x }}` sets: `x`; a value that is not an object literal is its own payload. */ -function htmlPayload(value: unknown): unknown { - if (kind(value) !== "ObjectExpression") return value; +/** What `dangerouslySetInnerHTML={{ __html: x }}` sets: `x`. A value that is not an object literal is its own payload, and an object with no `__html` sets nothing. */ +function htmlPayload(value: unknown): { html: unknown } | undefined { + if (kind(value) !== "ObjectExpression") return { html: value }; const entry = children(value, "properties").find( (property) => nameOf(child(property, "key")) === "__html", ); - return entry === undefined ? { type: "Literal", value: "" } : child(entry, "value"); + return entry === undefined ? undefined : { html: child(entry, "value") }; } -const ATTRIBUTE_SINKS = new Map unknown>([ +const ATTRIBUTE_SINKS = new Map { html: unknown } | undefined>([ ["dangerouslySetInnerHTML", htmlPayload], - ["set:html", (value) => value], + ["set:html", (value) => ({ html: value })], ]); function attributeSink(attribute: unknown): Sink | undefined { - const name = attributeName(attribute) ?? ""; - const payload = ATTRIBUTE_SINKS.get(name); - return payload === undefined - ? undefined - : { sink: name, html: payload(attributeValue(attribute)) }; + const name = attributeName(attribute); + const payload = lookup(ATTRIBUTE_SINKS, name)?.(attributeValue(attribute)); + return name === undefined || payload === undefined ? undefined : { sink: name, ...payload }; } function assignedSink(assignment: unknown): Sink | undefined { - const left = child(assignment, "left"); - const sink = kind(left) === "MemberExpression" ? propertyName(left) : undefined; + const sink = propertyName(child(assignment, "left")); return sink !== undefined && ASSIGNED_SINKS.has(sink) ? { sink, html: child(assignment, "right") } : undefined; @@ -72,8 +76,7 @@ function assignedSink(assignment: unknown): Sink | undefined { function insertedSink(call: unknown): Sink | undefined { const callee = child(call, "callee"); - const inserts = - kind(callee) === "MemberExpression" && propertyName(callee) === "insertAdjacentHTML"; + const inserts = propertyName(callee) === "insertAdjacentHTML"; return inserts ? { sink: "insertAdjacentHTML", html: children(call, "arguments")[1] } : undefined; } diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts index dbf58f7..e586d64 100644 --- a/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts @@ -1,5 +1,5 @@ import { RuleTester } from "eslint"; -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; import rule from "./public-env-only.ts"; RuleTester.describe = describe; @@ -15,6 +15,14 @@ const privateName = (name: string) => [ tester.run("public-env-only", rule, { valid: [ + { name: "import.meta.url handed on", code: "send(import.meta.url);" }, + { name: "another member handed on", code: "send(other.value);" }, + { name: "a member of a call result", code: "send(a.env);" }, + { + name: "two prefixes, the second one matching", + code: "const a = process.env.B_KEY;", + options: [{ prefixes: ["A_", "B_"] }], + }, { name: "a public import.meta.env variable", code: "const a = import.meta.env.PUBLIC_API_URL;", @@ -56,6 +64,22 @@ tester.run("public-env-only", rule, { }, ], invalid: [ + { + name: "the env object as the init of a for loop", + code: "for (process.env; ; ) {}", + errors: [{ messageId: "whole" }], + }, + { + name: "the env object as a computed key", + code: "const a = x[process.env];", + errors: [{ messageId: "whole" }], + }, + { + name: "two prefixes are listed in the message", + code: "const a = process.env.KEY;", + options: [{ prefixes: ["A_", "B_"] }], + errors: [{ messageId: "private", data: { name: "KEY", prefixes: "A_, B_" } }], + }, { name: "a private import.meta.env variable", code: "const a = import.meta.env.SECRET_KEY;", @@ -130,3 +154,30 @@ tester.run("public-env-only", rule, { }, ], }); + +describe("the rule's own description", () => { + it("states what it judges, its options and its messages", () => { + const list = { type: "array", items: { type: "string" }, uniqueItems: true }; + expect(rule.meta).toEqual({ + type: "problem", + docs: { description: "Only public env reaches client code (W-37)" }, + schema: [ + { + type: "object", + properties: { prefixes: list, allowed: list }, + additionalProperties: false, + }, + ], + messages: { + private: + "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", + dynamic: + "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", + whole: + "The whole env object reaches client code. Read the public variables you need, by name.", + server: + "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts index 38d1de9..a0fedcd 100644 --- a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts @@ -9,26 +9,17 @@ const BUILT_IN = ["MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE"]; /** `process.env` or `import.meta.env`. */ function isEnvObject(node: unknown): boolean { - if (kind(node) !== "MemberExpression") return false; const meta = kind(child(node, "object")) === "MetaProperty"; return dottedName(node) === "process.env" || (meta && propertyName(node) === "env"); } /** The key of a pattern property: `{ KEY }` and `{ KEY: alias }`; undefined for a computed or rest entry. */ const patternKey = (property: unknown): string | undefined => - kind(property) === "Property" && child(property, "computed") !== true - ? nameOf(child(property, "key")) - : undefined; + child(property, "computed") === true ? undefined : nameOf(child(property, "key")); const isChildOf = (parent: unknown, type: string, field: string, node: unknown): boolean => kind(parent) === type && child(parent, field) === node; -/** How an env object is used: read by member (checked at that member), destructured, or handed over whole. */ -function usage(parent: unknown, node: unknown): "read" | "destructured" | "whole" { - if (isChildOf(parent, "MemberExpression", "object", node)) return "read"; - return isChildOf(parent, "VariableDeclarator", "init", node) ? "destructured" : "whole"; -} - const rule: Rule.RuleModule = { meta: { type: "problem", @@ -72,12 +63,12 @@ const rule: Rule.RuleModule = { }; const inspectEnv = (node: Rule.Node): void => { const parent: unknown = node.parent; - const use = usage(parent, node); - if (use === "whole") context.report({ node, messageId: "whole" }); - if (use === "destructured") { - for (const property of children(child(parent, "id"), "properties")) { + if (isChildOf(parent, "VariableDeclarator", "init", node)) { + children(child(parent, "id"), "properties").forEach((property) => { reportName(node, patternKey(property)); - } + }); + } else if (!isChildOf(parent, "MemberExpression", "object", node)) { + context.report({ node, messageId: "whole" }); } }; return { From 50351f9293eee1052e02ff8cbf9dc5baf7a98b43 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 12:28:45 -0500 Subject: [PATCH 4/8] Kill the last four W-23 survivors The operands of a sum are found by node type, so only a binary expression can split, and only on +. Two cases: a glue after the last interpolation only, and a non-plus operand nested in a sum. Co-Authored-By: Claude Sonnet 5.5 --- .../src/rules/complete-tailwind-classes.test.ts | 9 +++++++++ .../src/rules/complete-tailwind-classes.ts | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts index 6403a07..cb95057 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts @@ -17,6 +17,10 @@ const incomplete = [{ messageId: "incomplete" as const }]; tester.run("complete-tailwind-classes", rule, { valid: [ + { + name: "a non-plus operand inside a sum stays one operand", + code: '
', + }, { name: "a subtraction is not a join", code: '
' }, { name: "an object with whole keys beside a plain one", @@ -61,6 +65,11 @@ tester.run("complete-tailwind-classes", rule, { { name: "a template in a computed member", code: "
" }, ], invalid: [ + { + name: "a glue after the last interpolation only", + code: "
", + errors: incomplete, + }, { name: "classnames", code: "classnames(`bg-${c}`);", errors: incomplete }, { name: "classNames", code: "classNames(`bg-${c}`);", errors: incomplete }, { name: "twMerge", code: "twMerge(`bg-${c}`);", errors: incomplete }, diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts index 41a97f0..a167d23 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts @@ -6,7 +6,6 @@ import { child, children, dottedName, - kind, lookup, propertyName, quasisOf, @@ -46,10 +45,19 @@ function pairGlued(left: unknown, right: unknown): boolean { ); } -/** The operands of a chain of `+`, left to right. */ +const PLUS_CHAIN = new Map readonly unknown[]>([ + [ + "BinaryExpression", + (node) => + child(node, "operator") === "+" + ? [...operands(child(node, "left")), ...operands(child(node, "right"))] + : [node], + ], +]); + +/** The operands of a chain of `+`, left to right; any other node is one operand. */ function operands(node: unknown): readonly unknown[] { - const plus = kind(node) === "BinaryExpression" && child(node, "operator") === "+"; - return plus ? [...operands(child(node, "left")), ...operands(child(node, "right"))] : [node]; + return byKind(PLUS_CHAIN, node)?.(node) ?? [node]; } function partsBuildToken(parts: readonly unknown[]): boolean { From 51a911ac60fbb1f0a40acb4ebaf8f2c8ab584573 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 12:40:13 -0500 Subject: [PATCH 5/8] Test a prefix joined with a non-plus operand Co-Authored-By: Claude Sonnet 5.5 --- .../src/rules/complete-tailwind-classes.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts index cb95057..36e1498 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts @@ -65,6 +65,11 @@ tester.run("complete-tailwind-classes", rule, { { name: "a template in a computed member", code: "
" }, ], invalid: [ + { + name: "a prefix joined with a non-plus operand", + code: '
', + errors: incomplete, + }, { name: "a glue after the last interpolation only", code: "
", From 9aec2411fe0dd60620432153b8e7ea6521413074 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 16:18:51 -0500 Subject: [PATCH 6/8] Enable the plugin's rules in the ESLint preset and ship the plugin inside the package (G6c) The web-tops/eslint preset imports eslint-plugin-webtops from its build, which the package ships in files, so an adopter has one dependency and no separate pin. The build runs on install (prepare), and before the tests through a Vitest global setup. - W-36 no-unsanitized-html is at error in every variant. - W-23 complete-tailwind-classes is at error in the react and astro variants. - W-37 public-env-only is at error in the react and astro variants, on **/*.jsx and **/*.tsx only: frontmatter is server code. W-37's reader cell in laws/W-37.yaml and section 8.2 carries the scope. Co-Authored-By: Claude Sonnet 5.5 --- WEB_TOPS.md | 6 +- .../init/astro-site/eslint.preset.json.golden | 26 +++++++- .../node-service/eslint.preset.json.golden | 6 +- .../init/ts-library/eslint.preset.json.golden | 6 +- .../ui-components/eslint.preset.json.golden | 26 +++++++- .../init/web-app/eslint.preset.json.golden | 26 +++++++- laws/W-37.yaml | 2 +- package.json | 5 +- src/cli/m3-open.test.ts | 1 + src/presets/eslint.js | 19 +++++- src/presets/presets.test.ts | 59 ++++++++++++++++++- vitest.config.ts | 2 + vitest.global-setup.js | 20 +++++++ 13 files changed, 185 insertions(+), 19 deletions(-) create mode 100644 vitest.global-setup.js diff --git a/WEB_TOPS.md b/WEB_TOPS.md index dfa52bb..5bd7f31 100644 --- a/WEB_TOPS.md +++ b/WEB_TOPS.md @@ -295,7 +295,7 @@ A second adopter, an `astro-site` with tests or a `node-service` reopens the que and `laws`, and build output only where the class maps a build-output layer. It requires the judged laws it maps (§8.2, the tick column): the laws no class gates, plus its "Extra laws" row, with W-27 only when the project depends on Astro. `W-06 strict` for `node-service` is a reading of W-06, -which every class maps, as it does W-48 (unused exports, files and dependencies). A law a class maps but that has no reader yet (W-37, W-42 to W-48) is +which every class maps, as it does W-48 (unused exports, files and dependencies). A law a class maps but that has no reader yet (W-42 to W-48) is required when it is judged. Under `hard`, `check` refuses a coverage floor below, and a CRAP cap or `unexplained_survivors_max` above, the class's value in this table (§9, §12). @@ -788,7 +788,7 @@ These tables are generated from `laws/W-NN.yaml` (§8.3). Edit the file, not the | W-34 | No focused or skipped tests committed | R | tl: `@vitest/eslint-plugin` (1.6) `no-focused-tests`, `no-disabled-tests` | ✓ | | W-35 | Every suppression names its rule and says why: `eslint-disable` with a description, `@ts-expect-error` with a description, no `@ts-ignore` or `@ts-nocheck`; unused directives fail | R | tl: `eslint-comments/require-description`, `no-unlimited-disable`; `ban-ts-comment` (`allow-with-description`); `reportUnusedDisableDirectives: "error"`. The suppression census in §6.7 lists every kind that is counted and ratcheted | ✓ | | W-36 | No `set:html`, `dangerouslySetInnerHTML` or `innerHTML` with unsanitized input | R | an | | -| W-37 | Only public env reaches client code (`PUBLIC_` vars, `astro:env` client fields) | R | an | | +| W-37 | Only public env reaches client code (`PUBLIC_` vars, `astro:env` client fields) | R | an: custom ESLint rule, on `**/*.{jsx,tsx}` and `.astro` client script blocks (frontmatter is server code) | | | W-38 | No high or critical advisories in production dependencies | R | tl: dependency audit **[verify `bun audit` output]** | ✓ | | W-39 | No secrets in source or fixtures | R | tl: secrets scanner **[verify]** | | | W-40 | `bun.lock` is committed and installs with `--frozen-lockfile` | R | tl | ✓ | @@ -1131,7 +1131,7 @@ web-tops/ │ ├── report/ # report writing, text and JSON rendering │ └── survivors/ # the survivor key (section 6.4), and the ledger when it lands ├── profiles/ # one profile per launch class: the data init renders from -├── packages/ # eslint-plugin-webtops: the custom ESLint rules behind W-23, W-36 and W-37 +├── packages/ # eslint-plugin-webtops: the custom ESLint rules behind W-23, W-36 and W-37, built into the web-tops package ├── laws/ # one W-NN.yaml per law (§8.3): the source of the §8.2 tables ├── schema/ # web-tops, gate-report, baseline, core (verdicts, modes) and law schemas ├── config/ # drop-in templates, AGENTS.md.tmpl diff --git a/fixtures/init/astro-site/eslint.preset.json.golden b/fixtures/init/astro-site/eslint.preset.json.golden index 7cc32af..67fe371 100644 --- a/fixtures/init/astro-site/eslint.preset.json.golden +++ b/fixtures/init/astro-site/eslint.preset.json.golden @@ -231,7 +231,8 @@ }, { "plugins": [ - "@eslint-community/eslint-comments" + "@eslint-community/eslint-comments", + "webtops" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -266,7 +267,8 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error", + "webtops/no-unsanitized-html": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -611,6 +613,26 @@ } } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/complete-tailwind-classes": "error" + } + }, + { + "files": [ + "**/*.jsx", + "**/*.tsx" + ], + "plugins": [ + "webtops" + ], + "rules": { + "webtops/public-env-only": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/node-service/eslint.preset.json.golden b/fixtures/init/node-service/eslint.preset.json.golden index e844a52..bc5c156 100644 --- a/fixtures/init/node-service/eslint.preset.json.golden +++ b/fixtures/init/node-service/eslint.preset.json.golden @@ -231,7 +231,8 @@ }, { "plugins": [ - "@eslint-community/eslint-comments" + "@eslint-community/eslint-comments", + "webtops" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -266,7 +267,8 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error", + "webtops/no-unsanitized-html": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" diff --git a/fixtures/init/ts-library/eslint.preset.json.golden b/fixtures/init/ts-library/eslint.preset.json.golden index e844a52..bc5c156 100644 --- a/fixtures/init/ts-library/eslint.preset.json.golden +++ b/fixtures/init/ts-library/eslint.preset.json.golden @@ -231,7 +231,8 @@ }, { "plugins": [ - "@eslint-community/eslint-comments" + "@eslint-community/eslint-comments", + "webtops" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -266,7 +267,8 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error", + "webtops/no-unsanitized-html": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" diff --git a/fixtures/init/ui-components/eslint.preset.json.golden b/fixtures/init/ui-components/eslint.preset.json.golden index 8afe878..200489a 100644 --- a/fixtures/init/ui-components/eslint.preset.json.golden +++ b/fixtures/init/ui-components/eslint.preset.json.golden @@ -231,7 +231,8 @@ }, { "plugins": [ - "@eslint-community/eslint-comments" + "@eslint-community/eslint-comments", + "webtops" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -266,7 +267,8 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error", + "webtops/no-unsanitized-html": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -398,6 +400,26 @@ } } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/complete-tailwind-classes": "error" + } + }, + { + "files": [ + "**/*.jsx", + "**/*.tsx" + ], + "plugins": [ + "webtops" + ], + "rules": { + "webtops/public-env-only": "error" + } + }, { "files": [ "**/*.jsx", diff --git a/fixtures/init/web-app/eslint.preset.json.golden b/fixtures/init/web-app/eslint.preset.json.golden index 8afe878..200489a 100644 --- a/fixtures/init/web-app/eslint.preset.json.golden +++ b/fixtures/init/web-app/eslint.preset.json.golden @@ -231,7 +231,8 @@ }, { "plugins": [ - "@eslint-community/eslint-comments" + "@eslint-community/eslint-comments", + "webtops" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -266,7 +267,8 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error", + "webtops/no-unsanitized-html": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -398,6 +400,26 @@ } } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/complete-tailwind-classes": "error" + } + }, + { + "files": [ + "**/*.jsx", + "**/*.tsx" + ], + "plugins": [ + "webtops" + ], + "rules": { + "webtops/public-env-only": "error" + } + }, { "files": [ "**/*.jsx", diff --git a/laws/W-37.yaml b/laws/W-37.yaml index ed25a44..373fc8e 100644 --- a/laws/W-37.yaml +++ b/laws/W-37.yaml @@ -6,7 +6,7 @@ severity: R classes: [ui-components, astro-site, web-app] reader: kinds: [an] - text: "an" + text: "an: custom ESLint rule, on `**/*.{jsx,tsx}` and `.astro` client script blocks (frontmatter is server code)" rules: - { tool: eslint, name: "webtops/public-env-only" } judged: m3 diff --git a/package.json b/package.json index 71dea74..a23aefc 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,9 @@ "schema", "laws", "config", - "profiles" + "profiles", + "packages/eslint-plugin-webtops/package.json", + "packages/eslint-plugin-webtops/dist" ], "engines": { "bun": ">=1.4.0", @@ -50,6 +52,7 @@ }, "packageManager": "bun@1.4.4", "scripts": { + "prepare": "tsc -p packages/eslint-plugin-webtops/tsconfig.build.json", "typecheck": "tsc -b --noEmit", "lint": "eslint .", "test": "vitest run --coverage --sequence.shuffle", diff --git a/src/cli/m3-open.test.ts b/src/cli/m3-open.test.ts index 1eb3ca0..a42e94e 100644 --- a/src/cli/m3-open.test.ts +++ b/src/cli/m3-open.test.ts @@ -262,6 +262,7 @@ describe("M3 G0b: the kit's Vitest config, exactly", () => { expect(vitestConfig).toEqual({ test: { testTimeout: 30_000, + globalSetup: ["./vitest.global-setup.js"], include: ["src/**/*.test.ts", "packages/**/*.test.ts"], exclude: [ ...configDefaults.exclude, diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 69d494f..f49ac4a 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -3,6 +3,7 @@ import js from "@eslint/js"; import vitest from "@vitest/eslint-plugin"; import { defineConfig } from "eslint/config"; import tseslint from "typescript-eslint"; +import webtops from "../../packages/eslint-plugin-webtops/dist/index.js"; // The ESLint preset behind `web-tops/eslint` (WEB_TOPS.md section 8.2). Every rule below is the reader // behind a judged law and stays at "error"; weaken one only through a protocol-change PR. A project's @@ -50,10 +51,24 @@ const LAW_RULES = { ], "@eslint-community/eslint-comments/require-description": "error", "@eslint-community/eslint-comments/no-unlimited-disable": "error", + // W-36 no unsanitized HTML in `set:html`, `dangerouslySetInnerHTML`, `innerHTML` and the like + "webtops/no-unsanitized-html": "error", }; const TSX = ["**/*.jsx", "**/*.tsx"]; +/** + * The rules of `eslint-plugin-webtops` that only a project with a UI maps. The plugin ships inside + * this package (its build is in `files`), so an adopter has one dependency and no separate pin. + */ +const WEBTOPS_UI = [ + // W-23 Tailwind class names are complete strings, in every file + { plugins: { webtops }, rules: { "webtops/complete-tailwind-classes": "error" } }, + // W-37 only public env reaches client code: the scope is the client modules, not .astro + // frontmatter, which is server code (an Astro client script block is read in the Astro rules) + { files: TSX, plugins: { webtops }, rules: { "webtops/public-env-only": "error" } }, +]; + const BASE_PACKAGES = [ "@eslint-community/eslint-plugin-eslint-comments", "@eslint/js", @@ -76,6 +91,7 @@ async function reactConfigs() { return [ // W-22 semantic elements, alt text, labels { files: TSX, ...a11y.configs.strict }, + ...WEBTOPS_UI, { // W-47 rules of hooks files: TSX, @@ -98,6 +114,7 @@ async function astroConfigs() { ...astro.configs["flat/recommended"], ...astro.configs["flat/jsx-a11y-strict"], { files: TSX, ...a11y.configs.strict }, + ...WEBTOPS_UI, ]; } @@ -130,7 +147,7 @@ export async function eslintPreset({ variant, tsconfigRootDir }) { languageOptions: { parserOptions: { projectService: true, tsconfigRootDir } }, // W-35: an unused suppression fails. linterOptions: { reportUnusedDisableDirectives: "error" }, - plugins: { "@eslint-community/eslint-comments": eslintComments }, + plugins: { "@eslint-community/eslint-comments": eslintComments, webtops }, rules: LAW_RULES, }, { diff --git a/src/presets/presets.test.ts b/src/presets/presets.test.ts index 6149849..acbda2d 100644 --- a/src/presets/presets.test.ts +++ b/src/presets/presets.test.ts @@ -156,6 +156,28 @@ describe("G2a: each preset imports from a scratch project", () => { REAL_TOOL_TIMEOUT, ); + it( + "the plugin's rules are live through web-tops/eslint: client code is flagged, server code is not", + () => { + const dir = scratchProject({ + "eslint.config.js": + 'import { eslintPreset } from "web-tops/eslint";\nexport default await eslintPreset({\n variant: "react",\n tsconfigRootDir: import.meta.dirname,\n});\n', + "tsconfig.json": + '{ "extends": "web-tops/tsconfig/strict.json", "compilerOptions": { "noEmit": true, "jsx": "preserve" } }\n', + "client.tsx": + "export const A = (p: { c: string; h: string }) => (\n
{process.env.SECRET}
\n);\n", + "server.ts": "export const s: unknown = process.env.SECRET;\n", + }); + const client = run(bin("eslint"), ["client.tsx"], dir); + for (const rule of ["complete-tailwind-classes", "no-unsanitized-html", "public-env-only"]) { + expect(client.output, rule).toContain(`webtops/${rule}`); + } + const server = run(bin("eslint"), ["server.ts"], dir); + expect(server.output).not.toContain("webtops/public-env-only"); + }, + 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); @@ -168,6 +190,14 @@ describe("G2a: each preset imports from a scratch project", () => { expect(text, target).toContain(`"${target}"`); } expect(text).not.toMatch(/src\/presets\/[\w/]+\.ts"/); + // The preset imports the plugin's build, so the build ships beside it. + const files: unknown = Reflect.get(exported ?? {}, "files"); + expect(files).toEqual( + expect.arrayContaining([ + "packages/eslint-plugin-webtops/package.json", + "packages/eslint-plugin-webtops/dist", + ]), + ); }); }); @@ -182,7 +212,7 @@ describe("the ESLint preset", () => { }); it("lists every package its source imports, and no other", () => { - const imported = [...PRESET_SOURCE.matchAll(/(?:from|load\()\s*"([^"]+)"/g)].map((match) => + const imported = [...PRESET_SOURCE.matchAll(/(?:from|load\()\s*"([^".][^"]*)"/g)].map((match) => (match[1] ?? "").replace(/^eslint\/config$/, "eslint"), ); const listed = new Set(Object.values(PACKAGES).flat()); @@ -202,9 +232,10 @@ describe("the ESLint preset", () => { it("sets the kit's own law rules, and no more, to error in every variant", async () => { const kit = writtenRules(KIT_CONFIG); expect(kit.size).toBeGreaterThanOrEqual(15); - // The hooks rules belong to the react variant alone; the rest is the kit's own set. + // The hooks rules belong to the react variant, and the `webtops` ones to the plugin the preset + // ships; the rest is the kit's own set. const written = [...writtenRules(PRESET_SOURCE)].filter( - (rule) => !rule.startsWith("react-hooks/"), + (rule) => !rule.startsWith("react-hooks/") && !rule.startsWith("webtops/"), ); expect(new Set(written)).toEqual(kit); for (const variant of VARIANTS) { @@ -213,6 +244,28 @@ describe("the ESLint preset", () => { } }); + it.each([ + ["base", ["webtops/no-unsanitized-html"], ["webtops/complete-tailwind-classes"]], + ["react", ["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) => { + 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); + expect(pluginNames(config)).toContain("webtops"); + }); + + it("scopes public-env-only (W-37) to the client modules, in the react and astro variants 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("astro")).toEqual([["**/*.jsx", "**/*.tsx"]]); + }); + it.each(VARIANTS)( "%s reports unused suppressions and ignores the usual output", async (variant) => { diff --git a/vitest.config.ts b/vitest.config.ts index 5a820b7..fd9a821 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,6 +4,8 @@ export default defineConfig({ test: { // Real git, bun and ESLint processes run in the gate, src/cli and src/diff tests; the macOS runner is slow. testTimeout: 30_000, + // Builds eslint-plugin-webtops, which the web-tops/eslint preset imports from its build. + globalSetup: ["./vitest.global-setup.js"], include: ["src/**/*.test.ts", "packages/**/*.test.ts"], // Reserved: probes and the deliberate cheats are data, never collected as this kit's tests. exclude: [ diff --git a/vitest.global-setup.js b/vitest.global-setup.js new file mode 100644 index 0000000..958e863 --- /dev/null +++ b/vitest.global-setup.js @@ -0,0 +1,20 @@ +import { spawnSync } from "node:child_process"; +import { join } from "node:path"; +import process from "node:process"; + +// Builds eslint-plugin-webtops before the tests run. The `web-tops/eslint` preset imports the plugin's +// build, and the build is not tracked, so every test that loads the preset needs it on disk. The +// build skips type checks: the gate's own `tsc` run checks the plugin's types, and a type check +// would fail on the instrumented sources inside the mutation sandbox. +export default function setup() { + const root = import.meta.dirname; + const tsc = join(root, "node_modules", "typescript", "bin", "tsc"); + const project = join(root, "packages", "eslint-plugin-webtops", "tsconfig.build.json"); + const build = spawnSync(process.execPath, [tsc, "-p", project, "--noCheck"], { + cwd: root, + encoding: "utf8", + }); + if (build.status !== 0) { + throw new Error(`building eslint-plugin-webtops failed:\n${build.stdout}${build.stderr}`); + } +} From 7bd9b66fb3540f3ac705c1349afc793573621805 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 17:24:27 -0500 Subject: [PATCH 7/8] Give web-app its own ESLint variant so ui-components does not get W-23 (G6c) A preset enables exactly the plugin rules the laws of its class map. W-23 (complete-tailwind-classes) maps to astro-site and web-app only, so the react variant, which ui-components used, loses it, and a new react-app variant, which web-app now names, keeps it. W-36 and W-37 are unchanged. A new test reads every launch class's variant, the rules its preset sets to error and the rules of the laws the class maps in the catalog, and requires the webtops/* sets to be equal. A law that names a plugin rule a later step builds (the Astro rules) is left out until the plugin has it; the step that adds the rule must then enable it. Co-Authored-By: Claude Sonnet 5.5 --- WEB_TOPS.md | 2 +- .../init/astro-site/eslint.preset.json.golden | 12 ++-- .../ui-components/eslint.preset.json.golden | 8 --- fixtures/init/web-app/eslint.config.js.golden | 2 +- .../init/web-app/eslint.preset.json.golden | 12 ++-- profiles/web-app.yaml | 2 +- src/init/init.test.ts | 4 +- src/init/profile.ts | 4 +- src/init/render.ts | 2 +- src/presets/class-rules.test.ts | 67 +++++++++++++++++++ src/presets/eslint.d.ts | 2 +- src/presets/eslint.js | 44 +++++++----- src/presets/presets.test.ts | 15 +++-- 13 files changed, 126 insertions(+), 50 deletions(-) create mode 100644 src/presets/class-rules.test.ts diff --git a/WEB_TOPS.md b/WEB_TOPS.md index 5bd7f31..fc9abdb 100644 --- a/WEB_TOPS.md +++ b/WEB_TOPS.md @@ -230,7 +230,7 @@ bunx webtops gate - `web-tops.yaml`, `web-tops.lock`; - thin importers, with the rules in the kit's presets and none in the project: `tsconfig.strict.json` (extends `web-tops/tsconfig/strict.json`), `eslint.config.js` (calls `web-tops/eslint` with the - class's variant: base, react or astro), `stylelint.config.js` (re-exports `web-tops/stylelint`) and + class's variant: base, react, react-app or astro), `stylelint.config.js` (re-exports `web-tops/stylelint`) and `.dependency-cruiser.cjs` (requires `web-tops/depcruise`); and `stryker.config.json` once the mutation layer ships; - the class CI workflow, with the jobs whose commands exist (§11); diff --git a/fixtures/init/astro-site/eslint.preset.json.golden b/fixtures/init/astro-site/eslint.preset.json.golden index 67fe371..ce823b8 100644 --- a/fixtures/init/astro-site/eslint.preset.json.golden +++ b/fixtures/init/astro-site/eslint.preset.json.golden @@ -614,23 +614,23 @@ } }, { + "files": [ + "**/*.jsx", + "**/*.tsx" + ], "plugins": [ "webtops" ], "rules": { - "webtops/complete-tailwind-classes": "error" + "webtops/public-env-only": "error" } }, { - "files": [ - "**/*.jsx", - "**/*.tsx" - ], "plugins": [ "webtops" ], "rules": { - "webtops/public-env-only": "error" + "webtops/complete-tailwind-classes": "error" } }, { diff --git a/fixtures/init/ui-components/eslint.preset.json.golden b/fixtures/init/ui-components/eslint.preset.json.golden index 200489a..5d80b02 100644 --- a/fixtures/init/ui-components/eslint.preset.json.golden +++ b/fixtures/init/ui-components/eslint.preset.json.golden @@ -400,14 +400,6 @@ } } }, - { - "plugins": [ - "webtops" - ], - "rules": { - "webtops/complete-tailwind-classes": "error" - } - }, { "files": [ "**/*.jsx", diff --git a/fixtures/init/web-app/eslint.config.js.golden b/fixtures/init/web-app/eslint.config.js.golden index 1f090c8..c275ab3 100644 --- a/fixtures/init/web-app/eslint.config.js.golden +++ b/fixtures/init/web-app/eslint.config.js.golden @@ -3,6 +3,6 @@ import { eslintPreset } from "web-tops/eslint"; export default await eslintPreset({ - variant: "react", + variant: "react-app", tsconfigRootDir: import.meta.dirname, }); diff --git a/fixtures/init/web-app/eslint.preset.json.golden b/fixtures/init/web-app/eslint.preset.json.golden index 200489a..0f26bb3 100644 --- a/fixtures/init/web-app/eslint.preset.json.golden +++ b/fixtures/init/web-app/eslint.preset.json.golden @@ -401,23 +401,23 @@ } }, { + "files": [ + "**/*.jsx", + "**/*.tsx" + ], "plugins": [ "webtops" ], "rules": { - "webtops/complete-tailwind-classes": "error" + "webtops/public-env-only": "error" } }, { - "files": [ - "**/*.jsx", - "**/*.tsx" - ], "plugins": [ "webtops" ], "rules": { - "webtops/public-env-only": "error" + "webtops/complete-tailwind-classes": "error" } }, { diff --git a/profiles/web-app.yaml b/profiles/web-app.yaml index 1891c44..cfdb93b 100644 --- a/profiles/web-app.yaml +++ b/profiles/web-app.yaml @@ -6,7 +6,7 @@ crap_cap: 6 survivors_max: 2 js_budget: "170 KB per route" playwright: true -eslint: react +eslint: react-app tools: - "@eslint-community/eslint-plugin-eslint-comments" - "@eslint/js" diff --git a/src/init/init.test.ts b/src/init/init.test.ts index d2ca4c3..3838a1d 100644 --- a/src/init/init.test.ts +++ b/src/init/init.test.ts @@ -16,11 +16,11 @@ const CLASSES = ["ts-library", "ui-components", "astro-site", "web-app", "node-s type Class = (typeof CLASSES)[number]; // From WEB_TOPS.md section 4: which plugin set each class adds to the base law rules. -const VARIANT: Record = { +const VARIANT: Record = { "ts-library": "base", "node-service": "base", "ui-components": "react", - "web-app": "react", + "web-app": "react-app", "astro-site": "astro", }; diff --git a/src/init/profile.ts b/src/init/profile.ts index 084c807..b475293 100644 --- a/src/init/profile.ts +++ b/src/init/profile.ts @@ -9,7 +9,7 @@ import { PROFILES, profileFor } from "../config/profiles.ts"; export const LAUNCH_CLASSES: readonly string[] = PROFILES.map((profile) => profile.class); /** Which plugin set `eslint.config.js` adds on top of the base law rules. */ -export type EslintVariant = "base" | "react" | "astro"; +export type EslintVariant = "base" | "react" | "react-app" | "astro"; /** The drop-in data for one class (the floors and mapped layers live in the class table; see the agreement test): floors, the tools its enabled layers run, and what M1 leaves off. */ export interface DropIn { @@ -46,7 +46,7 @@ const schema = { survivors_max: { type: "integer", minimum: 0 }, js_budget: { type: "string", minLength: 1 }, playwright: { type: "boolean" }, - eslint: { enum: ["base", "react", "astro"] }, + eslint: { enum: ["base", "react", "react-app", "astro"] }, tools: { type: "array", items: { type: "string", minLength: 1 }, uniqueItems: true }, disabled: { type: "object", additionalProperties: { type: "string", minLength: 1 } }, }, diff --git a/src/init/render.ts b/src/init/render.ts index 1241da8..4071b74 100644 --- a/src/init/render.ts +++ b/src/init/render.ts @@ -135,7 +135,7 @@ export function agentsSection(profile: DropIn, subject: Subject, astroCheck: Ast "rendered", `- JS per page or route ≤ \`${profile.js_budget}\` (brotli, from the build output), where the class ships pages`, ), - HOOKS_LINE: profile.eslint === "react" ? HOOKS_LINE : "", + HOOKS_LINE: profile.eslint.startsWith("react") ? HOOKS_LINE : "", RENDERED_SECTION: renderedSection(profile), VERIFIES: verifies(profile, astroCheck), LAWS_NOTE: enabled(profile, "laws") ? "" : LAWS_NOTE, diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts new file mode 100644 index 0000000..0b9ba11 --- /dev/null +++ b/src/presets/class-rules.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; +import { loadProfile } from "../init/profile.ts"; +import { CATALOG_DIR, LAW_CLASSES, loadCatalog, select } from "../laws/catalog/index.ts"; +import type { Law, LawClass } from "../laws/catalog/index.ts"; +import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; +import { eslintPreset } from "./eslint.js"; + +const PREFIX = "webtops/"; + +/** The laws of the catalog, as the catalog loads them. */ +function lawsOf(): readonly Law[] { + const catalog = loadCatalog(CATALOG_DIR); + if (!catalog.ok) throw new Error(JSON.stringify(catalog.problems)); + return catalog.laws; +} + +/** The plugin's rules, named as a config names them. */ +const IMPLEMENTED = new Set(Object.keys(plugin.rules ?? {}).map((name) => `${PREFIX}${name}`)); + +/** + * The `webtops/*` rules a class's laws map to the ESLint reader that the plugin has built. A law + * can name a rule that a later step builds (the Astro rules of W-28, W-30 and W-31); the step that + * adds the rule to the plugin must also enable it, or this test fails. + */ +function mappedRules(laws: readonly Law[], cls: LawClass): string[] { + return select(laws, { cls, required: false }) + .flatMap((law) => law.rules) + .filter((rule) => rule.tool === "eslint" && IMPLEMENTED.has(rule.name)) + .map((rule) => rule.name) + .sort(); +} + +/** The `webtops/*` rules the class's preset sets to error. */ +async function enabledRules(cls: LawClass): Promise { + const loaded = loadProfile(cls); + if (!loaded.ok) throw new Error(loaded.error); + const config = await eslintPreset({ variant: loaded.profile.eslint, tsconfigRootDir: "

" }); + const names = config.flatMap((entry) => + Object.entries(entry.rules ?? {}) + .filter(([name, setting]) => name.startsWith(PREFIX) && setting === "error") + .map(([name]) => name), + ); + return [...new Set(names)].sort(); +} + +describe("R98: a class's preset enables exactly the plugin rules its laws map", () => { + const laws = lawsOf(); + + it.each(LAW_CLASSES)( + "%s: the enabled webtops/* rules are the mapped laws' rules", + async (cls) => { + const mapped = mappedRules(laws, cls); + expect(mapped.length).toBeGreaterThan(0); + expect(await enabledRules(cls)).toEqual(mapped); + }, + ); + + it("holds the split the laws make: the Tailwind rule only for astro-site and web-app", async () => { + const withTailwind: LawClass[] = []; + for (const cls of LAW_CLASSES) { + if ((await enabledRules(cls)).includes("webtops/complete-tailwind-classes")) { + withTailwind.push(cls); + } + } + expect(withTailwind).toEqual(["astro-site", "web-app"]); + }); +}); diff --git a/src/presets/eslint.d.ts b/src/presets/eslint.d.ts index 8c0f8ee..2040433 100644 --- a/src/presets/eslint.d.ts +++ b/src/presets/eslint.d.ts @@ -1,7 +1,7 @@ import type { Linter } from "eslint"; /** The plugin set a class adds on top of the base law rules. */ -export type EslintVariant = "base" | "react" | "astro"; +export type EslintVariant = "base" | "react" | "react-app" | "astro"; export interface EslintPresetOptions { readonly variant: EslintVariant; diff --git a/src/presets/eslint.js b/src/presets/eslint.js index f49ac4a..10e47d4 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -57,18 +57,22 @@ const LAW_RULES = { const TSX = ["**/*.jsx", "**/*.tsx"]; -/** - * The rules of `eslint-plugin-webtops` that only a project with a UI maps. The plugin ships inside - * this package (its build is in `files`), so an adopter has one dependency and no separate pin. - */ -const WEBTOPS_UI = [ - // W-23 Tailwind class names are complete strings, in every file - { plugins: { webtops }, rules: { "webtops/complete-tailwind-classes": "error" } }, - // W-37 only public env reaches client code: the scope is the client modules, not .astro - // frontmatter, which is server code (an Astro client script block is read in the Astro rules) +// The rules of `eslint-plugin-webtops` beyond W-36. The plugin ships inside this package (its build +// 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. + +/** W-37 only public env reaches client code, for the classes with a UI (ui-components, astro-site, web-app). */ +const WEBTOPS_CLIENT = [ + // The scope is the client modules, not .astro frontmatter, which is server code (an Astro client + // script block is read in the Astro rules) { files: TSX, plugins: { webtops }, rules: { "webtops/public-env-only": "error" } }, ]; +/** W-23 Tailwind class names are complete strings, in every file, for astro-site and web-app. */ +const WEBTOPS_TAILWIND = [ + { plugins: { webtops }, rules: { "webtops/complete-tailwind-classes": "error" } }, +]; + const BASE_PACKAGES = [ "@eslint-community/eslint-plugin-eslint-comments", "@eslint/js", @@ -83,7 +87,8 @@ async function load(name) { return loaded.default; } -async function reactConfigs() { +/** The React plugin set; the web-app variant adds the Tailwind rule on top of the library's. */ +const reactConfigs = (extra) => async () => { const [a11y, hooks] = await Promise.all([ load("eslint-plugin-jsx-a11y-x"), load("eslint-plugin-react-hooks"), @@ -91,7 +96,7 @@ async function reactConfigs() { return [ // W-22 semantic elements, alt text, labels { files: TSX, ...a11y.configs.strict }, - ...WEBTOPS_UI, + ...extra, { // W-47 rules of hooks files: TSX, @@ -102,7 +107,7 @@ async function reactConfigs() { }, }, ]; -} +}; async function astroConfigs() { const [astro, a11y] = await Promise.all([ @@ -114,19 +119,28 @@ async function astroConfigs() { ...astro.configs["flat/recommended"], ...astro.configs["flat/jsx-a11y-strict"], { files: TSX, ...a11y.configs.strict }, - ...WEBTOPS_UI, + ...WEBTOPS_CLIENT, + ...WEBTOPS_TAILWIND, ]; } -const PLUGIN_CONFIGS = { base: async () => [], react: reactConfigs, astro: astroConfigs }; +const PLUGIN_CONFIGS = { + base: async () => [], + react: reactConfigs(WEBTOPS_CLIENT), + "react-app": reactConfigs([...WEBTOPS_CLIENT, ...WEBTOPS_TAILWIND]), + astro: astroConfigs, +}; /** The variants a class can name: the plugin set added on top of the base law rules. */ export const VARIANTS = Object.keys(PLUGIN_CONFIGS); +const REACT_PACKAGES = [...BASE_PACKAGES, "eslint-plugin-jsx-a11y-x", "eslint-plugin-react-hooks"]; + /** Every package a variant imports, so a class's tool list can be checked against it. */ export const PACKAGES = { base: BASE_PACKAGES, - react: [...BASE_PACKAGES, "eslint-plugin-jsx-a11y-x", "eslint-plugin-react-hooks"], + react: REACT_PACKAGES, + "react-app": REACT_PACKAGES, astro: [...BASE_PACKAGES, "eslint-plugin-astro", "eslint-plugin-jsx-a11y-x"], }; diff --git a/src/presets/presets.test.ts b/src/presets/presets.test.ts index acbda2d..2dacfdb 100644 --- a/src/presets/presets.test.ts +++ b/src/presets/presets.test.ts @@ -95,7 +95,7 @@ describe("G2a: each preset imports from a scratch project", () => { expect(result.status, result.output).toBe(0); const seen: unknown = JSON.parse(result.output); expect(seen).toEqual({ - variants: ["base", "react", "astro"], + variants: ["base", "react", "react-app", "astro"], configs: 9, stylelint: 9, depcruise: ["no-circular", "no-unresolvable"], @@ -161,7 +161,7 @@ describe("G2a: each preset imports from a scratch project", () => { () => { const dir = scratchProject({ "eslint.config.js": - 'import { eslintPreset } from "web-tops/eslint";\nexport default await eslintPreset({\n variant: "react",\n tsconfigRootDir: import.meta.dirname,\n});\n', + 'import { eslintPreset } from "web-tops/eslint";\nexport default await eslintPreset({\n variant: "react-app",\n tsconfigRootDir: import.meta.dirname,\n});\n', "tsconfig.json": '{ "extends": "web-tops/tsconfig/strict.json", "compilerOptions": { "noEmit": true, "jsx": "preserve" } }\n', "client.tsx": @@ -203,11 +203,11 @@ describe("G2a: each preset imports from a scratch project", () => { describe("the ESLint preset", () => { it("names its variants, and refuses one it does not have", async () => { - expect(VARIANTS).toEqual(["base", "react", "astro"]); + expect(VARIANTS).toEqual(["base", "react", "react-app", "astro"]); // @ts-expect-error: a variant the preset does not have const refused = eslintPreset({ variant: "vue", tsconfigRootDir: "." }); await expect(refused).rejects.toThrow( - 'web-tops/eslint has no variant "vue"; use base, react, astro', + 'web-tops/eslint has no variant "vue"; use base, react, react-app, astro', ); }); @@ -222,6 +222,7 @@ describe("the ESLint preset", () => { it.each([ ["base", ["@typescript-eslint", "vitest"], ["react-hooks", "jsx-a11y-x", "astro"]], ["react", ["react-hooks", "jsx-a11y-x"], ["astro"]], + ["react-app", ["react-hooks", "jsx-a11y-x"], ["astro"]], ["astro", ["astro", "jsx-a11y-x"], ["react-hooks"]], ] as const)("%s registers its plugins and no other class's", async (variant, has, hasNot) => { const plugins = pluginNames(await presetOf(variant)); @@ -246,7 +247,8 @@ describe("the ESLint preset", () => { it.each([ ["base", ["webtops/no-unsanitized-html"], ["webtops/complete-tailwind-classes"]], - ["react", ["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) => { const config = await presetOf(variant); @@ -256,13 +258,14 @@ describe("the ESLint preset", () => { expect(pluginNames(config)).toContain("webtops"); }); - it("scopes public-env-only (W-37) to the client modules, in the react and astro variants only", async () => { + 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"]]); }); From 41203747ff95709f37d3086688f9fd0bdc00db1a Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Thu, 19 Nov 2026 19:21:45 -0500 Subject: [PATCH 8/8] Decide the plugin's rules by class, and cut the mutation cost of G6 The mutation legs ran past their budget. The causes, and what changes: - Module-level data (tables, lists, rule metadata) became functions and getters, so a mutant in it no longer reruns the whole suite as a static mutant. - The test run no longer builds the plugin: the preset reads the plugin's source in a checkout and its build once published. vitest.config.ts, vitest.global-setup.js and src/cli/m3-open.test.ts are back as they were. - The web-app variant split is undone, so src/init (profile.ts, render.ts and their tests) and profiles/web-app.yaml are back as they were. The preset decides the plugin's rules by class instead: `class` is an option, and the project's web-tops.yaml says which when it is left out, so the importer init writes is unchanged. W-36 applies to every class, W-37 to the three with a UI and W-23 to astro-site and web-app. - class-rules.test.ts reads the profile and law files itself and requires the enabled webtops/* rules to equal the rules of the laws each class maps. Co-Authored-By: Claude Sonnet 5.5 --- WEB_TOPS.md | 2 +- .../init/astro-site/eslint.preset.json.golden | 20 +-- .../node-service/eslint.preset.json.golden | 14 +- .../init/ts-library/eslint.preset.json.golden | 14 +- .../ui-components/eslint.preset.json.golden | 20 +-- fixtures/init/web-app/eslint.config.js.golden | 2 +- .../init/web-app/eslint.preset.json.golden | 26 +--- packages/eslint-plugin-webtops/src/ast.ts | 14 +- packages/eslint-plugin-webtops/src/index.ts | 14 +- .../src/rules/complete-tailwind-classes.ts | 127 ++++++++++-------- .../src/rules/no-unsanitized-html.ts | 89 ++++++------ .../src/rules/public-env-only.ts | 52 +++---- profiles/web-app.yaml | 2 +- src/cli/m3-open.test.ts | 1 - src/init/init.test.ts | 4 +- src/init/profile.ts | 4 +- src/init/render.ts | 2 +- src/presets/class-rules.test.ts | 84 +++++++----- src/presets/eslint.d.ts | 4 +- src/presets/eslint.js | 107 ++++++++++----- src/presets/presets.test.ts | 80 ++++++----- vitest.config.ts | 2 - vitest.global-setup.js | 20 --- 23 files changed, 384 insertions(+), 320 deletions(-) delete mode 100644 vitest.global-setup.js diff --git a/WEB_TOPS.md b/WEB_TOPS.md index fc9abdb..5bd7f31 100644 --- a/WEB_TOPS.md +++ b/WEB_TOPS.md @@ -230,7 +230,7 @@ bunx webtops gate - `web-tops.yaml`, `web-tops.lock`; - thin importers, with the rules in the kit's presets and none in the project: `tsconfig.strict.json` (extends `web-tops/tsconfig/strict.json`), `eslint.config.js` (calls `web-tops/eslint` with the - class's variant: base, react, react-app or astro), `stylelint.config.js` (re-exports `web-tops/stylelint`) and + class's variant: base, react or astro), `stylelint.config.js` (re-exports `web-tops/stylelint`) and `.dependency-cruiser.cjs` (requires `web-tops/depcruise`); and `stryker.config.json` once the mutation layer ships; - the class CI workflow, with the jobs whose commands exist (§11); diff --git a/fixtures/init/astro-site/eslint.preset.json.golden b/fixtures/init/astro-site/eslint.preset.json.golden index ce823b8..0314027 100644 --- a/fixtures/init/astro-site/eslint.preset.json.golden +++ b/fixtures/init/astro-site/eslint.preset.json.golden @@ -231,8 +231,7 @@ }, { "plugins": [ - "@eslint-community/eslint-comments", - "webtops" + "@eslint-community/eslint-comments" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -267,8 +266,7 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error", - "webtops/no-unsanitized-html": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -613,24 +611,12 @@ } } }, - { - "files": [ - "**/*.jsx", - "**/*.tsx" - ], - "plugins": [ - "webtops" - ], - "rules": { - "webtops/public-env-only": "error" - } - }, { "plugins": [ "webtops" ], "rules": { - "webtops/complete-tailwind-classes": "error" + "webtops/no-unsanitized-html": "error" } }, { diff --git a/fixtures/init/node-service/eslint.preset.json.golden b/fixtures/init/node-service/eslint.preset.json.golden index bc5c156..c4d320b 100644 --- a/fixtures/init/node-service/eslint.preset.json.golden +++ b/fixtures/init/node-service/eslint.preset.json.golden @@ -231,8 +231,7 @@ }, { "plugins": [ - "@eslint-community/eslint-comments", - "webtops" + "@eslint-community/eslint-comments" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -267,8 +266,7 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error", - "webtops/no-unsanitized-html": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -291,6 +289,14 @@ "vitest/no-disabled-tests": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/ts-library/eslint.preset.json.golden b/fixtures/init/ts-library/eslint.preset.json.golden index bc5c156..c4d320b 100644 --- a/fixtures/init/ts-library/eslint.preset.json.golden +++ b/fixtures/init/ts-library/eslint.preset.json.golden @@ -231,8 +231,7 @@ }, { "plugins": [ - "@eslint-community/eslint-comments", - "webtops" + "@eslint-community/eslint-comments" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -267,8 +266,7 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error", - "webtops/no-unsanitized-html": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -291,6 +289,14 @@ "vitest/no-disabled-tests": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/ui-components/eslint.preset.json.golden b/fixtures/init/ui-components/eslint.preset.json.golden index 5d80b02..4e431bb 100644 --- a/fixtures/init/ui-components/eslint.preset.json.golden +++ b/fixtures/init/ui-components/eslint.preset.json.golden @@ -231,8 +231,7 @@ }, { "plugins": [ - "@eslint-community/eslint-comments", - "webtops" + "@eslint-community/eslint-comments" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -267,8 +266,7 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error", - "webtops/no-unsanitized-html": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -406,23 +404,19 @@ "**/*.tsx" ], "plugins": [ - "webtops" + "react-hooks" ], "rules": { - "webtops/public-env-only": "error" + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "error" } }, { - "files": [ - "**/*.jsx", - "**/*.tsx" - ], "plugins": [ - "react-hooks" + "webtops" ], "rules": { - "react-hooks/rules-of-hooks": "error", - "react-hooks/exhaustive-deps": "error" + "webtops/no-unsanitized-html": "error" } }, { diff --git a/fixtures/init/web-app/eslint.config.js.golden b/fixtures/init/web-app/eslint.config.js.golden index c275ab3..1f090c8 100644 --- a/fixtures/init/web-app/eslint.config.js.golden +++ b/fixtures/init/web-app/eslint.config.js.golden @@ -3,6 +3,6 @@ import { eslintPreset } from "web-tops/eslint"; export default await eslintPreset({ - variant: "react-app", + variant: "react", tsconfigRootDir: import.meta.dirname, }); diff --git a/fixtures/init/web-app/eslint.preset.json.golden b/fixtures/init/web-app/eslint.preset.json.golden index 0f26bb3..4e431bb 100644 --- a/fixtures/init/web-app/eslint.preset.json.golden +++ b/fixtures/init/web-app/eslint.preset.json.golden @@ -231,8 +231,7 @@ }, { "plugins": [ - "@eslint-community/eslint-comments", - "webtops" + "@eslint-community/eslint-comments" ], "rules": { "@typescript-eslint/no-explicit-any": "error", @@ -267,8 +266,7 @@ } ], "@eslint-community/eslint-comments/require-description": "error", - "@eslint-community/eslint-comments/no-unlimited-disable": "error", - "webtops/no-unsanitized-html": "error" + "@eslint-community/eslint-comments/no-unlimited-disable": "error" }, "linterOptions": { "reportUnusedDisableDirectives": "error" @@ -406,10 +404,11 @@ "**/*.tsx" ], "plugins": [ - "webtops" + "react-hooks" ], "rules": { - "webtops/public-env-only": "error" + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "error" } }, { @@ -417,20 +416,7 @@ "webtops" ], "rules": { - "webtops/complete-tailwind-classes": "error" - } - }, - { - "files": [ - "**/*.jsx", - "**/*.tsx" - ], - "plugins": [ - "react-hooks" - ], - "rules": { - "react-hooks/rules-of-hooks": "error", - "react-hooks/exhaustive-deps": "error" + "webtops/no-unsanitized-html": "error" } }, { diff --git a/packages/eslint-plugin-webtops/src/ast.ts b/packages/eslint-plugin-webtops/src/ast.ts index 6bf2088..fe0fdf0 100644 --- a/packages/eslint-plugin-webtops/src/ast.ts +++ b/packages/eslint-plugin-webtops/src/ast.ts @@ -40,10 +40,13 @@ const literalText = (node: unknown): string | undefined => { const plainTemplateText = (node: unknown): string | undefined => children(node, "expressions").length === 0 ? quasisOf(node)[0] : undefined; -const TEXT = new Map string | undefined>([ - ["Literal", literalText], - ["TemplateLiteral", plainTemplateText], -]); +// Tables are built where they are used, not at module level: a mutant in module-level data runs +// the whole suite again (a static mutant), one in a function runs only the tests that reach it. +const textReaders = (): ReadonlyMap string | undefined> => + new Map([ + ["Literal", literalText], + ["TemplateLiteral", plainTemplateText], + ]); /** The entry of a table keyed by node type, for the node's own type. */ export function byKind(table: ReadonlyMap, node: unknown): T | undefined { @@ -58,7 +61,8 @@ export const lookup = ( ): T | undefined => (name === undefined ? undefined : table.get(name)); /** The text of a string literal or of a template literal with no interpolation; undefined for anything else. */ -export const staticText = (node: unknown): string | undefined => byKind(TEXT, node)?.(node); +export const staticText = (node: unknown): string | undefined => + byKind(textReaders(), node)?.(node); const joined = (object: string | undefined, property: string | undefined): string | undefined => object !== undefined && property !== undefined ? `${object}.${property}` : undefined; diff --git a/packages/eslint-plugin-webtops/src/index.ts b/packages/eslint-plugin-webtops/src/index.ts index 831ecb3..9205ea0 100644 --- a/packages/eslint-plugin-webtops/src/index.ts +++ b/packages/eslint-plugin-webtops/src/index.ts @@ -5,11 +5,15 @@ import publicEnvOnly from "./rules/public-env-only.ts"; /** The rules behind Web-TOPS laws W-23, W-36 and W-37, under the `webtops` namespace. */ const plugin: ESLint.Plugin = { - meta: { name: "eslint-plugin-webtops" }, - rules: { - "complete-tailwind-classes": completeTailwindClasses, - "no-unsanitized-html": noUnsanitizedHtml, - "public-env-only": publicEnvOnly, + get meta() { + return { name: "eslint-plugin-webtops" }; + }, + get rules() { + return { + "complete-tailwind-classes": completeTailwindClasses, + "no-unsanitized-html": noUnsanitizedHtml, + "public-env-only": publicEnvOnly, + }; }, }; diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts index a167d23..c248f27 100644 --- a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts @@ -15,8 +15,19 @@ import { /** W-23: a Tailwind class name is a complete string, never built by interpolation or concatenation. */ -const CLASS_ATTRIBUTES = new Set(["className", "class"]); -const HELPERS = ["clsx", "cn", "classnames", "classNames", "twMerge", "twJoin", "cva", "tv"]; +const isClassAttribute = (name: string | undefined): boolean => + name === "className" || name === "class"; + +const defaultHelpers = (): string[] => [ + "clsx", + "cn", + "classnames", + "classNames", + "twMerge", + "twJoin", + "cva", + "tv", +]; const endsInToken = (text: string | undefined): boolean => text !== undefined && /\S$/u.test(text); const startsInToken = (text: string | undefined): boolean => @@ -45,19 +56,20 @@ function pairGlued(left: unknown, right: unknown): boolean { ); } -const PLUS_CHAIN = new Map readonly unknown[]>([ - [ - "BinaryExpression", - (node) => - child(node, "operator") === "+" - ? [...operands(child(node, "left")), ...operands(child(node, "right"))] - : [node], - ], -]); +const plusChain = (): ReadonlyMap readonly unknown[]> => + new Map([ + [ + "BinaryExpression", + (node) => + child(node, "operator") === "+" + ? [...operands(child(node, "left")), ...operands(child(node, "right"))] + : [node], + ], + ]); /** The operands of a chain of `+`, left to right; any other node is one operand. */ function operands(node: unknown): readonly unknown[] { - return byKind(PLUS_CHAIN, node)?.(node) ?? [node]; + return byKind(plusChain(), node)?.(node) ?? [node]; } function partsBuildToken(parts: readonly unknown[]): boolean { @@ -68,68 +80,73 @@ function partsBuildToken(parts: readonly unknown[]): boolean { } /** Method calls that build a class string: `"bg-".concat(color)` joins like `+`, and `[...].join(" ")` builds from its items. */ -const METHODS = new Map boolean>([ - ["concat", (object, args) => partsBuildToken([object, ...args])], - ["join", (object) => buildsToken(object)], -]); +const methods = (): ReadonlyMap boolean> => + new Map([ + ["concat", (object, args) => partsBuildToken([object, ...args])], + ["join", (object) => buildsToken(object)], + ]); function methodBuildsToken(call: unknown): boolean { const callee = child(call, "callee"); - const method = lookup(METHODS, propertyName(callee)); + const method = lookup(methods(), propertyName(callee)); return method?.(child(callee, "object"), children(call, "arguments")) === true; } /** A key that is not computed is an identifier or a literal, which cannot build a token. */ const keyBuildsToken = (property: unknown): boolean => buildsToken(child(property, "key")); -const CHECKS = new Map boolean>([ - ["TemplateLiteral", templateBuildsToken], - [ - "BinaryExpression", - (node) => child(node, "operator") === "+" && partsBuildToken(operands(node)), - ], - ["CallExpression", methodBuildsToken], - [ - "ConditionalExpression", - (node) => buildsToken(child(node, "consequent")) || buildsToken(child(node, "alternate")), - ], - [ - "LogicalExpression", - (node) => buildsToken(child(node, "left")) || buildsToken(child(node, "right")), - ], - ["ArrayExpression", (node) => children(node, "elements").some(buildsToken)], - ["ObjectExpression", (node) => children(node, "properties").some(keyBuildsToken)], -]); +const checks = (): ReadonlyMap boolean> => + new Map([ + ["TemplateLiteral", templateBuildsToken], + [ + "BinaryExpression", + (node) => child(node, "operator") === "+" && partsBuildToken(operands(node)), + ], + ["CallExpression", methodBuildsToken], + [ + "ConditionalExpression", + (node) => buildsToken(child(node, "consequent")) || buildsToken(child(node, "alternate")), + ], + [ + "LogicalExpression", + (node) => buildsToken(child(node, "left")) || buildsToken(child(node, "right")), + ], + ["ArrayExpression", (node) => children(node, "elements").some(buildsToken)], + ["ObjectExpression", (node) => children(node, "properties").some(keyBuildsToken)], + ]); /** Whether an expression that ends up in a class list builds a class token at run time. */ -export const buildsToken = (node: unknown): boolean => byKind(CHECKS, node)?.(node) === true; +export const buildsToken = (node: unknown): boolean => byKind(checks(), node)?.(node) === true; const rule: Rule.RuleModule = { - meta: { - type: "problem", - docs: { - description: - "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", - }, - schema: [ - { - type: "object", - properties: { functions: { type: "array", items: { type: "string" }, uniqueItems: true } }, - additionalProperties: false, + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { + description: + "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", }, - ], - messages: { - incomplete: - "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", - }, + schema: [ + { + type: "object", + properties: { + functions: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + incomplete: + "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", + }, + }; }, create(context) { const option: unknown = context.options[0]; - const helpers = new Set(stringList(option, "functions", HELPERS)); + const helpers = new Set(stringList(option, "functions", defaultHelpers())); return { JSXAttribute(node: Rule.Node) { - const name = attributeName(node); - if (name !== undefined && CLASS_ATTRIBUTES.has(name) && buildsToken(attributeValue(node))) { + if (isClassAttribute(attributeName(node)) && buildsToken(attributeValue(node))) { context.report({ node, messageId: "incomplete" }); } }, diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts index 600c0fc..482a983 100644 --- a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts @@ -16,9 +16,7 @@ import { /** W-36: HTML reaches `set:html`, `dangerouslySetInnerHTML` or `innerHTML` only as a literal or through a sanitizer. */ -const SANITIZERS = ["sanitize", "sanitizeHtml", "DOMPurify.sanitize"]; -const ASSIGNED_SINKS = new Set(["innerHTML", "outerHTML"]); -const WRITERS = new Set(["document.write", "document.writeln"]); +const defaultSanitizers = (): string[] => ["sanitize", "sanitizeHtml", "DOMPurify.sanitize"]; /** Where markup goes in, and what is put there. */ interface Sink { @@ -28,24 +26,26 @@ interface Sink { type Safe = (node: unknown, sanitizers: ReadonlySet) => boolean; -const SAFE = new Map([ - [ - "CallExpression", - (node, sanitizers) => { - const callee = dottedName(child(node, "callee")); - return callee !== undefined && sanitizers.has(callee); - }, - ], - [ - "ConditionalExpression", - (node, sanitizers) => - isSafe(child(node, "consequent"), sanitizers) && isSafe(child(node, "alternate"), sanitizers), - ], -]); +const safeChecks = (): ReadonlyMap => + new Map([ + [ + "CallExpression", + (node, sanitizers) => { + const callee = dottedName(child(node, "callee")); + return callee !== undefined && sanitizers.has(callee); + }, + ], + [ + "ConditionalExpression", + (node, sanitizers) => + isSafe(child(node, "consequent"), sanitizers) && + isSafe(child(node, "alternate"), sanitizers), + ], + ]); /** A literal, or the result of a sanitizer; a conditional is safe when both branches are. */ export const isSafe = (node: unknown, sanitizers: ReadonlySet): boolean => - staticText(node) !== undefined || byKind(SAFE, node)?.(node, sanitizers) === true; + staticText(node) !== undefined || byKind(safeChecks(), node)?.(node, sanitizers) === true; /** What `dangerouslySetInnerHTML={{ __html: x }}` sets: `x`. A value that is not an object literal is its own payload, and an object with no `__html` sets nothing. */ function htmlPayload(value: unknown): { html: unknown } | undefined { @@ -56,20 +56,21 @@ function htmlPayload(value: unknown): { html: unknown } | undefined { return entry === undefined ? undefined : { html: child(entry, "value") }; } -const ATTRIBUTE_SINKS = new Map { html: unknown } | undefined>([ - ["dangerouslySetInnerHTML", htmlPayload], - ["set:html", (value) => ({ html: value })], -]); +const attributeSinks = (): ReadonlyMap { html: unknown } | undefined> => + new Map([ + ["dangerouslySetInnerHTML", htmlPayload], + ["set:html", (value) => ({ html: value })], + ]); function attributeSink(attribute: unknown): Sink | undefined { const name = attributeName(attribute); - const payload = lookup(ATTRIBUTE_SINKS, name)?.(attributeValue(attribute)); + const payload = lookup(attributeSinks(), name)?.(attributeValue(attribute)); return name === undefined || payload === undefined ? undefined : { sink: name, ...payload }; } function assignedSink(assignment: unknown): Sink | undefined { const sink = propertyName(child(assignment, "left")); - return sink !== undefined && ASSIGNED_SINKS.has(sink) + return sink === "innerHTML" || sink === "outerHTML" ? { sink, html: child(assignment, "right") } : undefined; } @@ -82,7 +83,7 @@ function insertedSink(call: unknown): Sink | undefined { function writtenSink(call: unknown): Sink | undefined { const name = dottedName(child(call, "callee")); - return name !== undefined && WRITERS.has(name) + return name === "document.write" || name === "document.writeln" ? { sink: name, html: children(call, "arguments")[0] } : undefined; } @@ -90,27 +91,31 @@ function writtenSink(call: unknown): Sink | undefined { const callSink = (call: unknown): Sink | undefined => insertedSink(call) ?? writtenSink(call); const rule: Rule.RuleModule = { - meta: { - type: "problem", - docs: { - description: - "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", - }, - schema: [ - { - type: "object", - properties: { sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true } }, - additionalProperties: false, + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { + description: + "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", }, - ], - messages: { - unsanitized: - "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", - }, + schema: [ + { + type: "object", + properties: { + sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + unsanitized: + "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", + }, + }; }, create(context) { const option: unknown = context.options[0]; - const list = stringList(option, "sanitizers", SANITIZERS); + const list = stringList(option, "sanitizers", defaultSanitizers()); const sanitizers = new Set(list); const inspect = (node: Rule.Node, found: Sink | undefined): void => { if (found === undefined || isSafe(found.html, sanitizers)) return; diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts index a0fedcd..a7ae01d 100644 --- a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts @@ -3,9 +3,9 @@ import { child, children, dottedName, kind, nameOf, propertyName, stringList } f /** W-37: client code reads only public env: `PUBLIC_` variables, and `astro:env/client` fields. */ -const PREFIXES = ["PUBLIC_"]; +const defaultPrefixes = (): string[] => ["PUBLIC_"]; /** What Vite and Astro define for every build, and none of it is a secret. */ -const BUILT_IN = ["MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE"]; +const builtIn = (): string[] => ["MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE"]; /** `process.env` or `import.meta.env`. */ function isEnvObject(node: unknown): boolean { @@ -21,34 +21,36 @@ const isChildOf = (parent: unknown, type: string, field: string, node: unknown): kind(parent) === type && child(parent, field) === node; const rule: Rule.RuleModule = { - meta: { - type: "problem", - docs: { description: "Only public env reaches client code (W-37)" }, - schema: [ - { - type: "object", - properties: { - prefixes: { type: "array", items: { type: "string" }, uniqueItems: true }, - allowed: { type: "array", items: { type: "string" }, uniqueItems: true }, + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { description: "Only public env reaches client code (W-37)" }, + schema: [ + { + type: "object", + properties: { + prefixes: { type: "array", items: { type: "string" }, uniqueItems: true }, + allowed: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, }, - additionalProperties: false, + ], + messages: { + private: + "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", + dynamic: + "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", + whole: + "The whole env object reaches client code. Read the public variables you need, by name.", + server: + "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", }, - ], - messages: { - private: - "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", - dynamic: - "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", - whole: - "The whole env object reaches client code. Read the public variables you need, by name.", - server: - "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", - }, + }; }, create(context) { const option: unknown = context.options[0]; - const prefixes = stringList(option, "prefixes", PREFIXES); - const allowed = new Set(stringList(option, "allowed", BUILT_IN)); + const prefixes = stringList(option, "prefixes", defaultPrefixes()); + const allowed = new Set(stringList(option, "allowed", builtIn())); const isPublic = (name: string): boolean => allowed.has(name) || prefixes.some((prefix) => name.startsWith(prefix)); const reportName = (node: Rule.Node, name: string | undefined): void => { diff --git a/profiles/web-app.yaml b/profiles/web-app.yaml index cfdb93b..1891c44 100644 --- a/profiles/web-app.yaml +++ b/profiles/web-app.yaml @@ -6,7 +6,7 @@ crap_cap: 6 survivors_max: 2 js_budget: "170 KB per route" playwright: true -eslint: react-app +eslint: react tools: - "@eslint-community/eslint-plugin-eslint-comments" - "@eslint/js" diff --git a/src/cli/m3-open.test.ts b/src/cli/m3-open.test.ts index a42e94e..1eb3ca0 100644 --- a/src/cli/m3-open.test.ts +++ b/src/cli/m3-open.test.ts @@ -262,7 +262,6 @@ describe("M3 G0b: the kit's Vitest config, exactly", () => { expect(vitestConfig).toEqual({ test: { testTimeout: 30_000, - globalSetup: ["./vitest.global-setup.js"], include: ["src/**/*.test.ts", "packages/**/*.test.ts"], exclude: [ ...configDefaults.exclude, diff --git a/src/init/init.test.ts b/src/init/init.test.ts index 3838a1d..d2ca4c3 100644 --- a/src/init/init.test.ts +++ b/src/init/init.test.ts @@ -16,11 +16,11 @@ const CLASSES = ["ts-library", "ui-components", "astro-site", "web-app", "node-s type Class = (typeof CLASSES)[number]; // From WEB_TOPS.md section 4: which plugin set each class adds to the base law rules. -const VARIANT: Record = { +const VARIANT: Record = { "ts-library": "base", "node-service": "base", "ui-components": "react", - "web-app": "react-app", + "web-app": "react", "astro-site": "astro", }; diff --git a/src/init/profile.ts b/src/init/profile.ts index b475293..084c807 100644 --- a/src/init/profile.ts +++ b/src/init/profile.ts @@ -9,7 +9,7 @@ import { PROFILES, profileFor } from "../config/profiles.ts"; export const LAUNCH_CLASSES: readonly string[] = PROFILES.map((profile) => profile.class); /** Which plugin set `eslint.config.js` adds on top of the base law rules. */ -export type EslintVariant = "base" | "react" | "react-app" | "astro"; +export type EslintVariant = "base" | "react" | "astro"; /** The drop-in data for one class (the floors and mapped layers live in the class table; see the agreement test): floors, the tools its enabled layers run, and what M1 leaves off. */ export interface DropIn { @@ -46,7 +46,7 @@ const schema = { survivors_max: { type: "integer", minimum: 0 }, js_budget: { type: "string", minLength: 1 }, playwright: { type: "boolean" }, - eslint: { enum: ["base", "react", "react-app", "astro"] }, + eslint: { enum: ["base", "react", "astro"] }, tools: { type: "array", items: { type: "string", minLength: 1 }, uniqueItems: true }, disabled: { type: "object", additionalProperties: { type: "string", minLength: 1 } }, }, diff --git a/src/init/render.ts b/src/init/render.ts index 4071b74..1241da8 100644 --- a/src/init/render.ts +++ b/src/init/render.ts @@ -135,7 +135,7 @@ export function agentsSection(profile: DropIn, subject: Subject, astroCheck: Ast "rendered", `- JS per page or route ≤ \`${profile.js_budget}\` (brotli, from the build output), where the class ships pages`, ), - HOOKS_LINE: profile.eslint.startsWith("react") ? HOOKS_LINE : "", + HOOKS_LINE: profile.eslint === "react" ? HOOKS_LINE : "", RENDERED_SECTION: renderedSection(profile), VERIFIES: verifies(profile, astroCheck), LAWS_NOTE: enabled(profile, "laws") ? "" : LAWS_NOTE, diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts index 0b9ba11..21a3903 100644 --- a/src/presets/class-rules.test.ts +++ b/src/presets/class-rules.test.ts @@ -1,40 +1,61 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { join, resolve } from "node:path"; import { describe, expect, it } from "vitest"; -import { loadProfile } from "../init/profile.ts"; -import { CATALOG_DIR, LAW_CLASSES, loadCatalog, select } from "../laws/catalog/index.ts"; -import type { Law, LawClass } from "../laws/catalog/index.ts"; +import { parse } from "yaml"; import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; import { eslintPreset } from "./eslint.js"; +import type { EslintVariant } from "./eslint.js"; +const ROOT = resolve(import.meta.dirname, "../.."); const PREFIX = "webtops/"; +const CLASSES = ["ts-library", "ui-components", "astro-site", "web-app", "node-service"]; -/** The laws of the catalog, as the catalog loads them. */ -function lawsOf(): readonly Law[] { - const catalog = loadCatalog(CATALOG_DIR); - if (!catalog.ok) throw new Error(JSON.stringify(catalog.problems)); - return catalog.laws; +function yamlOf(path: string): unknown { + return parse(readFileSync(join(ROOT, path), "utf8")); +} + +function field(value: unknown, key: string): unknown { + return typeof value === "object" && value !== null ? Reflect.get(value, key) : undefined; +} + +function list(value: unknown, key: string): unknown[] { + const found = field(value, key); + return Array.isArray(found) ? found : []; +} + +/** The variant a class's drop-in profile names. */ +function variantOf(cls: string): EslintVariant { + const named = field(yamlOf(`profiles/${cls}.yaml`), "eslint"); + if (named === "base" || named === "react" || named === "astro") return named; + throw new Error(`profiles/${cls}.yaml names no variant`); } /** The plugin's rules, named as a config names them. */ const IMPLEMENTED = new Set(Object.keys(plugin.rules ?? {}).map((name) => `${PREFIX}${name}`)); /** - * The `webtops/*` rules a class's laws map to the ESLint reader that the plugin has built. A law - * can name a rule that a later step builds (the Astro rules of W-28, W-30 and W-31); the step that - * adds the rule to the plugin must also enable it, or this test fails. + * The `webtops/*` rules the laws a class maps give the ESLint reader, read from the law files. A law + * can name a rule that a later step builds; the step that adds the rule to the plugin must also + * enable it, or this test fails. */ -function mappedRules(laws: readonly Law[], cls: LawClass): string[] { - return select(laws, { cls, required: false }) - .flatMap((law) => law.rules) - .filter((rule) => rule.tool === "eslint" && IMPLEMENTED.has(rule.name)) - .map((rule) => rule.name) - .sort(); +function mappedRules(cls: string): string[] { + const names = readdirSync(join(ROOT, "laws")) + .filter((file) => file.endsWith(".yaml")) + .map((file) => yamlOf(`laws/${file}`)) + .filter((law) => list(law, "classes").includes(cls)) + .flatMap((law) => list(law, "rules")) + .filter((rule) => field(rule, "tool") === "eslint") + .map((rule) => field(rule, "name")) + .filter((name): name is string => typeof name === "string" && IMPLEMENTED.has(name)); + return names.sort(); } -/** The `webtops/*` rules the class's preset sets to error. */ -async function enabledRules(cls: LawClass): Promise { - const loaded = loadProfile(cls); - if (!loaded.ok) throw new Error(loaded.error); - const config = await eslintPreset({ variant: loaded.profile.eslint, tsconfigRootDir: "

" }); +async function enabledRules(cls: string): Promise { + const config = await eslintPreset({ + variant: variantOf(cls), + tsconfigRootDir: "", + class: cls, + }); const names = config.flatMap((entry) => Object.entries(entry.rules ?? {}) .filter(([name, setting]) => name.startsWith(PREFIX) && setting === "error") @@ -44,20 +65,15 @@ async function enabledRules(cls: LawClass): Promise { } describe("R98: a class's preset enables exactly the plugin rules its laws map", () => { - const laws = lawsOf(); - - it.each(LAW_CLASSES)( - "%s: the enabled webtops/* rules are the mapped laws' rules", - async (cls) => { - const mapped = mappedRules(laws, cls); - expect(mapped.length).toBeGreaterThan(0); - expect(await enabledRules(cls)).toEqual(mapped); - }, - ); + it.each(CLASSES)("%s: the enabled webtops/* rules are the mapped laws' rules", async (cls) => { + const mapped = mappedRules(cls); + expect(mapped.length).toBeGreaterThan(0); + expect(await enabledRules(cls)).toEqual(mapped); + }); it("holds the split the laws make: the Tailwind rule only for astro-site and web-app", async () => { - const withTailwind: LawClass[] = []; - for (const cls of LAW_CLASSES) { + const withTailwind: string[] = []; + for (const cls of CLASSES) { if ((await enabledRules(cls)).includes("webtops/complete-tailwind-classes")) { withTailwind.push(cls); } diff --git a/src/presets/eslint.d.ts b/src/presets/eslint.d.ts index 2040433..26f2de5 100644 --- a/src/presets/eslint.d.ts +++ b/src/presets/eslint.d.ts @@ -1,12 +1,14 @@ import type { Linter } from "eslint"; /** The plugin set a class adds on top of the base law rules. */ -export type EslintVariant = "base" | "react" | "react-app" | "astro"; +export type EslintVariant = "base" | "react" | "astro"; export interface EslintPresetOptions { readonly variant: EslintVariant; /** The project root, so the type-aware rules find its tsconfig. */ readonly tsconfigRootDir: string; + /** The project's class, which decides the rules of `eslint-plugin-webtops`; read from `web-tops.yaml` when left out. */ + readonly class?: string; } export const VARIANTS: readonly EslintVariant[]; diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 10e47d4..03fa48c 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -1,9 +1,11 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; import eslintComments from "@eslint-community/eslint-plugin-eslint-comments"; import js from "@eslint/js"; import vitest from "@vitest/eslint-plugin"; import { defineConfig } from "eslint/config"; import tseslint from "typescript-eslint"; -import webtops from "../../packages/eslint-plugin-webtops/dist/index.js"; // The ESLint preset behind `web-tops/eslint` (WEB_TOPS.md section 8.2). Every rule below is the reader // behind a judged law and stays at "error"; weaken one only through a protocol-change PR. A project's @@ -51,28 +53,74 @@ const LAW_RULES = { ], "@eslint-community/eslint-comments/require-description": "error", "@eslint-community/eslint-comments/no-unlimited-disable": "error", - // W-36 no unsanitized HTML in `set:html`, `dangerouslySetInnerHTML`, `innerHTML` and the like - "webtops/no-unsanitized-html": "error", }; const TSX = ["**/*.jsx", "**/*.tsx"]; -// The rules of `eslint-plugin-webtops` beyond W-36. The plugin ships inside this package (its build -// 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 PLUGIN_SOURCE = join( + import.meta.dirname, + "../../packages/eslint-plugin-webtops/src/index.ts", +); -/** W-37 only public env reaches client code, for the classes with a UI (ui-components, astro-site, web-app). */ -const WEBTOPS_CLIENT = [ - // The scope is the client modules, not .astro frontmatter, which is server code (an Astro client - // script block is read in the Astro rules) - { files: TSX, plugins: { webtops }, rules: { "webtops/public-env-only": "error" } }, -]; +/** + * `eslint-plugin-webtops`, which ships inside this package: a published package has its build, and + * a checkout of the kit has the source, which Node reads as it is, so a test run needs no build. + */ +async function loadWebtops() { + const loaded = existsSync(PLUGIN_SOURCE) + ? await import(pathToFileURL(PLUGIN_SOURCE).href) + : await import("../../packages/eslint-plugin-webtops/dist/index.js"); + return loaded.default; +} -/** W-23 Tailwind class names are complete strings, in every file, for astro-site and web-app. */ -const WEBTOPS_TAILWIND = [ - { plugins: { webtops }, rules: { "webtops/complete-tailwind-classes": "error" } }, +const webtops = await loadWebtops(); + +/** eslint-plugin-astro lints each `