diff --git a/fixtures/init/astro-site/eslint.preset.json.golden b/fixtures/init/astro-site/eslint.preset.json.golden index 0314027..4d849d2 100644 --- a/fixtures/init/astro-site/eslint.preset.json.golden +++ b/fixtures/init/astro-site/eslint.preset.json.golden @@ -611,6 +611,109 @@ } } }, + { + "files": [ + "**/*.astro" + ], + "plugins": [], + "parserOptions": { + "projectService": false, + "project": "./tsconfig.json", + "tsconfigRootDir": "", + "extraFileExtensions": [ + ".astro" + ] + } + }, + { + "files": [ + "**/*.astro/*.ts", + "**/*.astro/*.js" + ], + "plugins": [], + "rules": { + "@typescript-eslint/await-thenable": "off", + "@typescript-eslint/consistent-return": "off", + "@typescript-eslint/consistent-type-exports": "off", + "@typescript-eslint/dot-notation": "off", + "@typescript-eslint/naming-convention": "off", + "@typescript-eslint/no-array-delete": "off", + "@typescript-eslint/no-base-to-string": "off", + "@typescript-eslint/no-confusing-void-expression": "off", + "@typescript-eslint/no-deprecated": "off", + "@typescript-eslint/no-duplicate-type-constituents": "off", + "@typescript-eslint/no-floating-promises": "off", + "@typescript-eslint/no-for-in-array": "off", + "@typescript-eslint/no-generated-empty-object-type": "off", + "@typescript-eslint/no-implied-eval": "off", + "@typescript-eslint/no-meaningless-void-operator": "off", + "@typescript-eslint/no-misused-promises": "off", + "@typescript-eslint/no-misused-spread": "off", + "@typescript-eslint/no-mixed-enums": "off", + "@typescript-eslint/no-redundant-type-constituents": "off", + "@typescript-eslint/no-unnecessary-boolean-literal-compare": "off", + "@typescript-eslint/no-unnecessary-condition": "off", + "@typescript-eslint/no-unnecessary-qualifier": "off", + "@typescript-eslint/no-unnecessary-template-expression": "off", + "@typescript-eslint/no-unnecessary-type-arguments": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "off", + "@typescript-eslint/no-unnecessary-type-conversion": "off", + "@typescript-eslint/no-unnecessary-type-parameters": "off", + "@typescript-eslint/no-unsafe-argument": "off", + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unsafe-call": "off", + "@typescript-eslint/no-unsafe-class-instance-assignment": "off", + "@typescript-eslint/no-unsafe-enum-assignment": "off", + "@typescript-eslint/no-unsafe-enum-comparison": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/no-unsafe-return": "off", + "@typescript-eslint/no-unsafe-type-assertion": "off", + "@typescript-eslint/no-unsafe-unary-minus": "off", + "@typescript-eslint/no-useless-default-assignment": "off", + "@typescript-eslint/non-nullable-type-assertion-style": "off", + "@typescript-eslint/only-throw-error": "off", + "@typescript-eslint/prefer-destructuring": "off", + "@typescript-eslint/prefer-find": "off", + "@typescript-eslint/prefer-includes": "off", + "@typescript-eslint/prefer-nullish-coalescing": "off", + "@typescript-eslint/prefer-optional-chain": "off", + "@typescript-eslint/prefer-promise-reject-errors": "off", + "@typescript-eslint/prefer-readonly": "off", + "@typescript-eslint/prefer-readonly-parameter-types": "off", + "@typescript-eslint/prefer-reduce-type-parameter": "off", + "@typescript-eslint/prefer-regexp-exec": "off", + "@typescript-eslint/prefer-return-this-type": "off", + "@typescript-eslint/prefer-string-starts-ends-with": "off", + "@typescript-eslint/promise-function-async": "off", + "@typescript-eslint/related-getter-setter-pairs": "off", + "@typescript-eslint/require-array-sort-compare": "off", + "@typescript-eslint/require-await": "off", + "@typescript-eslint/restrict-plus-operands": "off", + "@typescript-eslint/restrict-template-expressions": "off", + "@typescript-eslint/return-await": "off", + "@typescript-eslint/strict-boolean-expressions": "off", + "@typescript-eslint/strict-void-return": "off", + "@typescript-eslint/switch-exhaustiveness-check": "off", + "@typescript-eslint/unbound-method": "off", + "@typescript-eslint/use-unknown-in-catch-callback-variable": "off" + }, + "parserOptions": { + "program": null, + "project": false, + "projectService": false + } + }, + { + "files": [ + "**/*.astro/*.ts", + "**/*.astro/*.js" + ], + "plugins": [], + "parserOptions": { + "projectService": false, + "project": null + } + }, { "plugins": [ "webtops" diff --git a/packages/eslint-plugin-webtops/src/ack.test.ts b/packages/eslint-plugin-webtops/src/ack.test.ts new file mode 100644 index 0000000..24db6ba --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ack.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { ackReason } from "./ack.ts"; + +describe("ackReason", () => { + it("gives the reason, trimmed", () => { + expect(ackReason(" webtops-ack W-28: the cart must work at once ", "W-28")).toBe( + "the cart must work at once", + ); + }); + + it("takes a reason over several lines", () => { + expect(ackReason("\n webtops-ack W-28: the cart\n must work\n", "W-28")).toBe( + "the cart\n must work", + ); + }); + + it("needs no space after the colon, and takes more than one before the law", () => { + expect(ackReason("webtops-ack W-28:reason", "W-28")).toBe("reason"); + expect(ackReason("webtops-ack W-28: reason", "W-28")).toBe("reason"); + }); + + it.each([ + ["no reason", "webtops-ack W-28:"], + ["a blank reason", "webtops-ack W-28: "], + ["another law", "webtops-ack W-30: reason"], + ["a longer law number", "webtops-ack W-280: reason"], + ["no colon", "webtops-ack W-28 reason"], + ["no space before the law", "webtops-ackW-28: reason"], + ["text before it", "see webtops-ack W-28: reason"], + ["another marker", "ack W-28: reason"], + ["a plain comment", "the cart"], + ])("is nothing for %s", (_name, text) => { + expect(ackReason(text, "W-28")).toBeUndefined(); + }); + + it("is nothing for a law that is not the one asked for", () => { + expect(ackReason("webtops-ack W-28: reason", "W-2")).toBeUndefined(); + expect(ackReason("webtops-ack W-28: reason", "W-30")).toBeUndefined(); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/ack.ts b/packages/eslint-plugin-webtops/src/ack.ts new file mode 100644 index 0000000..c22bf85 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ack.ts @@ -0,0 +1,10 @@ +/** + * The acknowledgement a soft law (severity A) accepts written in the source: `webtops-ack W-NN: reason`, + * with a reason. The ledger form lives in `.web-tops/` and is read by the laws layer (milestone M3, G8): + * this is the one place the plugin reads an acknowledgement, so G8 widens it here. + */ +/** The reason a comment's text gives for acknowledging the law, or undefined when it does not acknowledge it. */ +export function ackReason(text: string, law: string): string | undefined { + const match = /^\s*webtops-ack\s+(W-\d+):\s*(\S[\s\S]*?)\s*$/u.exec(text); + return match?.[1] === law ? match[2] : undefined; +} diff --git a/packages/eslint-plugin-webtops/src/index.test.ts b/packages/eslint-plugin-webtops/src/index.test.ts index 7fa69ca..ddc2f10 100644 --- a/packages/eslint-plugin-webtops/src/index.test.ts +++ b/packages/eslint-plugin-webtops/src/index.test.ts @@ -18,10 +18,12 @@ function need(value: T | undefined): T { return value; } -const RULES = ["complete-tailwind-classes", "no-unsanitized-html", "public-env-only"]; +const JSX_RULES = ["complete-tailwind-classes", "no-unsanitized-html", "public-env-only"]; +const ASTRO_RULES = ["astro-assets-image", "astro-client-load-ack", "astro-frontmatter-size"]; +const RULES = [...ASTRO_RULES, ...JSX_RULES]; describe("G6a: eslint-plugin-webtops", () => { - it("names itself and holds the three rules of W-23, W-36 and W-37", () => { + it("names itself and holds the rules of W-23, W-28, W-30, W-31, W-36 and W-37", () => { expect(plugin.meta).toEqual({ name: "eslint-plugin-webtops" }); expect(Object.keys(plugin.rules ?? {}).sort()).toEqual(RULES); }); @@ -63,7 +65,7 @@ describe("G6a: eslint-plugin-webtops", () => { ].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}`), + JSX_RULES.map((name) => `webtops/${name}`), ); }); diff --git a/packages/eslint-plugin-webtops/src/index.ts b/packages/eslint-plugin-webtops/src/index.ts index 9205ea0..9573036 100644 --- a/packages/eslint-plugin-webtops/src/index.ts +++ b/packages/eslint-plugin-webtops/src/index.ts @@ -1,15 +1,21 @@ import type { ESLint } from "eslint"; +import astroAssetsImage from "./rules/astro-assets-image.ts"; +import astroClientLoadAck from "./rules/astro-client-load-ack.ts"; +import astroFrontmatterSize from "./rules/astro-frontmatter-size.ts"; 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. */ +/** The rules behind Web-TOPS laws W-23, W-28, W-30, W-31, W-36 and W-37, under the `webtops` namespace. */ const plugin: ESLint.Plugin = { get meta() { return { name: "eslint-plugin-webtops" }; }, get rules() { return { + "astro-assets-image": astroAssetsImage, + "astro-client-load-ack": astroClientLoadAck, + "astro-frontmatter-size": astroFrontmatterSize, "complete-tailwind-classes": completeTailwindClasses, "no-unsanitized-html": noUnsanitizedHtml, "public-env-only": publicEnvOnly, diff --git a/packages/eslint-plugin-webtops/src/rules/astro-assets-image.test.ts b/packages/eslint-plugin-webtops/src/rules/astro-assets-image.test.ts new file mode 100644 index 0000000..63cb01f --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-assets-image.test.ts @@ -0,0 +1,143 @@ +import { RuleTester } from "eslint"; +import type { Linter } from "eslint"; +import astro from "eslint-plugin-astro"; +import { describe, expect, it } from "vitest"; +import rule from "./astro-assets-image.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +/** The language options eslint-plugin-astro gives `.astro` files: the Astro parser, with TypeScript in the frontmatter. */ +function astroOptions(): Linter.LanguageOptions { + const entry = astro.configs["flat/base"].find((config) => config.name === "astro/base"); + if (entry?.languageOptions === undefined) throw new Error("no astro/base config"); + return entry.languageOptions; +} + +const tester = new RuleTester({ languageOptions: astroOptions() }); + +const IMPORT = 'import { Image, Picture } from "astro:assets";'; + +const page = (template: string, imports = IMPORT): { code: string; filename: string } => ({ + code: `---\n${imports}\nimport hero from "../hero.png";\n---\n${template}\n`, + filename: "page.astro", +}); + +const raw = [{ messageId: "raw" as const }]; +const lacking = (name: string) => [{ messageId: "dimensions" as const, data: { name } }]; + +tester.run("astro-assets-image", rule, { + valid: [ + { + name: "an Image with dimensions", + ...page(''), + }, + { + name: "a Picture with dimensions", + ...page(''), + }, + { + name: "an Image whose size Astro reads from the file", + ...page(''), + }, + { + name: "an Image with a spread that may carry the dimensions", + ...page(""), + }, + { + name: "a spread beside other attributes", + ...page(''), + }, + { + name: "a named Image from another module", + ...page('', 'import { Image } from "../components";'), + }, + { + name: "a member element is not read as an Image", + ...page('', 'import * as assets from "astro:assets";'), + }, + { + name: "an aliased import", + ...page( + '', + 'import { Image as Img } from "astro:assets";', + ), + }, + { + name: "an Image from another module is not the astro:assets one", + ...page('', 'import Image from "../Image.astro";'), + }, + { + name: "an Image that is not imported", + ...page('', ""), + }, + { + name: "another member of astro:assets", + ...page('', 'import { getImage as Foo } from "astro:assets";'), + }, + { name: "an ordinary element", ...page("

text

") }, + { + name: "a default import named Image", + ...page('', 'import Image from "astro:assets";'), + }, + ], + invalid: [ + { name: "an img", ...page(''), errors: raw }, + { + name: "an img with width and height", + ...page(''), + errors: raw, + }, + { name: "an img with an expression source", ...page(""), errors: raw }, + { + name: "two img elements, in a parent", + ...page('
'), + errors: [...raw, ...raw], + }, + { + name: "an Image with no dimensions", + ...page(''), + errors: lacking("Image"), + }, + { + name: "an Image with a width only", + ...page(''), + errors: lacking("Image"), + }, + { + name: "an Image with a height only", + ...page(''), + errors: lacking("Image"), + }, + { + name: "a Picture with no dimensions", + ...page(''), + errors: lacking("Picture"), + }, + { + name: "an aliased Image with no dimensions, named by its tag", + ...page('', 'import { Image as Img } from "astro:assets";'), + errors: lacking("Img"), + }, + { + name: "an Image imported with a second one", + ...page("", 'import { Picture, Image } from "astro:assets";'), + errors: lacking("Picture"), + }, + ], +}); + +describe("W-30's rule", () => { + it("says which law it judges", () => { + expect(rule.meta).toEqual({ + type: "suggestion", + docs: { description: "Images go through astro:assets with dimensions (W-30)" }, + schema: [], + messages: { + raw: "An is not optimized. Use or from astro:assets, with width and height.", + dimensions: + "<{{ name }}> needs width and height (or inferSize), so the layout does not shift.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/astro-assets-image.ts b/packages/eslint-plugin-webtops/src/rules/astro-assets-image.ts new file mode 100644 index 0000000..d3035cf --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-assets-image.ts @@ -0,0 +1,56 @@ +import type { Rule } from "eslint"; +import { attributeName, child, children, kind } from "../ast.ts"; + +/** W-30: images go through `astro:assets` (``, ``) with dimensions. */ + +const isComponent = (name: unknown): boolean => name === "Image" || name === "Picture"; + +/** The local names `import { Image, Picture } from "astro:assets"` binds, aliases included. */ +function assetNames(declaration: unknown): unknown[] { + return children(declaration, "specifiers") + .filter((specifier) => isComponent(child(child(specifier, "imported"), "name"))) + .map((specifier) => child(child(specifier, "local"), "name")); +} + +/** Whether the tag leaves its dimensions open: neither stated, nor inferred, nor possibly in a spread. */ +function lacksDimensions(opening: unknown): boolean { + const attributes = children(opening, "attributes"); + if (attributes.some((attribute) => kind(attribute) === "JSXSpreadAttribute")) return false; + const names = new Set(attributes.map(attributeName)); + return !names.has("inferSize") && !(names.has("width") && names.has("height")); +} + +const tagName = (opening: unknown): unknown => child(child(opening, "name"), "name"); + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "suggestion", + docs: { description: "Images go through astro:assets with dimensions (W-30)" }, + schema: [], + messages: { + raw: "An is not optimized. Use or from astro:assets, with width and height.", + dimensions: + "<{{ name }}> needs width and height (or inferSize), so the layout does not shift.", + }, + }; + }, + create(context) { + const bound = new Set(); + return { + ImportDeclaration(node: Rule.Node) { + if (child(child(node, "source"), "value") === "astro:assets") + assetNames(node).forEach((name) => bound.add(name)); + }, + JSXOpeningElement(node: Rule.Node) { + const name = tagName(node); + if (name === "img") context.report({ node, messageId: "raw" }); + else if (bound.has(name) && lacksDimensions(node)) { + context.report({ node, messageId: "dimensions", data: { name: String(name) } }); + } + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.test.ts b/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.test.ts new file mode 100644 index 0000000..4cb0418 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.test.ts @@ -0,0 +1,146 @@ +import { RuleTester } from "eslint"; +import type { Linter } from "eslint"; +import astro from "eslint-plugin-astro"; +import { describe, expect, it } from "vitest"; +import rule from "./astro-client-load-ack.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +/** The language options eslint-plugin-astro gives `.astro` files: the Astro parser, with TypeScript in the frontmatter. */ +function astroOptions(): Linter.LanguageOptions { + const entry = astro.configs["flat/base"].find((config) => config.name === "astro/base"); + if (entry?.languageOptions === undefined) throw new Error("no astro/base config"); + return entry.languageOptions; +} + +const tester = new RuleTester({ languageOptions: astroOptions() }); + +const page = (template: string): { code: string; filename: string } => ({ + code: `---\nimport Widget from "../Widget.tsx";\n---\n${template}\n`, + filename: "page.astro", +}); + +const unacknowledged = [{ messageId: "unacknowledged" as const }]; + +tester.run("astro-client-load-ack", rule, { + valid: [ + { name: "no directive", ...page("") }, + { name: "client:visible", ...page("") }, + { name: "client:idle", ...page("") }, + { name: "client:only", ...page('') }, + { name: "another namespaced attribute", ...page("") }, + { name: "a plain attribute named load", ...page("") }, + { + name: "acknowledged by the comment right before", + ...page("\n"), + }, + { + name: "acknowledged with no space inside the comment", + ...page(""), + }, + { + name: "acknowledged with a reason over several lines", + ...page( + "\n", + ), + }, + { + name: "acknowledged inside a parent element", + ...page("
\n \n \n
"), + }, + { + name: "each of two is acknowledged", + ...page( + "\n\n\n", + ), + }, + ], + invalid: [ + { name: "bare client:load", ...page(""), errors: unacknowledged }, + { + name: "client:load with other attributes", + ...page(''), + errors: unacknowledged, + }, + { + name: "client:load on an element with children", + ...page("text"), + errors: unacknowledged, + }, + { + name: "a plain comment", + ...page("\n"), + errors: unacknowledged, + }, + { + name: "an acknowledgement of another law", + ...page("\n"), + errors: unacknowledged, + }, + { + name: "an acknowledgement of a law whose number starts with W-28", + ...page("\n"), + errors: unacknowledged, + }, + { + name: "an acknowledgement with no reason", + ...page("\n"), + errors: unacknowledged, + }, + { + name: "the comment after the element", + ...page("\n"), + errors: unacknowledged, + }, + { + name: "an empty comment between the acknowledgement and the element", + ...page("\n\n"), + errors: unacknowledged, + }, + { + name: "the acknowledgement written as text, not as a comment", + ...page("webtops-ack W-28: reason\n"), + errors: unacknowledged, + }, + { + name: "the comment before another element", + ...page("\n

\n"), + errors: unacknowledged, + }, + { + name: "the comment before some text", + ...page("\ntext\n"), + errors: unacknowledged, + }, + { + name: "the comment in a sibling parent", + ...page("\n

"), + errors: unacknowledged, + }, + { + name: "client:load behind a condition", + ...page("{show && }"), + errors: unacknowledged, + }, + { + name: "one of two is acknowledged", + ...page("\n\n"), + errors: unacknowledged, + }, + ], +}); + +describe("W-28's rule", () => { + it("says which law it judges, and reports on the attribute", () => { + expect(rule.meta).toEqual({ + type: "suggestion", + docs: { description: "`client:load` needs an acknowledgement (W-28)" }, + schema: [], + messages: { + unacknowledged: + "client:load ships and runs JavaScript on every page view. Prefer client:visible, client:idle or no directive, or acknowledge it with a comment right before the element: .", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.ts b/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.ts new file mode 100644 index 0000000..6aadba6 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-client-load-ack.ts @@ -0,0 +1,54 @@ +import type { Rule } from "eslint"; +import { ackReason } from "../ack.ts"; +import { attributeName, child, children, kind } from "../ast.ts"; + +/** W-28: `client:load` ships and runs JavaScript on every page view, so it needs an acknowledgement. */ + +const isBlank = (node: unknown): boolean => { + const text = child(node, "value"); + return kind(node) === "JSXText" && typeof text === "string" && text.trim() === ""; +}; + +/** The node just before the element among its siblings, skipping blank text. */ +function nodeBefore(element: unknown): unknown { + const siblings = children(child(element, "parent"), "children"); + return siblings.slice(0, siblings.indexOf(element)).findLast((node) => !isBlank(node)); +} + +/** Whether an HTML comment right before the element acknowledges the law: ``. */ +function acknowledged(element: unknown): boolean { + const before = nodeBefore(element); + const text = child(before, "value"); + return ( + kind(before) === "AstroHTMLComment" && + typeof text === "string" && + ackReason(text, "W-28") !== undefined + ); +} + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "suggestion", + docs: { description: "`client:load` needs an acknowledgement (W-28)" }, + schema: [], + messages: { + unacknowledged: + "client:load ships and runs JavaScript on every page view. Prefer client:visible, client:idle or no directive, or acknowledge it with a comment right before the element: .", + }, + }; + }, + create(context) { + return { + JSXAttribute(node: Rule.Node) { + if (attributeName(node) !== "client:load") return; + const opening: unknown = node.parent; + if (!acknowledged(child(opening, "parent"))) { + context.report({ node, messageId: "unacknowledged" }); + } + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.test.ts b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.test.ts new file mode 100644 index 0000000..75c3649 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.test.ts @@ -0,0 +1,161 @@ +import { RuleTester } from "eslint"; +import type { Linter } from "eslint"; +import astro from "eslint-plugin-astro"; +import { describe, expect, it } from "vitest"; +import rule from "./astro-frontmatter-size.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +/** The language options eslint-plugin-astro gives `.astro` files: the Astro parser, with TypeScript in the frontmatter. */ +function astroOptions(): Linter.LanguageOptions { + const entry = astro.configs["flat/base"].find((config) => config.name === "astro/base"); + if (entry?.languageOptions === undefined) throw new Error("no astro/base config"); + return entry.languageOptions; +} + +const tester = new RuleTester({ languageOptions: astroOptions() }); + +const page = (frontmatter: string, template = "

"): { code: string; filename: string } => ({ + code: `---\n${frontmatter}\n---\n${template}\n`, + filename: "page.astro", +}); + +/** `count` statements, one to a line: `const s1 = 1;` and so on. */ +const statements = (count: number): string => + Array.from( + { length: count }, + (_, index) => `const s${String(index + 1)} = ${String(index)};`, + ).join("\n"); + +const tooLong = (max: number, line: number) => [ + { messageId: "tooLong" as const, data: { max: String(max) }, line }, +]; + +/** One statement of each kind the rule counts. */ +const COUNTED: readonly (readonly [string, string])[] = [ + ["an expression", "run();"], + ["a variable declaration", "const a = 1;"], + ["a function declaration", "function f() {}"], + ["a class declaration", "class A {}"], + ["an if", "if (a) {}"], + ["a for", "for (;;) {}"], + ["a for-in", "for (const k in o) {}"], + ["a for-of", "for (const k of o) {}"], + ["a while", "while (a) {}"], + ["a do-while", "do {} while (a);"], + ["a switch", "switch (a) {}"], + ["a try", "try {} catch {}"], + ["a labeled loop", "a: while (b) {}"], + ["an exported declaration", "export const a = 1;"], +]; + +tester.run("astro-frontmatter-size", rule, { + valid: [ + { name: "an empty frontmatter", ...page("") }, + { name: "no frontmatter", code: "

\n", filename: "page.astro" }, + { name: "ten statements", ...page(statements(10)) }, + { + name: "imports are not logic", + ...page( + `${Array.from({ length: 12 }, (_, i) => `import a${String(i)} from "./a${String(i)}";`).join("\n")}\n${statements(10)}`, + ), + }, + { + name: "type declarations are not logic", + ...page(`interface Props { a: string }\ntype A = string;\n${statements(10)}`), + }, + { + name: "re-exports are not logic", + ...page(`export { a } from "./a";\nexport * from "./b";\n${statements(10)}`), + }, + { name: "empty statements and bare blocks are not logic", ...page(`;\n{}\n${statements(10)}`) }, + { + name: "statements in the template are not frontmatter", + ...page("const a = 1;", `{items.map((item) => {\n${statements(12)}\nreturn item;\n})}`), + }, + { name: "a raised limit", ...page(statements(12)), options: [{ max: 12 }] }, + { + name: "statements in a script are not frontmatter", + ...page("const a = 1;", ``), + }, + ], + invalid: [ + { + name: "eleven statements, reported at the eleventh", + ...page(statements(11)), + errors: tooLong(10, 12), + }, + { + name: "many more than eleven report once", + ...page(statements(25)), + errors: tooLong(10, 12), + }, + { + name: "nested statements count: a function body", + ...page(`${statements(8)}\nfunction f() {\n const a = 1;\n return a;\n}`), + errors: tooLong(10, 12), + }, + { + name: "nested statements count: a branch", + ...page(`${statements(9)}\nif (s1) {\n run();\n}`), + errors: tooLong(10, 12), + }, + { + name: "imports beside eleven statements", + ...page(`import a from "./a";\n${statements(11)}`), + errors: tooLong(10, 13), + }, + { + name: "a lowered limit", + ...page(statements(3)), + options: [{ max: 2 }], + errors: tooLong(2, 4), + }, + { + name: "a limit of zero", + ...page("const zero = 0;"), + options: [{ max: 0 }], + errors: tooLong(0, 2), + }, + ...COUNTED.map(([name, code]) => ({ + name: `${name} counts`, + ...page(code), + options: [{ max: 0 }], + errors: [{ messageId: "tooLong" as const }], + })), + { + name: "return and throw count", + code: "---\nfunction f() {\n throw e;\n}\nfunction g() {\n return 1;\n}\n---\n

\n", + filename: "page.astro", + options: [{ max: 3 }], + errors: [{ messageId: "tooLong" as const, line: 6 }], + }, + { + name: "break and continue count", + ...page("while (a) {\n if (b) {\n break;\n }\n continue;\n}"), + options: [{ max: 3 }], + errors: [{ messageId: "tooLong" as const, line: 6 }], + }, + ], +}); + +describe("W-31's rule", () => { + it("says which law it judges, and takes a limit", () => { + expect(rule.meta).toEqual({ + type: "suggestion", + docs: { description: "Frontmatter logic beyond 10 statements moves to a .ts module (W-31)" }, + schema: [ + { + type: "object", + properties: { max: { type: "integer", minimum: 0 } }, + additionalProperties: false, + }, + ], + messages: { + tooLong: + "The frontmatter has more than {{ max }} statements. Move the logic into a .ts module and import it, so it can be tested.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts new file mode 100644 index 0000000..937233d --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/astro-frontmatter-size.ts @@ -0,0 +1,70 @@ +import type { Rule } from "eslint"; +import { child } from "../ast.ts"; + +/** + * W-31: frontmatter logic beyond 10 statements moves to a `.ts` module, where it can be tested. + * Every statement counts, nested ones too (the body of a function or a branch); imports and type + * declarations do not, and neither does anything in the template, which starts at `AstroFragment`. + */ + +/** The statement types that count. */ +const statementTypes = (): string[] => [ + "ExpressionStatement", + "VariableDeclaration", + "FunctionDeclaration", + "ClassDeclaration", + "IfStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "WhileStatement", + "DoWhileStatement", + "SwitchStatement", + "ReturnStatement", + "ThrowStatement", + "TryStatement", + "BreakStatement", + "ContinueStatement", + "LabeledStatement", +]; + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "suggestion", + docs: { description: "Frontmatter logic beyond 10 statements moves to a .ts module (W-31)" }, + schema: [ + { + type: "object", + properties: { max: { type: "integer", minimum: 0 } }, + additionalProperties: false, + }, + ], + messages: { + tooLong: + "The frontmatter has more than {{ max }} statements. Move the logic into a .ts module and import it, so it can be tested.", + }, + }; + }, + create(context) { + const option: unknown = context.options[0]; + const limit = child(option, "max"); + const max = typeof limit === "number" ? limit : 10; + let inTemplate = false; + let count = 0; + return { + AstroFragment() { + inTemplate = true; + }, + [statementTypes().join(", ")](node: Rule.Node) { + if (inTemplate) return; + count += 1; + if (count === max + 1) { + context.report({ node, messageId: "tooLong", data: { max: String(max) } }); + } + }, + }; + }, +}; + +export default rule; diff --git a/profiles/web-app.yaml b/profiles/web-app.yaml index 1891c44..ada39f9 100644 --- a/profiles/web-app.yaml +++ b/profiles/web-app.yaml @@ -22,6 +22,9 @@ tools: - "typescript" - "typescript-eslint" - "vitest" +# Installed and locked only where the project depends on astro: the parser behind its .astro files (W-28). +astro_tools: + - "eslint-plugin-astro" disabled: package_exports: "not mapped for class: an app publishes no package exports" crap: "milestone M2: native CRAP lands in M2" diff --git a/src/init/astro-tools.test.ts b/src/init/astro-tools.test.ts new file mode 100644 index 0000000..bc86c92 --- /dev/null +++ b/src/init/astro-tools.test.ts @@ -0,0 +1,65 @@ +import { readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { parseLock } from "../lock/format.ts"; +import { TOOL_PINS } from "../lock/pins.ts"; +import { runInit } from "./run.ts"; +import { madeDirs, put, tempDir } from "./test-support.ts"; + +afterAll(() => { + for (const dir of madeDirs()) rmSync(dir, { recursive: true, force: true }); +}); + +const PLUGIN = "eslint-plugin-astro"; +const withAstro = (field: string): string => + JSON.stringify({ name: "p", version: "1.0.0", [field]: { astro: "7.4.12" } }); + +function initInto(className: string, files: Readonly>) { + const dir = tempDir(); + for (const [path, text] of Object.entries(files)) put(dir, path, text); + const outcome = runInit({ className, dir, force: false }); + expect(outcome.code, outcome.problems.join("\n")).toBe(0); + const lock = parseLock(readFileSync(join(dir, "web-tops.lock"), "utf8")); + return { install: outcome.install, locked: lock.ok ? Object.keys(lock.lock) : [] }; +} + +const times = (install: readonly string[]): number => + install.filter((entry) => entry.startsWith(`${PLUGIN}@`)).length; + +describe("R105: init lists the Astro parser among web-app's conditional tools", () => { + it.each(["dependencies", "devDependencies", "peerDependencies"])( + "web-app with astro in %s installs and locks it once, at its pin", + (field) => { + const { install, locked } = initInto("web-app", { "package.json": withAstro(field) }); + expect(install.filter((entry) => entry.startsWith(`${PLUGIN}@`))).toEqual([ + `${PLUGIN}@${Reflect.get(TOOL_PINS, PLUGIN)}`, + ]); + expect(locked).toContain(PLUGIN); + }, + ); + + it("web-app without astro installs and locks no Astro tool", () => { + for (const files of [{}, { "package.json": "{ nope" }]) { + const { install, locked } = initInto("web-app", files); + expect(times(install)).toBe(0); + expect(locked).not.toContain(PLUGIN); + } + }); + + it.each(["ui-components", "ts-library", "node-service"])( + "%s lists it never, even with astro in package.json", + (className) => { + const { install, locked } = initInto(className, { + "package.json": withAstro("dependencies"), + }); + expect(times(install)).toBe(0); + expect(locked).not.toContain(PLUGIN); + }, + ); + + it("astro-site, which lists it among its tools, installs it once with or without astro", () => { + for (const files of [{}, { "package.json": withAstro("dependencies") }]) { + expect(times(initInto("astro-site", files).install)).toBe(1); + } + }); +}); diff --git a/src/init/profile.ts b/src/init/profile.ts index 084c807..e4a63b2 100644 --- a/src/init/profile.ts +++ b/src/init/profile.ts @@ -21,6 +21,8 @@ export interface DropIn { readonly playwright: boolean; readonly eslint: EslintVariant; readonly tools: readonly string[]; + /** Tools the class adds only where the project depends on astro. */ + readonly astro_tools?: readonly string[]; /** Layer key to the reason it is written `enabled: false`. */ readonly disabled: Readonly>; } @@ -48,6 +50,7 @@ const schema = { playwright: { type: "boolean" }, eslint: { enum: ["base", "react", "astro"] }, tools: { type: "array", items: { type: "string", minLength: 1 }, uniqueItems: true }, + astro_tools: { type: "array", items: { type: "string", minLength: 1 }, uniqueItems: true }, disabled: { type: "object", additionalProperties: { type: "string", minLength: 1 } }, }, } as const; diff --git a/src/init/run.ts b/src/init/run.ts index 89c2211..5e510f4 100644 --- a/src/init/run.ts +++ b/src/init/run.ts @@ -34,6 +34,11 @@ export interface InitOutcome { /** What `astro check` needs, locked only where the step runs. */ const ASTRO_TOOLS = ["@astrojs/check", "astro"]; +/** The tools the class adds only where `astro check` runs: the shared ones and its own. */ +function conditionalTools(profile: DropIn, astro: boolean): readonly string[] { + return astro ? [...ASTRO_TOOLS, ...(profile.astro_tools ?? [])] : []; +} + /** What a run decided to write, before it touches the disk. */ interface Plan { readonly files: ReadonlyMap; @@ -98,7 +103,7 @@ function pinTools( ): { lock: Record; install: string[] } | string { const lock: Record = { webtops: pkg.version, node: NODE_RANGE }; const install: string[] = [`web-tops@${pkg.version}`]; - for (const tool of [...profile.tools, ...(astro ? ASTRO_TOOLS : [])]) { + for (const tool of [...profile.tools, ...conditionalTools(profile, astro)]) { const version: unknown = Reflect.get(TOOL_PINS, tool); if (typeof version !== "string") return `profiles/${profile.class}.yaml pins ${tool}, which has no exact version`; diff --git a/src/presets/astro-parser.test.ts b/src/presets/astro-parser.test.ts new file mode 100644 index 0000000..1a60189 --- /dev/null +++ b/src/presets/astro-parser.test.ts @@ -0,0 +1,100 @@ +import type { Linter } from "eslint"; +import { describe, expect, it } from "vitest"; +import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; +import { eslintPreset } from "./eslint.js"; +import type { EslintVariant } from "./eslint.js"; +import { TSCONFIG, bin, configFor, run, scratchProject } from "./test-support-scratch.ts"; + +const ASTRO = { dependencies: { astro: "7.4.12" } }; +const manifest = (extra: object): string => JSON.stringify({ type: "module", ...extra }); + +const hasParser = (config: readonly Linter.Config[]): boolean => + config.some((entry) => entry.name === "astro/base"); + +async function parserFor( + variant: EslintVariant, + className: string, + files: Record, +): Promise { + const dir = scratchProject(files); + return hasParser(await eslintPreset({ variant, tsconfigRootDir: dir, class: className })); +} + +describe("R105: a class that maps an .astro-scoped rule gets the Astro parser where the project uses astro", () => { + it.each(["dependencies", "devDependencies", "peerDependencies"])( + "web-app, a react variant, adds it when astro is in %s", + async (field) => { + const files = { "package.json": manifest({ [field]: { astro: "7.4.12" } }) }; + expect(await parserFor("react", "web-app", files)).toBe(true); + }, + ); + + it("leaves the astro variant as it is, with its own parser", async () => { + const [plain, astro] = [scratchProject(), scratchProject({ "package.json": manifest(ASTRO) })]; + const sizes = await Promise.all( + [plain, astro].map( + async (dir) => + (await eslintPreset({ variant: "astro", tsconfigRootDir: dir, class: "astro-site" })) + .length, + ), + ); + expect(sizes[0]).toBe(sizes[1]); + expect(await parserFor("astro", "astro-site", {})).toBe(true); + }); + + it("leaves it out when the project lists no astro, or its package.json is unreadable", async () => { + for (const files of [ + {}, + { "package.json": manifest({ dependencies: { react: "19.0.0" } }) }, + { "package.json": "{ nope" }, + { "package.json": "null" }, + ]) { + expect(await parserFor("react", "web-app", files)).toBe(false); + } + }); + + it.each([ + ["ui-components", "react"], + ["ts-library", "base"], + ["node-service", "base"], + ] as const)( + "leaves it out of %s, which maps no .astro page rule, even with astro", + async (cls, variant) => { + expect(await parserFor(variant, cls, { "package.json": manifest(ASTRO) })).toBe(false); + }, + ); + + it( + "web-app lints a page: client:load is flagged, an acknowledged one is not, and a script block's env is flagged", + () => { + const page = [ + "---", + "const Widget = (): null => null;", + "---", + "", + "", + "", + "", + "", + ].join("\n"); + const dir = scratchProject({ + "package.json": manifest(ASTRO), + "web-tops.yaml": "class: web-app\n", + "eslint.config.js": configFor("react"), + "tsconfig.json": TSCONFIG, + "src/page.astro": page, + }); + const result = run(bin("eslint"), ["--format", "json", "src/page.astro"], dir); + const reports: unknown = JSON.parse(result.stdout); + const messages = JSON.stringify(reports); + expect(messages).not.toContain('"fatal":true'); + expect(messages.split("webtops/astro-client-load-ack")).toHaveLength(2); + expect(messages.split("webtops/public-env-only")).toHaveLength(2); + expect(messages).not.toContain("webtops/astro-assets-image"); + expect(messages).not.toContain("webtops/astro-frontmatter-size"); + }, + REAL_TOOL_TIMEOUT, + ); +}); diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts index 21a3903..4a923bb 100644 --- a/src/presets/class-rules.test.ts +++ b/src/presets/class-rules.test.ts @@ -1,10 +1,12 @@ -import { readFileSync, readdirSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { readFileSync, readdirSync, realpathSync } from "node:fs"; +import { join, relative, resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { parse } from "yaml"; import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; +import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; import { eslintPreset } from "./eslint.js"; import type { EslintVariant } from "./eslint.js"; +import { TSCONFIG, bin, configFor, run, scratchProject } from "./test-support-scratch.ts"; const ROOT = resolve(import.meta.dirname, "../.."); const PREFIX = "webtops/"; @@ -81,3 +83,57 @@ describe("R98: a class's preset enables exactly the plugin rules its laws map", expect(withTailwind).toEqual(["astro-site", "web-app"]); }); }); + +/** One file of each kind a class's rules can match: a module, a React module and an Astro page. */ +const KINDS = { + "src/a.ts": "export const a: number = 1;\n", + "src/c.tsx": "export const c = (): null => null;\n", + "src/page.astro": [ + "---", + "const Widget = (): null => null;", + "---", + "", + "", + ].join("\n"), +}; + +/** ESLint's report for every file under src, as JSON. */ +function lintAll(dir: string): unknown[] { + const parsed: unknown = JSON.parse(run(bin("eslint"), ["--format", "json", "src"], dir).stdout); + return Array.isArray(parsed) ? parsed : []; +} + +function pathOf(dir: string, report: unknown): string { + const path = field(report, "filePath"); + return typeof path === "string" ? relative(realpathSync(dir), path) : ""; +} + +const messagesOf = (report: unknown): unknown[] => list(report, "messages"); + +describe("R105: a class's preset can parse every file kind its rules match", () => { + it.each(CLASSES)( + "%s: its project lints a module, a React module and a page with no parse error", + (cls) => { + const dir = scratchProject({ + "package.json": JSON.stringify({ type: "module", dependencies: { astro: "7.4.12" } }), + "web-tops.yaml": `class: ${cls}\n`, + "eslint.config.js": configFor(variantOf(cls)), + "tsconfig.json": TSCONFIG, + ...KINDS, + }); + const reports = lintAll(dir); + const mapsPages = mappedRules(cls).some((rule) => rule.startsWith(`${PREFIX}astro-`)); + expect(reports.map((report) => pathOf(dir, report)).sort()).toEqual( + mapsPages ? Object.keys(KINDS).sort() : ["src/a.ts", "src/c.tsx"], + ); + for (const report of reports) { + const fatal = messagesOf(report).filter((message) => field(message, "fatal") === true); + expect(fatal, pathOf(dir, report)).toEqual([]); + } + const page = reports.find((report) => pathOf(dir, report) === "src/page.astro"); + const ruleIds = messagesOf(page).map((message) => field(message, "ruleId")); + expect(ruleIds.includes(`${PREFIX}astro-client-load-ack`)).toBe(mapsPages); + }, + REAL_TOOL_TIMEOUT, + ); +}); diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 03fa48c..05bff82 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -75,6 +75,8 @@ async function loadWebtops() { const webtops = await loadWebtops(); +const ASTRO = ["**/*.astro"]; + /** eslint-plugin-astro lints each `", + "", + ].join("\n"), + }); + const page = run(bin("eslint"), ["src/page.astro"], dir); + for (const rule of [ + "astro-assets-image", + "astro-client-load-ack", + "astro-frontmatter-size", + ]) { + expect(page.output, rule).toContain(`webtops/${rule}`); + } + expect(page.output.split("webtops/public-env-only")).toHaveLength(2); + expect(page.output).toMatch(/\n\s+21:27\s+error\s+SECRET[^\n]*webtops\/public-env-only/u); + }, + REAL_TOOL_TIMEOUT, + ); + it("exports plain JavaScript and JSON, which Node loads from inside node_modules", () => { const exported: unknown = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); const text = JSON.stringify(exported); @@ -247,18 +254,22 @@ describe("the ESLint preset", () => { const W36 = "webtops/no-unsanitized-html"; const W37 = "webtops/public-env-only"; const W23 = "webtops/complete-tailwind-classes"; + const W28 = "webtops/astro-client-load-ack"; + const W30 = "webtops/astro-assets-image"; + const W31 = "webtops/astro-frontmatter-size"; + const ALL = [W36, W37, W23, W28, W30, W31]; it.each([ ["ts-library", "base", [W36]], ["node-service", "base", [W36]], ["ui-components", "react", [W36, W37]], - ["web-app", "react", [W36, W37, W23]], - ["astro-site", "astro", [W36, W37, W23]], + ["web-app", "react", [W36, W37, W23, W28]], + ["astro-site", "astro", ALL], ["cli", "base", []], ] as const)("class %s (%s) enables exactly the plugin rules %j", async (cls, variant, has) => { const config = await eslintPreset({ variant, tsconfigRootDir: "", class: cls }); const rules = errorRules(config); - for (const name of [W36, W37, W23]) { + for (const name of ALL) { if (has.some((wanted) => wanted === name)) expect(rules, name).toContain(name); else expect(rules, name).not.toContain(name); } @@ -268,13 +279,13 @@ describe("the ESLint preset", () => { it("reads the class from the project's web-tops.yaml, and falls back to the loosest class", async () => { const root = scratchProject({ "web-tops.yaml": 'protocol: "0.3.0"\nclass: "web-app"\n' }); const declared = errorRules(await eslintPreset({ variant: "react", tsconfigRootDir: root })); - expect([W36, W37, W23].filter((name) => declared.has(name))).toEqual([W36, W37, W23]); + expect(ALL.filter((name) => declared.has(name))).toEqual([W36, W37, W23, W28]); const none = scratchProject(); const fallback = errorRules(await eslintPreset({ variant: "react", tsconfigRootDir: none })); - expect([W36, W37, W23].filter((name) => fallback.has(name))).toEqual([W36]); + expect(ALL.filter((name) => fallback.has(name))).toEqual([W36]); const unquoted = scratchProject({ "web-tops.yaml": "class: ui-components\n" }); const read = errorRules(await eslintPreset({ variant: "react", tsconfigRootDir: unquoted })); - expect([W36, W37, W23].filter((name) => read.has(name))).toEqual([W36, W37]); + expect(ALL.filter((name) => read.has(name))).toEqual([W36, W37]); }); it("scopes public-env-only (W-37) to the client modules and the