Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions WEB_TOPS.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ have different budgets.
| `size-limit` per entry | required | required | no | no | no |
| HTML validity, axe, links | no | on fixture pages | required | required | no |
| JS per page or route (brotli) | n/a | n/a | 0 KB unless the page has islands; ≤ 50 KB with | ≤ 170 KB per route | n/a |
| Extra laws | W-18 | W-18, W-22, W-37, W-47; W-27 when Astro | W-20–W-31, W-37, W-42–W-46, W-47 | W-20–W-29, W-37, W-42–W-46, W-47; W-27 when Astro | W-06 strict |
| Extra laws | W-18 | W-18, W-22, W-37, W-47; W-27 when Astro | W-20–W-31, W-37, W-42–W-46, W-47, W-49 | W-20–W-29, W-37, W-42–W-46, W-47; W-27 when Astro | W-06 strict |
| Required layers | hygiene, tests, coverage, crap, mutation, build-output, laws | hygiene, tests, coverage, crap, mutation, build-output, laws | hygiene, tests, coverage, crap, mutation, build-output, laws | hygiene, tests, coverage, crap, mutation, build-output, laws | hygiene, tests, coverage, crap, mutation, laws |

There is one CRAP cap per class, the same for every author; there is no per-author cap. The cap
Expand Down Expand Up @@ -707,7 +707,7 @@ law: the bad twin breaks each enabled rule on purpose, with an `// expect: <rule
line, and the clean twin stays quiet. A test fails if a marked rule stays quiet on the bad twin or
an unmarked one fires. Custom ESLint rules are tested with ESLint's `RuleTester`.

### 8.2 Law catalog (draft: 48 laws, W-01…W-48)
### 8.2 Law catalog (draft: 49 laws, W-01…W-49)

Severity: **R** = a break is `refuse`, **A** = a break needs an acknowledgement or is `ack-missing`. ✓ = judged in v0.1. Law IDs from the TS-TOPS sketch
(T-NN) are noted where they map. Laws added after W-46 take the next number; ids are not renumbered by
Expand Down Expand Up @@ -778,6 +778,7 @@ These tables are generated from `laws/W-NN.yaml` (§8.3). Edit the file, not the
| W-29 | Each page or route stays within its JS and CSS byte budget | R | an: `dist/` reader | ✓ |
| W-30 | Images go through `astro:assets` (`<Image>`, `<Picture>`) with dimensions | A | an | |
| W-31 | Frontmatter logic beyond 10 statements moves to a `.ts` module, where it can be tested | A | an | |
| W-49 | Astro components use the Astro API correctly: no deprecated APIs, conflicting directives or exports from components | R | tl: `eslint-plugin-astro` `recommended` | |

**Tests, suppressions, security, build**

Expand Down Expand Up @@ -814,7 +815,7 @@ the readers.
| W-47 | React hooks follow the rules of hooks: called only at the top level of a component or custom hook, with complete dependency arrays | R | tl: `eslint-plugin-react-hooks` `rules-of-hooks`, `exhaustive-deps` | |
| W-48 | No unused exports, files or dependencies | A | tbd: `knip` over all three (M3) | |

**v0.1 target:** 26 of 48 laws judged. Most are delegated, because the TypeScript and web
**v0.1 target:** 26 of 49 laws judged. Most are delegated, because the TypeScript and web
ecosystem already ships the checks. Class-specific laws are `skip` for other classes.

### 8.3 Law metadata
Expand Down
4 changes: 2 additions & 2 deletions laws/W-19.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ classes: [ts-library, ui-components, astro-site, web-app, node-service]
reader:
kinds: [tl]
text: "tl: `dependency-cruiser`"
rules: []
rules:
- { tool: dependency-cruiser, name: "no-optional-peer-import" }
judged: v0.1
rationale: "An optional peer imported from an entry that does not declare it breaks installs that skip the peer."
fix: "Import the peer only from entries that declare it, or declare it for the entry."
note: "The dependency-cruiser rule lands with its reader in M3."
4 changes: 2 additions & 2 deletions laws/W-39.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ classes: [ts-library, ui-components, astro-site, web-app, node-service]
reader:
kinds: [tl]
text: "tl: secrets scanner **[verify]**"
rules: []
rules:
- { tool: secretlint, name: "@secretlint/secretlint-rule-preset-recommend" }
judged: m3
rationale: "A secret in source or a fixture is a leaked credential, in history too."
fix: "Remove it, rotate it, and load it from the environment."
note: "The scanner is chosen in M3; no rule names it yet."
3 changes: 2 additions & 1 deletion laws/W-41.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ classes: [ts-library, ui-components, astro-site, web-app, node-service]
reader:
kinds: [an]
text: "an"
rules: []
rules:
- { tool: lock, name: "web-tops.lock" }
judged: v0.1
rationale: "A tool version that differs from the lock makes a gate result mean something else on another machine."
fix: "Run `webtops lock --update` after a deliberate change, or reinstall the locked version."
22 changes: 22 additions & 0 deletions laws/W-49.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# W-49: the source of its row in WEB_TOPS.md section 8.2 (`webtops laws sync` regenerates the table from these files).
id: W-49
title: "Astro components use the Astro API correctly: no deprecated APIs, conflicting directives or exports from components"
family: "Astro"
severity: R
classes: [astro-site]
reader:
kinds: [tl]
text: "tl: `eslint-plugin-astro` `recommended`"
rules:
- { tool: eslint, name: "astro/missing-client-only-directive-value" }
- { tool: eslint, name: "astro/no-conflict-set-directives" }
- { tool: eslint, name: "astro/no-deprecated-astro-canonicalurl" }
- { tool: eslint, name: "astro/no-deprecated-astro-fetchcontent" }
- { tool: eslint, name: "astro/no-deprecated-astro-resolve" }
- { tool: eslint, name: "astro/no-deprecated-getentrybyslug" }
- { tool: eslint, name: "astro/no-exports-from-components" }
- { tool: eslint, name: "astro/no-prerender-export-outside-pages" }
- { tool: eslint, name: "astro/no-unused-define-vars-in-style" }
judged: m3
rationale: "A removed API, two directives that fight over the same content, or an export from a component breaks the build or the page."
fix: "Use the current Astro API, set content with one directive, and move the export out of the component."
18 changes: 9 additions & 9 deletions src/cli/laws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,27 +76,27 @@ const idsOf = (out: string): string[] =>
.map((line) => line.slice(0, 4 + 1).trim());

describe("webtops laws list (G1b)", () => {
it("lists all 48 laws with no filter", async () => {
it("lists all 49 laws with no filter", async () => {
const { code, out } = await laws(["list"]);
expect(code).toBe(0);
expect(out.startsWith("48 of 48 laws\n")).toBe(true);
expect(idsOf(out)).toHaveLength(48);
expect(out.startsWith("49 of 49 laws\n")).toBe(true);
expect(idsOf(out)).toHaveLength(49);
});

it("lists the laws a class requires, 22 for a ts-library and 21 for a node-service", async () => {
const tsLibrary = await laws(["list", "--class", "ts-library", "--required"]);
expect(tsLibrary.out.split("\n")[0]).toBe("22 of 48 laws (class ts-library, required)");
expect(tsLibrary.out.split("\n")[0]).toBe("22 of 49 laws (class ts-library, required)");
const service = await laws(["list", "--class=node-service", "--required"]);
expect(service.out.split("\n")[0]).toBe("21 of 48 laws (class node-service, required)");
expect(service.out.split("\n")[0]).toBe("21 of 49 laws (class node-service, required)");
expect(idsOf(service.out)).not.toContain("W-18");
});

it("lists the laws a class maps with --class alone, and the judged laws with --required alone", async () => {
expect((await laws(["list", "--class", "astro-site"])).out.split("\n")[0]).toBe(
"47 of 48 laws (class astro-site)",
"48 of 49 laws (class astro-site)",
);
expect((await laws(["list", "--required"])).out.split("\n")[0]).toBe(
"33 of 48 laws (required)",
"34 of 49 laws (required)",
);
});

Expand Down Expand Up @@ -269,7 +269,7 @@ describe("bun src/cli/main.ts laws: the registered command, in a real process",
it("lists the laws a class requires, exit 0", () => {
const { status, stdout } = spawnCli("list", "--class", "ts-library", "--required");
expect(status).toBe(0);
expect(stdout.split("\n")[0]).toBe("22 of 48 laws (class ts-library, required)");
expect(stdout.split("\n")[0]).toBe("22 of 49 laws (class ts-library, required)");
});

it("exits 2 for a law that is not in the catalog, and names it", () => {
Expand All @@ -287,6 +287,6 @@ describe("laws is registered with the command dispatcher", () => {
it("run hands `laws list` to the laws command, in this process", async () => {
const { io, out } = capture();
expect(await run(["laws", "list", "--class", "ts-library", "--required"], io)).toBe(0);
expect(out().split("\n")[0]).toBe("22 of 48 laws (class ts-library, required)");
expect(out().split("\n")[0]).toBe("22 of 49 laws (class ts-library, required)");
});
});
2 changes: 1 addition & 1 deletion src/config/profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export const PROFILES: readonly Profile[] = [
layers: ["html_validate", "axe", "rendered", "themes"],
steps: [...CORE_STEPS, "astro_check", "stylelint"],
conditionalSteps: [],
extraLaws: [...lawIds(20, 31), "W-37", ...RENDERED_LAWS, "W-47"],
extraLaws: [...lawIds(20, 31), "W-37", ...RENDERED_LAWS, "W-47", "W-49"],
conditionalLaws: [],
},
{
Expand Down
4 changes: 2 additions & 2 deletions src/config/required.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ describe("G3d: section 5.2 states how the caps work (X2)", () => {
});

describe("R55: W-47 and W-48 join the catalog, unjudged", () => {
it("counts as many laws as section 8.2 lists, 48", () => {
it("counts as many laws as section 8.2 lists, 49", () => {
const rows = spec.split("\n").filter((line) => /^\| W-\d+ /.test(line));
expect(LAW_COUNT).toBe(48);
expect(LAW_COUNT).toBe(49);
expect(rows).toHaveLength(LAW_COUNT);
});

Expand Down
8 changes: 5 additions & 3 deletions src/config/required.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export const JUDGED_LAWS: readonly string[] = [
"W-41",
];

/** W-01 to W-48 (WEB_TOPS.md section 8.2). */
export const LAW_COUNT = 48;
/** W-01 to W-49 (WEB_TOPS.md section 8.2). */
export const LAW_COUNT = 49;
const ALL_LAWS = Array.from(
{ length: LAW_COUNT },
(_, index) => `W-${String(index + 1).padStart(2, "0")}`,
Expand All @@ -57,7 +57,9 @@ const BUILD_OUTPUT: readonly LayerKey[] = [

/** Every law the class maps: the ones no class gates, and the class's own (W-27 only with Astro). */
export function mappedLaws(profile: Profile, project: Project): readonly string[] {
const own = [...profile.extraLaws, ...(project.dependsOnAstro ? profile.conditionalLaws : [])];
const own = project.dependsOnAstro
? [...profile.extraLaws, ...profile.conditionalLaws]
: profile.extraLaws;
return ALL_LAWS.filter((id) => !GATED.has(id) || own.includes(id));
}

Expand Down
11 changes: 6 additions & 5 deletions src/init/catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,16 +109,17 @@ describe("G8a: section 7 names the presets, page JavaScript and axe's settings",
});

describe("G8b: section 8 corrections and new laws", () => {
it("states 48 laws, with one row for each id from W-01 to W-48", () => {
expect(section82).toContain("draft: 48 laws, W-01…W-48");
it("states 49 laws, with one row for each id from W-01 to W-49", () => {
expect(section82).toContain("draft: 49 laws, W-01…W-49");
const ids = section82
.split("\n")
.map((line) => /^\| (W-\d+) \|/.exec(line)?.[1])
.filter((id) => id !== undefined);
expect(ids).toEqual(
Array.from({ length: 48 }, (_, i) => `W-${String(i + 1).padStart(2, "0")}`),
// A family's laws sit together, so W-49 follows W-31 in the Astro table: the set is W-01 to W-49.
expect([...ids].sort()).toEqual(
Array.from({ length: 49 }, (_, i) => `W-${String(i + 1).padStart(2, "0")}`),
);
expect(section82).toContain("**v0.1 target:** 26 of 48 laws judged");
expect(section82).toContain("**v0.1 target:** 26 of 49 laws judged");
});

it("W-06 no longer says FormData and storage return any", () => {
Expand Down
8 changes: 5 additions & 3 deletions src/laws/catalog/catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const loaded = loadCatalog(join(ROOT, "laws"));
if (!loaded.ok) throw new Error(loaded.problems.map((found) => found.message).join("; "));
const laws: readonly Law[] = loaded.laws;

const LAW_COUNT = 48;
const LAW_COUNT = 49;

/** The tick column of section 8.2 (v0.1): the laws judged today. */
const TICKED = [
Expand Down Expand Up @@ -73,11 +73,11 @@ const ids = (shown: readonly { id: string }[]): string[] => shown.map((law) => l
const numbered = (list: string): string[] => list.split(/[ ,]+/u).filter((word) => word !== "");

describe("the kit's catalog: laws/W-NN.yaml (G1a)", () => {
it("holds a valid file for each of the 48 laws, W-01 to W-48, in order", () => {
it("holds a valid file for each of the 49 laws, W-01 to W-49, in order", () => {
expect(ids(laws)).toEqual(
Array.from({ length: LAW_COUNT }, (_, index) => `W-${String(index + 1).padStart(2, "0")}`),
);
expect(laws).toHaveLength(48);
expect(laws).toHaveLength(LAW_COUNT);
});

it("puts every law in a family the text of section 8.2 has a table for", () => {
Expand Down Expand Up @@ -126,6 +126,7 @@ describe("the catalog agrees with the profiles and with section 5.2 (G1b)", () =
"W-37",
"W-39",
"W-48",
"W-49",
]);
});

Expand Down Expand Up @@ -249,6 +250,7 @@ describe("the rules a law names, for the law probe", () => {
"dependency-cruiser",
"eslint",
"html-validate",
"lock",
"publint",
"stylelint",
"tsc",
Expand Down
2 changes: 1 addition & 1 deletion src/laws/catalog/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const ids = (shown: readonly { id: string }[]): string[] => shown.map((law) => l

describe("select", () => {
it("is every law with no filter", () => {
expect(select(laws, { cls: undefined, required: false })).toHaveLength(48);
expect(select(laws, { cls: undefined, required: false })).toHaveLength(49);
});

it("is the laws a class maps, required or not", () => {
Expand Down
13 changes: 13 additions & 0 deletions src/presets/depcruise.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// resolver reads each package's `exports`, so an import through a path it does not expose cannot be
// resolved and fails at no-unresolvable. A rule on the resolved path would flag every normal import,
// because a package's own types resolve into its dist.
// W-19: React and R3F, when a package declares them as peers, are imported only from its `react`
// entries and its `adapters`, the only places that may need them (WEB_TOPS.md section 8.2).
/** @type {import("dependency-cruiser").IConfiguration} */
module.exports = {
forbidden: [
Expand All @@ -21,6 +23,17 @@ module.exports = {
from: {},
to: { couldNotResolve: true },
},
{
name: "no-optional-peer-import",
comment:
"W-19: an optional peer (React, R3F) is imported only from a react entry or an adapter.",
severity: "error",
from: { pathNot: "(^|/)(react|adapters)(/|\\.[cm]?[jt]sx?$)" },
to: {
dependencyTypes: ["npm-peer"],
path: "(^|/)node_modules/(react|react-dom|three|@react-three/[^/]+)(/|$)",
},
},
],
options: {
doNotFollow: { path: "node_modules" },
Expand Down
116 changes: 116 additions & 0 deletions src/presets/depcruise.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts";

const ROOT = resolve(import.meta.dirname, "../..");
const made: string[] = [];
afterAll(() => {
for (const dir of made) rmSync(dir, { recursive: true, force: true });
});

/** A package that declares `react` as a peer, with `react` installed, and these files under src. */
function peerPackage(files: Readonly<Record<string, string>>, peer = "react"): string {
const dir = mkdtempSync(join(tmpdir(), "wt-depcruise-"));
made.push(dir);
const all: Record<string, string> = {
"package.json": JSON.stringify({
name: "probe",
type: "module",
peerDependencies: { [peer]: "*" },
peerDependenciesMeta: { [peer]: { optional: true } },
}),
"tsconfig.json": JSON.stringify({
compilerOptions: { module: "preserve", moduleResolution: "bundler", noEmit: true },
include: ["src"],
}),
[`node_modules/${peer}/package.json`]: JSON.stringify({ name: peer, main: "index.js" }),
[`node_modules/${peer}/index.js`]: "module.exports = {};\n",
...files,
};
for (const [path, text] of Object.entries(all)) {
mkdirSync(dirname(join(dir, path)), { recursive: true });
writeFileSync(join(dir, path), text);
}
symlinkSync(join(ROOT, "node_modules", "typescript"), join(dir, "node_modules", "typescript"));
return dir;
}

function cruise(dir: string): { status: number | null; output: string } {
const bin = join(ROOT, "node_modules", ".bin", "depcruise");
const config = join(ROOT, "src", "presets", "depcruise.cjs");
const result = spawnSync(bin, ["--config", config, "src"], { cwd: dir, encoding: "utf8" });
return { status: result.status, output: `${result.stdout}${result.stderr}` };
}

const IMPORT = 'import * as peer from "react";\nexport const value = peer;\n';
const NAME = "no-optional-peer-import";

describe("W-19: web-tops/depcruise keeps an optional peer to the entries that declare it", () => {
it(
"flags an import of a peer from a file outside the react entries and the adapters",
() => {
const result = cruise(peerPackage({ "src/index.ts": IMPORT }));
expect(result.status, result.output).toBe(1);
expect(result.output).toContain(NAME);
expect(result.output).toContain("src/index.ts");
},
REAL_TOOL_TIMEOUT,
);

it.each(["src/react/index.ts", "src/react.ts", "src/adapters/three.ts", "src/lib/react/a.tsx"])(
"lets %s import it",
(file) => {
const result = cruise(peerPackage({ [file]: IMPORT }));
expect(result.output).not.toContain(NAME);
expect(result.status, result.output).toBe(0);
},
REAL_TOOL_TIMEOUT,
);

it(
"flags the R3F and three peers too",
() => {
const result = cruise(
peerPackage(
{ "src/index.ts": 'import * as peer from "three";\nexport const v = peer;\n' },
"three",
),
);
expect(result.output).toContain(NAME);
},
REAL_TOOL_TIMEOUT,
);

it(
"leaves a package that depends on react directly alone",
() => {
const dir = peerPackage({ "src/index.ts": IMPORT });
writeFileSync(
join(dir, "package.json"),
JSON.stringify({ name: "probe", type: "module", dependencies: { react: "*" } }),
);
const result = cruise(dir);
expect(result.output).not.toContain(NAME);
expect(result.status, result.output).toBe(0);
},
REAL_TOOL_TIMEOUT,
);

it(
"leaves another peer alone",
() => {
const result = cruise(
peerPackage(
{ "src/index.ts": 'import * as peer from "left-pad";\nexport const v = peer;\n' },
"left-pad",
),
);
expect(result.output).not.toContain(NAME);
expect(result.status, result.output).toBe(0);
},
REAL_TOOL_TIMEOUT,
);
});
Loading
Loading