@terpjs/eslint-boundaries 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "id": "frontend/no-inline-styling",
3
3
  "surface": "frontend",
4
- "title": "style and className attributes are refused in app modules",
5
- "intent": "A style or className attribute is a side channel into hand-authored CSS that drifts per screen; styling flows from the app's design tokens and sanctioned layout primitives only. The refused attributes are declared in restricted-surface.json (restrictedAttributes).",
4
+ "title": "App classes come from local CSS Modules",
5
+ "intent": "Paint follows the palette, and a framework control keeps the styling and focus treatment it ships with, so a control looks and behaves the same in every app. Inline style and a hardcoded colour in app script paint around the palette, and a class on a framework control, or ink and type an element passes down to the framework component it holds, restyle what the framework owns. So a CSS Module's binding is read only in a className on a native element, naming a class the module defines or choosing between two of them, and a class that sets inherited ink or type goes only on an element that holds the app's own text; a framework control is configured through its props. A style attribute, a className attribute that names no module class, any other read of the binding, and a #hex colour in a string literal in app script are refused.",
6
6
  "layer": "static-portable",
7
7
  "enforcement": [
8
+ {
9
+ "kind": "build-time",
10
+ "tool": "@terpjs/eslint-boundaries",
11
+ "ref": "terp/no-inline-styling",
12
+ "reported_as": "terp/no-inline-styling"
13
+ },
8
14
  {
9
15
  "kind": "build-time",
10
16
  "tool": "@terpjs/eslint-boundaries",
@@ -12,11 +18,12 @@
12
18
  "reported_as": "no-restricted-syntax"
13
19
  }
14
20
  ],
15
- "reference": "Layout via Stack, DetailList and the page archetypes from @terpjs/react-core; theming via the app's token source.",
21
+ "reference": "Layout via Stack, Grid, DetailList and the page archetypes from @terpjs/react-core. A layout a component owns: import styles from \"./Board.module.css\" and className={styles.board}, or className={active ? styles.active : styles.board}, on a native element in the body of a plain Page, with ink and type on the element that holds the app's own text. Paint via the design tokens.",
16
22
  "opt_out": "// terp-allow-no-inline-styling: <reason>",
17
23
  "runtime": {
18
- "applicability": "not-applicable",
19
- "rationale": "style/className are authoring-surface attributes: the token pipeline itself emits inline styles and class names into the built DOM, so their presence at runtime is legitimate and unattributable to app authorship."
24
+ "applicability": "deferred",
25
+ "rationale": "Most of the rule is erased before the app serves: react-core sets inline styles of its own, and a CSS Module's class is a hashed name like any other in the built DOM, so neither a style nor a class on a native element can be attributed to app authorship there. One part can be. Every react-core control's root carries a data-terp marker and react-core renders no class on it, save the router's active link, so a class on a framework control is observable in the running page, on the seam the archetype slot check (verifySlotChildren) already walks by those markers. A refusal there has not shipped.",
26
+ "tracking": "docs/decisions/0217-app-components-can-own-a-scoped-stylesheet.md in the reference implementation, the Consequences section: a runtime refusal of a class on a data-terp element, beside verifySlotChildren, flips this entry to required."
20
27
  },
21
28
  "restricted_surface": [
22
29
  "restrictedAttributes"
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "id": "frontend/no-style-imports",
3
3
  "surface": "frontend",
4
- "title": "Module-authored stylesheets are refused",
5
- "intent": "Importing a stylesheet from an app module reintroduces per-screen CSS; theming flows from the app's token source only. The refused stylesheet extensions are declared in restricted-surface.json (styleImportExtensions).",
4
+ "title": "Component styles come from a local CSS Module",
5
+ "intent": "Paint follows the palette and a stylesheet reaches only what its component owns. A global stylesheet, a library's included, paints outside the palettes and reaches every element on the page, so only the bootstrap imports global ones, and only the token pipeline's three. A component may statically default-import its sibling Name.module.css, whose rules select its own classes, named as script identifiers, group them in @media, @container or @supports, and set layout and typography properties and paint. Paint takes a palette role: an ink for color, a surface for a background (one of the three the framework sets its own components on), a border token for a border, chosen so that every admitted ink over every admitted surface is a text pair the palette declares and holds to AA in every theme. A list marker takes a keyword, never copy. Only the exact sibling spelling ./Name.module.css (letters, digits, _, . and - in the name, no query, this letter case) is read, and for it the import opt-out covers the import's form only: a finding inside the module names its CSS line and survives a marker on the import. Any other spelling (another directory, a query, another letter case) is refused as a path, and a marker that waives that refusal leaves the file unread. Global selectors, imports, cross-file composition and a stylesheet loaded through import() or import.meta.glob are refused.",
6
6
  "layer": "static-portable",
7
7
  "enforcement": [
8
+ {
9
+ "kind": "build-time",
10
+ "tool": "@terpjs/eslint-boundaries",
11
+ "ref": "terp/no-style-imports",
12
+ "reported_as": "terp/no-style-imports"
13
+ },
8
14
  {
9
15
  "kind": "build-time",
10
16
  "tool": "@terpjs/eslint-boundaries",
@@ -20,5 +26,6 @@
20
26
  "restricted_surface": [
21
27
  "styleImportExtensions"
22
28
  ],
23
- "corpus": true
29
+ "corpus": true,
30
+ "reference": "A component's own layout: import styles from \"./Board.module.css\", one static default binding, beside the component, with className={styles.board} on a native element. Ink: var(--color-fg-default), var(--color-fg-muted), var(--color-fg-subtle). Surfaces: var(--color-bg-canvas), var(--color-bg-surface), var(--color-bg-subtle). Borders: var(--color-border-default), var(--color-border-strong), var(--color-border-subtle). Otherwise Stack, Grid and the page archetypes from @terpjs/react-core. The bootstrap imports @terpjs/contract/tokens.css, ./house-style.css and ./theme.css."
24
31
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@terpjs/eslint-boundaries",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "type": "module",
5
- "description": "Terp frontend boundary rules (as data) + the ESLint adapter, over all app source under src/: no cross-module imports, no package internals, design-token-only styling (no style/className/stylesheets; the bootstrap alone loads the token pipeline), token-styled components for raw HTML tags, router-only in-app links, generated-client-only, and browser XSS/navigation sink bans. Strict-only (no modes); governed opt-outs via terp-allow markers + the escape-hatch budget ratchet (terp-boundaries-budget).",
5
+ "description": "Terp frontend boundary rules (as data) + the ESLint adapter, over all app source under src/: no cross-module imports, no package internals, component-scoped CSS Modules and a shared token pipeline, token-styled components for raw HTML tags, router-only in-app links, generated-client-only, and browser XSS/navigation sink bans. Strict-only (no modes); governed opt-outs via terp-allow markers + the escape-hatch budget ratchet (terp-boundaries-budget).",
6
6
  "main": "./src/index.js",
7
7
  "bin": {
8
8
  "terp-boundaries-budget": "./src/budget.js",
@@ -27,11 +27,12 @@
27
27
  "eslint": ">=9"
28
28
  },
29
29
  "dependencies": {
30
- "typescript-eslint": "^8.72.1"
30
+ "postcss": "^8.5.32",
31
+ "typescript-eslint": "^8.72.2"
31
32
  },
32
33
  "devDependencies": {
33
- "@terpjs/spec": "0.46.0",
34
- "eslint": "^10.14.0",
34
+ "@terpjs/spec": "0.50.0",
35
+ "eslint": "^10.15.0",
35
36
  "vitest": "^5.1.0"
36
37
  },
37
38
  "license": "Apache-2.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "title": "Terp Standard - the refused raw frontend surface",
3
- "description": "The normative declaration of the raw browser primitives an app module must not author directly. The prohibition is the portable part of the rules that cite this file (token-styled-elements, no-inline-styling, generated-client-only, no-style-imports, no-deep-imports); which sanctioned component or helper answers each primitive is per-stack configuration, recorded non-normatively in the catalog entry's 'reference' field. A checker realises this file for its language; the reference adapter's BOUNDARY_SPEC is parity-tested against it.",
3
+ "description": "The normative declaration of the raw browser primitives an app module must not author directly. For className and stylesheet imports, the scoped module allowance is defined by the corresponding catalog entries. The prohibition is the portable part of the rules that cite this file (token-styled-elements, no-inline-styling, generated-client-only, no-style-imports, no-deep-imports); which sanctioned component or helper answers each primitive is per-stack configuration, recorded non-normatively in the catalog entry's 'reference' field. A checker realises this file for its language; the reference adapter's BOUNDARY_SPEC is parity-tested against it.",
4
4
  "restrictedElements": ["button", "dialog", "form", "input", "meter", "select", "table", "textarea"],
5
5
  "restrictedAttributes": ["className", "style"],
6
6
  "restrictedGlobals": ["EventSource", "WebSocket", "XMLHttpRequest", "fetch"],
package/src/budget.js CHANGED
@@ -45,7 +45,7 @@ function parsedReviewDate(value) {
45
45
  }
46
46
 
47
47
  /** Every app-authored `src/**` source file under *root*, recursively. */
48
- function sourceFiles(root) {
48
+ export function sourceFiles(root) {
49
49
  const sourceRoot = path.join(root, "src");
50
50
  if (!fs.existsSync(sourceRoot)) {
51
51
  return [];
@@ -0,0 +1,403 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import postcss from "postcss";
5
+
6
+ // A sibling file keeps the stylesheet in the component's module boundary. The name holds no
7
+ // slash, so the file sits beside the component; dots are allowed (`Board.lanes.module.css`).
8
+ export const localModuleSource = String.raw`\./[A-Za-z0-9_][A-Za-z0-9_.-]*\.module\.css`;
9
+ const localModule = new RegExp(`^${localModuleSource}$`);
10
+
11
+ // CSS Modules scope class names, but also accept global selectors, cross-file composition
12
+ // and imports. Accept a small stylesheet grammar whose rules target local classes only.
13
+ // A class is named as a script identifier: Vite exports `.task-card` as "task-card", which
14
+ // `className={styles.x}` cannot name, so a hyphenated class would be one no element can use.
15
+ const states = String.raw`(?::(?:focus|focus-visible|focus-within|hover|active|disabled))*`;
16
+ const selector = new RegExp(String.raw`^\.[A-Za-z_][A-Za-z0-9_]*` + states + "$");
17
+ const hyphenated = new RegExp(String.raw`^\.([A-Za-z_][\w-]*)` + states + "$");
18
+ const camel = (name) => name.replace(/-+([A-Za-z0-9])/g, (_, letter) => letter.toUpperCase()).replace(/-/g, "");
19
+
20
+ // Keep composition expressive while leaving paint, focus indicators and theme ownership
21
+ // with the framework. Shorthands that can paint need the same checks as longhands.
22
+ const layoutProperties = new Set(`
23
+ display box-sizing inset inset-inline inset-inline-start inset-inline-end inset-block inset-block-start inset-block-end
24
+ top right bottom left aspect-ratio width height min-width min-height max-width max-height
25
+ block-size inline-size min-block-size min-inline-size max-block-size max-inline-size
26
+ margin margin-top margin-right margin-bottom margin-left margin-inline margin-inline-start margin-inline-end
27
+ margin-block margin-block-start margin-block-end padding padding-top padding-right padding-bottom padding-left
28
+ padding-inline padding-inline-start padding-inline-end padding-block padding-block-start padding-block-end
29
+ gap row-gap column-gap grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-start
30
+ grid-column-end grid-row grid-row-start grid-row-end grid-template grid-template-areas grid-template-columns
31
+ grid-template-rows flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap order align-content
32
+ align-items align-self justify-content justify-items justify-self place-content place-items place-self
33
+ overflow overflow-x overflow-y overflow-wrap font font-family font-size font-style font-weight line-height
34
+ letter-spacing word-spacing white-space text-align text-transform text-wrap list-style-type border-radius
35
+ border-top-left-radius border-top-right-radius border-bottom-left-radius border-bottom-right-radius container-name container-type
36
+ `.trim().split(/\s+/));
37
+
38
+ /**
39
+ * Paint takes a palette role, not merely a `--color-*` token. Every ink here over every surface
40
+ * here is a text pair the palette declares and holds to AA in every theme (index.test.js checks
41
+ * that against @terpjs/contract's token-pairs.json), so a pairing an app forms from them, on one
42
+ * element or across two, is one the palette already measures. The surfaces are the three the
43
+ * framework sets its own components on (the canvas, a surface, a subtle container), so a
44
+ * framework control an app places on one meets no background it does not meet in the
45
+ * framework's own pages. A brand fill, a status ink, the accent, the summary band and the
46
+ * primitive ramp stay with the framework controls that carry their partners.
47
+ */
48
+ export const PAINT_ROLES = {
49
+ ink: ["--color-fg-default", "--color-fg-muted", "--color-fg-subtle"],
50
+ surface: ["--color-bg-canvas", "--color-bg-surface", "--color-bg-subtle"],
51
+ border: ["--color-border-default", "--color-border-strong", "--color-border-subtle"],
52
+ };
53
+ const roleToken = (role) => new RegExp(String.raw`^var\(\s*(?:${PAINT_ROLES[role].join("|")})\s*\)$`);
54
+ const listed = (role) => PAINT_ROLES[role].map((token) => `var(${token})`).join(", ");
55
+ const PAINT = {
56
+ color: { role: "ink", keywords: ["currentColor", "inherit"] },
57
+ background: { role: "surface", keywords: ["transparent"] },
58
+ "background-color": { role: "surface", keywords: ["transparent"] },
59
+ "border-color": { role: "border", keywords: ["transparent", "currentColor"] },
60
+ };
61
+ const border = /^border(?:-(?:top|right|bottom|left|(?:block|inline)(?:-start|-end)?))?$/;
62
+ const borderValue = new RegExp(
63
+ String.raw`^(?:0|none|(?:0|(?:\d*\.)?\d+(?:px|em|rem))\s+(?:solid|dashed|dotted|double)\s+` +
64
+ String.raw`(?:var\(\s*(?:${PAINT_ROLES.border.join("|")})\s*\)|currentColor|transparent))$`, "i");
65
+
66
+ /**
67
+ * The ink and type properties a descendant inherits. On an element that holds a component they
68
+ * would reach into it and restyle text the framework owns, so they belong on an element whose
69
+ * content is the app's own text. A list marker is left out: it paints only a list item, and a
70
+ * list of the app's own tiles has to be able to drop its bullets whatever the tiles hold.
71
+ */
72
+ const INHERITED = new Set(`
73
+ color font font-family font-size font-style font-weight line-height letter-spacing word-spacing
74
+ text-align text-transform white-space text-wrap overflow-wrap
75
+ `.trim().split(/\s+/));
76
+
77
+ /** Why a declaration is refused, as the remedy to apply, or null when it is admitted. */
78
+ function declarationProblem(node) {
79
+ const prop = node.prop.toLowerCase();
80
+ const value = node.value.trim();
81
+ if (node.important) return `drop !important from ${prop}: the stylesheet orders app and framework rules itself`;
82
+ if (prop === "position") {
83
+ return ["static", "relative", "absolute", "sticky"].includes(value)
84
+ ? null : "position takes static, relative, absolute or sticky";
85
+ }
86
+ if (prop === "list-style") return value === "none" ? null : "list-style takes none; list-style-type sets a marker";
87
+ // A string or symbols() marker renders as text, which no catalog translates.
88
+ if (prop === "list-style-type") {
89
+ return /^[a-z][a-z-]*$/i.test(value) ? null
90
+ : "list-style-type takes a counter style keyword, such as disc or decimal; a string or symbols() puts copy on screen that no catalog translates, so write it in the markup with Trans";
91
+ }
92
+ const paint = PAINT[prop];
93
+ if (paint) {
94
+ if (roleToken(paint.role).test(value) || paint.keywords.includes(value)) return null;
95
+ return `${prop} takes ${paint.role === "ink" ? "an" : "a"} ${paint.role} token, one of ${listed(paint.role)}, with no fallback, or ${paint.keywords.join(" or ")}`;
96
+ }
97
+ if (border.test(prop)) {
98
+ return borderValue.test(value) ? null
99
+ : `${prop} takes none, or a width, a style and a border token, such as 1px solid var(--color-border-default)`;
100
+ }
101
+ return layoutProperties.has(prop) ? null
102
+ : `${prop} is not among the properties a CSS Module may set (layout, typography, and paint through color, ` +
103
+ "background, background-color, border-color and the border shorthands); what it would style belongs to " +
104
+ "the react-core component that owns it, or to a token or prop asked of the framework";
105
+ }
106
+
107
+ /**
108
+ * Read one level of the stylesheet: the file itself, or a responsive group inside it. Every
109
+ * problem is reported, each with the line it is on, so one run names all of them.
110
+ */
111
+ function inspectContainer(container, file, sheet) {
112
+ const at = (node) => `${path.basename(file)}:${node.source.start.line}`;
113
+ for (const node of container.nodes ?? []) {
114
+ if (node.type === "comment") continue;
115
+ if (node.type === "atrule" && ["media", "container", "supports"].includes(node.name) && node.nodes) {
116
+ inspectContainer(node, file, sheet);
117
+ continue;
118
+ }
119
+ if (node.type === "atrule") {
120
+ sheet.problems.push(`${at(node)}: @${node.name} is refused; group rules only in @media, @container or @supports.`);
121
+ continue;
122
+ }
123
+ if (node.type !== "rule") {
124
+ sheet.problems.push(`${at(node)}: a declaration belongs inside a rule for one of this module's classes.`);
125
+ continue;
126
+ }
127
+ const outside = node.selectors.filter((part) => !selector.test(part));
128
+ if (outside.length) {
129
+ for (const part of outside) {
130
+ const name = hyphenated.exec(part)?.[1];
131
+ sheet.problems.push(name
132
+ ? `${at(node)}: .${name} cannot be named from script, since className reads a class as styles.<name>; call it .${camel(name)}.`
133
+ : `${at(node)}: ${part} is not a selector a CSS Module may use: select one of its own classes, optionally with ` +
134
+ ":hover, :focus, :focus-visible, :focus-within, :active or :disabled. For a state the component knows, " +
135
+ "give the element another class: className={active ? styles.active : styles.lane}.");
136
+ }
137
+ continue;
138
+ }
139
+ const names = node.selectors.map((part) => part.slice(1).split(":")[0]);
140
+ for (const name of names) sheet.classes.add(name);
141
+ for (const child of node.nodes) {
142
+ if (child.type === "comment") continue;
143
+ if (child.type !== "decl") {
144
+ sheet.problems.push(`${at(child)}: a rule holds declarations only; nest no rule or at-rule inside it.`);
145
+ continue;
146
+ }
147
+ const problem = declarationProblem(child);
148
+ if (problem) sheet.problems.push(`${at(child)}: ${problem}.`);
149
+ if (INHERITED.has(child.prop.toLowerCase())) {
150
+ for (const name of names) {
151
+ if (!sheet.inherited.has(name)) sheet.inherited.set(name, new Set());
152
+ sheet.inherited.get(name).add(child.prop.toLowerCase());
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ function inspectStylesheet(file) {
160
+ const sheet = { classes: new Set(), inherited: new Map(), problems: [] };
161
+ const name = path.basename(file);
162
+ let text;
163
+ try {
164
+ text = fs.readFileSync(file, "utf8");
165
+ } catch {
166
+ sheet.problems.push(`${name} is not beside this component: create it there, or import the sibling module that is.`);
167
+ return sheet;
168
+ }
169
+ let root;
170
+ try {
171
+ root = postcss.parse(text, { from: file });
172
+ } catch (error) {
173
+ sheet.problems.push(`${name}:${error.line ?? 1}: ${error.reason ?? "the stylesheet does not parse"}; fix the CSS on that line.`);
174
+ return sheet;
175
+ }
176
+ inspectContainer(root, file, sheet);
177
+ return sheet;
178
+ }
179
+
180
+ // Both ESLint rules see the same SourceCode for one lint pass. A new pass reads
181
+ // the stylesheet again, even if the importing source text did not change.
182
+ const sheetsBySource = new WeakMap();
183
+ function sheetFor(context, source) {
184
+ let sheets = sheetsBySource.get(context.sourceCode);
185
+ if (!sheets) {
186
+ sheets = new Map();
187
+ sheetsBySource.set(context.sourceCode, sheets);
188
+ }
189
+ if (!sheets.has(source)) {
190
+ sheets.set(source, inspectStylesheet(path.resolve(path.dirname(context.physicalFilename), source)));
191
+ }
192
+ return sheets.get(source);
193
+ }
194
+
195
+ export const moduleImports = {
196
+ meta: { type: "problem", schema: [], messages: { stylesheetContent: "{{detail}}" } },
197
+ create(context) {
198
+ return {
199
+ "ImportDeclaration, ExportNamedDeclaration, ExportAllDeclaration"(node) {
200
+ const source = node.source?.value;
201
+ if (!localModule.test(source)) return;
202
+ const binding = node.specifiers?.[0];
203
+ if (node.type !== "ImportDeclaration" || node.specifiers.length !== 1
204
+ || binding.type !== "ImportDefaultSpecifier" || node.importKind === "type") {
205
+ context.report({ node, message: `Import the sibling CSS Module with one static default binding: import styles from "${source}".` });
206
+ }
207
+ for (const detail of sheetFor(context, source).problems) {
208
+ context.report({ node, messageId: "stylesheetContent", data: { detail } });
209
+ }
210
+ },
211
+ };
212
+ },
213
+ };
214
+
215
+ /** `styles.board` where `styles` is the default binding of a sibling CSS Module, as `{ source, name }`. */
216
+ function moduleMember(context, node, expression) {
217
+ if (expression?.type !== "MemberExpression" || expression.computed || expression.optional
218
+ || expression.object.type !== "Identifier") return null;
219
+ let scope = context.sourceCode.getScope(node);
220
+ while (scope && !scope.set.has(expression.object.name)) scope = scope.upper;
221
+ const def = scope?.set.get(expression.object.name)?.defs[0];
222
+ if (def?.type !== "ImportBinding" || def.node.type !== "ImportDefaultSpecifier"
223
+ || !localModule.test(def.parent.source.value)) return null;
224
+ return { source: def.parent.source.value, name: expression.property.name };
225
+ }
226
+
227
+ // Read as the app's own text: words, an expression that renders no element and reads no
228
+ // `children`, a Trans, a fragment, and native elements holding the same. Trans and Fragment count
229
+ // only as the imports they are, so a component imported under either name is still a component.
230
+ const TRANSPARENT = { Trans: "@terpjs/react-core", Fragment: "react" };
231
+ const ELEMENT_CALLS = new Set(["createElement", "cloneElement", "jsx", "jsxs"]);
232
+
233
+ function variableOf(sourceCode, identifier) {
234
+ let scope = sourceCode.getScope(identifier);
235
+ while (scope && !scope.set.has(identifier.name)) scope = scope.upper;
236
+ return scope?.set.get(identifier.name) ?? null;
237
+ }
238
+
239
+ /** Whether a JSX tag is Trans or Fragment as imported from their own packages. */
240
+ function transparentTag(tag, sourceCode) {
241
+ if (tag.type === "JSXMemberExpression") {
242
+ if (tag.property.name !== "Fragment" || tag.object.type !== "JSXIdentifier") return false;
243
+ const def = variableOf(sourceCode, tag.object)?.defs[0];
244
+ return def?.type === "ImportBinding" && def.parent.source.value === "react";
245
+ }
246
+ if (tag.type !== "JSXIdentifier") return false;
247
+ const def = variableOf(sourceCode, tag)?.defs[0];
248
+ if (def?.type !== "ImportBinding" || def.node.type !== "ImportSpecifier") return false;
249
+ const imported = def.node.imported.name ?? def.node.imported.value;
250
+ return Object.hasOwn(TRANSPARENT, imported) && TRANSPARENT[imported] === def.parent.source.value;
251
+ }
252
+
253
+ /** `x.children`, `x?.children` or `x["children"]`. */
254
+ function childrenMember(node) {
255
+ const member = node?.type === "ChainExpression" ? node.expression : node;
256
+ if (member?.type !== "MemberExpression") return false;
257
+ return member.computed
258
+ ? member.property.type === "Literal" && member.property.value === "children"
259
+ : member.property.name === "children";
260
+ }
261
+
262
+ /** Whether a referenced name is `children`, or a binding taken from it: `{ children: body }`, `body = x.children`. */
263
+ function childrenBinding(identifier, sourceCode) {
264
+ if (identifier.name === "children") return true;
265
+ const def = variableOf(sourceCode, identifier)?.defs[0];
266
+ if (!def) return false;
267
+ let value = def.name;
268
+ let parent = value?.parent;
269
+ if (parent?.type === "AssignmentPattern" && parent.left === value) {
270
+ value = parent;
271
+ parent = parent.parent;
272
+ }
273
+ if (parent?.type === "Property" && parent.value === value && !parent.computed
274
+ && (parent.key.name ?? parent.key.value) === "children") return true;
275
+ return def.type === "Variable" && childrenMember(def.node.init);
276
+ }
277
+
278
+ /** An identifier that names a value here, not a property key or the member read off an object. */
279
+ function isReference(identifier) {
280
+ const parent = identifier.parent;
281
+ if (parent?.type === "MemberExpression" && parent.property === identifier && !parent.computed) return false;
282
+ if (parent?.type === "Property" && parent.key === identifier && !parent.computed && !parent.shorthand) return false;
283
+ return true;
284
+ }
285
+
286
+ /**
287
+ * The first thing inside *element* the lint cannot read as the app's own text: a component, a
288
+ * `children` read (by name, member, computed member or a binding taken from it), a call that
289
+ * makes an element, a spread or a `children` attribute. Null when there is none.
290
+ */
291
+ function notAppText(element, sourceCode) {
292
+ const attributesHold = (opening) => {
293
+ for (const attribute of opening.attributes) {
294
+ if (attribute.type === "JSXSpreadAttribute") return `a spread of ${sourceCode.getText(attribute.argument)}`;
295
+ if (attribute.name.name === "children") return "a children attribute";
296
+ }
297
+ return null;
298
+ };
299
+ const own = attributesHold(element.openingElement);
300
+ if (own) return own;
301
+ const stack = [...element.children];
302
+ while (stack.length) {
303
+ const node = stack.pop();
304
+ if (!node || typeof node.type !== "string") continue;
305
+ if (node.type === "JSXElement") {
306
+ const tag = node.openingElement.name;
307
+ const name = sourceCode.getText(tag);
308
+ if (!(tag.type === "JSXIdentifier" && /^[a-z]/.test(name)) && !transparentTag(tag, sourceCode)) return `<${name}>`;
309
+ const held = attributesHold(node.openingElement);
310
+ if (held) return held;
311
+ stack.push(...node.children);
312
+ continue;
313
+ }
314
+ if (childrenMember(node)) return `{${sourceCode.getText(node)}}`;
315
+ if (node.type === "Identifier" && isReference(node) && childrenBinding(node, sourceCode)) {
316
+ return `{${node.name}}`;
317
+ }
318
+ if (node.type === "CallExpression") {
319
+ const callee = node.callee.type === "MemberExpression" ? node.callee.property : node.callee;
320
+ if (callee.type === "Identifier" && ELEMENT_CALLS.has(callee.name)) return `${sourceCode.getText(node.callee)}(...)`;
321
+ }
322
+ for (const key of sourceCode.visitorKeys[node.type] ?? []) {
323
+ const value = node[key];
324
+ if (Array.isArray(value)) stack.push(...value);
325
+ else if (value) stack.push(value);
326
+ }
327
+ }
328
+ return null;
329
+ }
330
+
331
+ /**
332
+ * Whether *identifier* is read where the className check reads it: inside a `className`
333
+ * attribute, and not in the test of its conditional, which chooses a class and must not read
334
+ * (or pass on) the binding itself.
335
+ */
336
+ function insideClassName(identifier) {
337
+ for (let child = identifier, node = identifier.parent; node; child = node, node = node.parent) {
338
+ if (node.type === "ConditionalExpression" && node.test === child) return false;
339
+ if (node.type === "JSXAttribute") return node.name.name === "className";
340
+ if (node.type === "JSXElement" || node.type === "JSXFragment" || node.type === "Program") return false;
341
+ }
342
+ return false;
343
+ }
344
+
345
+ export const moduleClassNames = {
346
+ meta: { type: "problem", schema: [] },
347
+ create(context) {
348
+ const report = (node, message) => context.report({ node, message });
349
+ return {
350
+ // A module's binding is read nowhere but in a className: passed on through a spread, a call
351
+ // or a variable, its class could land on a framework control, where no check could see it.
352
+ ImportDeclaration(node) {
353
+ if (!localModule.test(node.source.value)) return;
354
+ for (const variable of context.sourceCode.getDeclaredVariables(node)) {
355
+ for (const { identifier } of variable.references) {
356
+ if (insideClassName(identifier)) continue;
357
+ report(identifier,
358
+ `${variable.name} is read only in a className on a native element: className={${variable.name}.board}, or ` +
359
+ `className={active ? ${variable.name}.active : ${variable.name}.board}. A module class passed on through a ` +
360
+ "spread, a call or a variable could reach a framework control.");
361
+ }
362
+ }
363
+ },
364
+ "JSXAttribute[name.name='className']"(node) {
365
+ const expression = node.value?.type === "JSXExpressionContainer" ? node.value.expression : null;
366
+ const branches = expression?.type === "ConditionalExpression"
367
+ ? [expression.consequent, expression.alternate] : [expression];
368
+ const members = branches.map((branch) => moduleMember(context, node, branch));
369
+ if (members.some((member) => member === null)) {
370
+ report(node,
371
+ "className takes one class of a sibling CSS Module: className={styles.board}, after " +
372
+ 'import styles from "./Board.module.css". For a style that follows a state, choose between ' +
373
+ "two of its classes: className={active ? styles.active : styles.board}.");
374
+ return;
375
+ }
376
+ const tag = node.parent.name;
377
+ if (tag.type !== "JSXIdentifier" || !/^[a-z]/.test(tag.name)) {
378
+ report(node,
379
+ `A module class goes on a native element, never on <${context.sourceCode.getText(tag)}>: a framework ` +
380
+ "component takes its props, and keeps the styling and focus treatment it ships with.");
381
+ return;
382
+ }
383
+ for (const { source, name } of members) {
384
+ const sheet = sheetFor(context, source);
385
+ if (sheet.problems.length) continue; // Reported at the import, by line.
386
+ if (!sheet.classes.has(name)) {
387
+ const known = [...sheet.classes].sort().join(", ") || "none yet";
388
+ report(node, `${source} defines no .${name} class: define it there, or use one it has (${known}).`);
389
+ continue;
390
+ }
391
+ const inherited = [...(sheet.inherited.get(name) ?? [])].sort();
392
+ const holder = inherited.length ? notAppText(node.parent.parent, context.sourceCode) : null;
393
+ if (holder) {
394
+ report(node,
395
+ `.${name} sets ${inherited.join(", ")}, which ${holder} inside this element would inherit: ink and ` +
396
+ "type go on an element that holds only the app's own text (words, expressions, Trans, and native " +
397
+ "elements around them), so keep the component, children or spread outside it.");
398
+ }
399
+ }
400
+ },
401
+ };
402
+ },
403
+ };
package/src/findings.js CHANGED
@@ -2,8 +2,8 @@
2
2
  /**
3
3
  * The machine-readable boundary lint — the frontend analog of `terp check --format json`.
4
4
  *
5
- * `terp-boundaries-lint` runs the app's own ESLint config (the flat config in the cwd,
6
- * exactly what `eslint .` would load) **and** the escape-hatch budget ratchet (the same
5
+ * `terp-boundaries-lint` runs the shipped boundary config on app source, the app's own
6
+ * ESLint config on its configured files, and the escape-hatch budget ratchet (the same
7
7
  * check `terp-boundaries-budget` runs) in one command, and publishes one **findings
8
8
  * envelope** on stdout:
9
9
  *
@@ -50,8 +50,8 @@ import { pathToFileURL } from "node:url";
50
50
 
51
51
  import { ESLint } from "eslint";
52
52
 
53
- import { checkBudget } from "./budget.js";
54
- import { activeLayoutContract, catalogRuleId, catalogRuleIds } from "./index.js";
53
+ import { checkBudget, sourceFiles } from "./budget.js";
54
+ import { activeLayoutContract, catalogRuleId, catalogRuleIds, terpBoundaries } from "./index.js";
55
55
  import { SPEC_VERSION } from "./spec.js";
56
56
 
57
57
  /** This package's own version — the `checker.version` a check report carries. */
@@ -108,10 +108,15 @@ export function renderEnvelope(results, cwd = process.cwd(), options = {}) {
108
108
  const findings = [];
109
109
  const unattributed = [];
110
110
  const human = [];
111
+ const seen = new Set();
111
112
  for (const result of results) {
112
113
  const relative = path.relative(cwd, result.filePath).split(path.sep).join("/");
113
114
  const file = relative === "" ? result.filePath.split(path.sep).join("/") : relative;
114
115
  for (const message of result.messages) {
116
+ // The app config normally includes Terp. Publish a shared diagnostic once.
117
+ const key = JSON.stringify([file, message.line, message.column, message.ruleId, message.message]);
118
+ if (seen.has(key)) continue;
119
+ seen.add(key);
115
120
  const rule = catalogRuleId(message);
116
121
  const line = Number.isInteger(message.line) && message.line > 0 ? message.line : 1;
117
122
  if (rule === null) {
@@ -174,6 +179,16 @@ async function main() {
174
179
  args.splice(formatIndex, 2);
175
180
  }
176
181
  const budgetPath = args[0] ?? path.join(cwd, "escape-hatch-budget.json");
182
+ // Evaluate the published inventory with the package's config before loading app config.
183
+ // The budget and the lint walk the same app-authored files, including files an app ignores.
184
+ const sources = sourceFiles(cwd);
185
+ const boundaries = new ESLint({
186
+ overrideConfigFile: true,
187
+ overrideConfig: terpBoundaries(),
188
+ globInputPaths: false,
189
+ });
190
+ const mandatory = sources.length ? await boundaries.lintFiles(sources) : [];
191
+
177
192
  // The app's own config and ignore set. Two rules also read checked-in declarations
178
193
  // outside the linted source file, so include those bytes in the cache namespace.
179
194
  // Otherwise fixing i18n.json can replay a stale failure, and breaking it after a
@@ -182,12 +197,15 @@ async function main() {
182
197
  const file = path.join(cwd, name);
183
198
  return fs.existsSync(file) ? fs.readFileSync(file) : Buffer.from("<missing>");
184
199
  });
185
- const declarationHash = createHash("sha256")
186
- .update(externalInputs[0])
187
- .update("\0")
188
- .update(externalInputs[1])
189
- .digest("hex")
190
- .slice(0, 16);
200
+ const hash = createHash("sha256").update(externalInputs[0]).update("\0").update(externalInputs[1]);
201
+ // CSS Modules are linted from the importing component. Editing or deleting just its
202
+ // stylesheet must invalidate the same cached result as changing the JSX.
203
+ // A repacked adapter can change the CSS policy without changing app sources.
204
+ hash.update("\0").update(fs.readFileSync(new URL("./cssModules.js", import.meta.url)));
205
+ for (const file of fs.globSync("src/**/*.module.css", { cwd }).sort()) {
206
+ hash.update("\0").update(file).update("\0").update(fs.readFileSync(path.join(cwd, file)));
207
+ }
208
+ const declarationHash = hash.digest("hex").slice(0, 16);
191
209
  const eslint = new ESLint({
192
210
  cache: true,
193
211
  cacheLocation: path.join(
@@ -198,7 +216,7 @@ async function main() {
198
216
  ".eslintcache",
199
217
  ),
200
218
  });
201
- const results = await eslint.lintFiles(["."]);
219
+ const results = [...mandatory, ...await eslint.lintFiles(["."])];
202
220
  // The ratchet runs regardless of the lint verdict — both halves always report.
203
221
  const budgetProblems = checkBudget(cwd, budgetPath);
204
222
  const relativeBudget = path.relative(cwd, budgetPath).split(path.sep).join("/");
@@ -197,6 +197,25 @@ describe("terp-boundaries-lint (the bin)", () => {
197
197
  expect(run.stderr).toMatch(/problem/);
198
198
  });
199
199
 
200
+ it("holds ignored app source to the shipped rules and keeps additional app diagnostics", () => {
201
+ const root = appRoot({
202
+ "package.json": '{ "type": "module" }',
203
+ "eslint.config.js": 'export default [{ ignores: ["src/private/**"] }, { rules: { "no-debugger": "error" } }];',
204
+ "escape-hatch-budget.json": "{}",
205
+ "src/private/View.tsx": "export const View = () => <button>ok</button>;",
206
+ "extra.js": "debugger;",
207
+ });
208
+ const run = runBin(root);
209
+ expect(run.status).toBe(1);
210
+ const report = JSON.parse(run.stdout);
211
+ expect(report.findings).toContainEqual(expect.objectContaining({
212
+ path: "src/private/View.tsx", rule: "frontend/token-styled-elements",
213
+ }));
214
+ expect(report.unattributed).toContainEqual(expect.objectContaining({
215
+ path: "extra.js", reported_as: "no-debugger",
216
+ }));
217
+ });
218
+
200
219
  it("stays green (exit 0) with an empty findings list on a clean app", () => {
201
220
  const root = appRoot({
202
221
  "package.json": '{ "type": "module" }',
@@ -247,7 +266,31 @@ describe("terp-boundaries-lint (the bin)", () => {
247
266
  const complete = runBin(root);
248
267
  expect(complete.status).toBe(0);
249
268
  expect(JSON.parse(complete.stdout).findings).toEqual([]);
250
- });
269
+ // Two runs of the bin, as in the stylesheet case below: past vitest's 5 s default on a slow runner.
270
+ }, 30_000);
271
+
272
+ it("rechecks an imported CSS Module when only the stylesheet changes", () => {
273
+ const root = appRoot({
274
+ "package.json": '{ "type": "module" }',
275
+ "eslint.config.js": config,
276
+ "escape-hatch-budget.json": "{}",
277
+ "src/Layout.tsx": 'import layout from "./Layout.module.css"; export const View = () => <div className={layout.board} />;',
278
+ "src/Layout.module.css": ":global(body) { display: none }",
279
+ });
280
+ // Refused first, so the cached pass stores the refusal. Fixing only the stylesheet leaves the
281
+ // component's bytes as they were: without the stylesheet in the cache key, ESLint would replay
282
+ // that stored refusal over a stylesheet that is now fine, and the run would stay red.
283
+ const refused = runBin(root);
284
+ expect(refused.status).toBe(1);
285
+ expect(new Set(JSON.parse(refused.stdout).findings.map(({ rule }) => rule))).toEqual(
286
+ new Set(["frontend/no-style-imports"]),
287
+ );
288
+ fs.writeFileSync(path.join(root, "src/Layout.module.css"), "@media (width < 40rem) { .board { display: grid } }");
289
+ const fixed = runBin(root);
290
+ expect(fixed.status).toBe(0);
291
+ expect(JSON.parse(fixed.stdout).findings).toEqual([]);
292
+ // Two runs of the bin, each a full ESLint start: past vitest's 5 s default on a slow runner.
293
+ }, 30_000);
251
294
 
252
295
  it("reports budget drift even when the boundary lint fails (both halves always run)", () => {
253
296
  // The regression the merged bin exists for: with `eslint . && terp-boundaries-budget`
package/src/index.js CHANGED
@@ -16,6 +16,7 @@
16
16
  import fs from "node:fs";
17
17
  import path from "node:path";
18
18
 
19
+ import { localModuleSource, moduleClassNames, moduleImports } from "./cssModules.js";
19
20
  import tseslint from "typescript-eslint";
20
21
 
21
22
  import {
@@ -1229,6 +1230,8 @@ const terpPlugin = {
1229
1230
  rules: {
1230
1231
  "locale-catalogs-complete": localeCatalogsComplete,
1231
1232
  "layout-contract": layoutContract,
1233
+ "no-inline-styling": moduleClassNames,
1234
+ "no-style-imports": moduleImports,
1232
1235
  "no-cross-module-imports": noCrossModuleImports,
1233
1236
  "no-dom-html-injection": noDomHtmlInjection,
1234
1237
  "no-eval": noEval,
@@ -1260,14 +1263,14 @@ const localDateTimeMessage =
1260
1263
  const deepImportMessage =
1261
1264
  "Import from the package root (@terpjs/react-core, @terpjs/contract), not its internals.";
1262
1265
  const styleImportMessage =
1263
- "App-authored stylesheets are forbidden, a library's included; theming flows from the " +
1264
- "design tokens, which only the bootstrap loads (tokens.css, house-style.css, theme.css), " +
1265
- "and layout from the react-core components (Stack, the page archetypes).";
1266
+ "Use a sibling CSS Module for a component's own layout, default-imported: " +
1267
+ `import styles from "./Board.module.css". Any other stylesheet is refused, a library's ` +
1268
+ "included: only the bootstrap imports global ones, and only the token pipeline's three " +
1269
+ "(@terpjs/contract/tokens.css, ./house-style.css, ./theme.css).";
1266
1270
  const dynamicStyleImportMessage =
1267
1271
  "A stylesheet loaded through import() or import.meta.glob is a stylesheet import like any " +
1268
- "other, and is refused the same way: theming flows from the design tokens, which only the " +
1269
- "bootstrap loads, statically (tokens.css, house-style.css, theme.css), and layout from the " +
1270
- "react-core components (Stack, the page archetypes).";
1272
+ "other. A component's own layout is a static default import of its sibling CSS Module: " +
1273
+ `import styles from "./Board.module.css".`;
1271
1274
 
1272
1275
  /**
1273
1276
  * The stylesheet extensions the boundary refuses, read off `BOUNDARY_SPEC.styleImportPatterns`
@@ -1304,12 +1307,14 @@ function restrictedSyntaxWithCatalogIds() {
1304
1307
  (guidance === undefined ? "" : ` ${guidance}`),
1305
1308
  };
1306
1309
  });
1307
- const rawAttributes = BOUNDARY_SPEC.restrictedAttributes.map((attribute) => ({
1310
+ const rawAttributes = BOUNDARY_SPEC.restrictedAttributes.filter((attribute) => attribute !== "className").map((attribute) => ({
1308
1311
  catalogId: "frontend/no-inline-styling",
1309
1312
  selector: `JSXAttribute[name.name='${attribute}']`,
1310
1313
  message:
1311
1314
  `The ${attribute} attribute is forbidden in app source; layout comes from the ` +
1312
- "react-core components (Stack, Page, ...) and styling from the design tokens.",
1315
+ "react-core components (Stack, Page, ...) and styling from the design tokens. A layout " +
1316
+ 'a component owns goes in its sibling CSS Module: import styles from "./Board.module.css" ' +
1317
+ "and className={styles.board} on a native element.",
1313
1318
  }));
1314
1319
  const inAppAnchors = BOUNDARY_SPEC.restrictInAppAnchors
1315
1320
  ? [
@@ -1529,7 +1534,9 @@ export function catalogRuleIds() {
1529
1534
  */
1530
1535
  function suppressibleRuleName(message) {
1531
1536
  const id = catalogRuleId(message);
1532
- if (id === null || id === "frontend/escape-hatch") {
1537
+ // A marker on an import governs that edge, never every CSS line behind it.
1538
+ if (id === null || id === "frontend/escape-hatch" ||
1539
+ (id === "frontend/no-style-imports" && message.messageId === "stylesheetContent")) {
1533
1540
  return null;
1534
1541
  }
1535
1542
  return id.slice("frontend/".length);
@@ -1667,29 +1674,18 @@ function escapeHatchProcessor() {
1667
1674
  }
1668
1675
 
1669
1676
  /**
1670
- * The `no-restricted-imports` entry: deep imports are refused everywhere, and so is every
1671
- * stylesheet except the ones `allowedStylesheets` names.
1672
- *
1673
- * With no allowance, the stylesheet refusal is the declared glob group, which ESLint matches in
1674
- * any letter case. An allowance cannot be a negated glob in that group: the negation would match
1675
- * case-insensitively too, so `./THEME.css` would pass as `./theme.css`. It is a regular
1676
- * expression instead, matched case-sensitively, that refuses a specifier ending in a stylesheet
1677
- * extension in any letter case unless it is exactly one of the allowed specifiers. Exact
1678
- * specifiers, so the allowance is never a shape a library's stylesheet, a nested `theme.css` or a
1679
- * `?inline` / `?url` / `?raw` variant could also match.
1677
+ * The generic import rule checks path spelling. A sibling CSS Module passes through to
1678
+ * moduleImports, which checks its binding and file contents. Only the bootstrap adds
1679
+ * the three exact global token imports. Other stylesheet extensions match in any case.
1680
1680
  */
1681
1681
  function restrictedImports(allowedStylesheets = []) {
1682
1682
  const anyCase = (extension) =>
1683
1683
  [...extension].map((letter) => `[${letter.toLowerCase()}${letter.toUpperCase()}]`).join("");
1684
- const stylesheets =
1685
- allowedStylesheets.length === 0
1686
- ? { group: BOUNDARY_SPEC.styleImportPatterns }
1687
- : {
1688
- regex:
1689
- `^(?!(?:${allowedStylesheets.map(escapeRegExp).join("|")})$)` +
1690
- `.*\\.(?:${STYLESHEET_EXTENSIONS.map(anyCase).join("|")})(?:\\?.*)?$`,
1691
- caseSensitive: true,
1692
- };
1684
+ const allowed = [localModuleSource, ...allowedStylesheets.map(escapeRegExp)];
1685
+ const stylesheets = {
1686
+ regex: `^(?!(?:${allowed.join("|")})$).*\\.(?:${STYLESHEET_EXTENSIONS.map(anyCase).join("|")})(?:\\?.*)?$`,
1687
+ caseSensitive: true,
1688
+ };
1693
1689
  return [
1694
1690
  "error",
1695
1691
  {
@@ -1737,6 +1733,8 @@ export function terpBoundaries() {
1737
1733
  "terp/no-framework-markers": "error",
1738
1734
  "terp/no-untranslated-ui": "error",
1739
1735
  "terp/layout-contract": "error",
1736
+ "terp/no-inline-styling": "error",
1737
+ "terp/no-style-imports": "error",
1740
1738
  "terp/no-cross-module-imports": "error",
1741
1739
  "terp/no-dom-html-injection": "error",
1742
1740
  "terp/no-eval": "error",
package/src/index.test.js CHANGED
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { ESLint } from "eslint";
6
6
  import { afterAll, describe, expect, it } from "vitest";
7
7
 
8
+ import { PAINT_ROLES } from "./cssModules.js";
8
9
  import terpBoundaries, { catalogRuleId } from "./index.js";
9
10
 
10
11
  // The frontend analog of the arch harness's meta-tests: prove each boundary rule actually fires on
@@ -108,9 +109,9 @@ describe("terpBoundaries", () => {
108
109
  expect(await lint('export const W = ({ label }) => <a href="https://example.com">{label}</a>;')).toEqual([]);
109
110
  });
110
111
 
111
- it("flags className (no side channel into hand-authored CSS)", async () => {
112
+ it("flags an arbitrary class name", async () => {
112
113
  expect(await lint('export const W = () => <div className="x">y</div>;')).toContain(
113
- "no-restricted-syntax",
114
+ "terp/no-inline-styling",
114
115
  );
115
116
  });
116
117
 
@@ -125,6 +126,218 @@ describe("terpBoundaries", () => {
125
126
  );
126
127
  });
127
128
 
129
+ it("checks class bindings and stylesheet scope independently", async () => {
130
+ fs.mkdirSync(path.dirname(MODULE_FILE), { recursive: true });
131
+ const sheet = path.join(path.dirname(MODULE_FILE), "Board.module.css");
132
+ const prefix = 'import layout from "./Board.module.css"; ';
133
+ fs.writeFileSync(sheet, ".board { display: grid }");
134
+ expect(await lint(prefix + 'export const W = () => <div className={layout.board} />;')).toEqual([]);
135
+ expect(await lint(prefix + 'export const W = (layout) => <div className={layout.board} />;')).toContain("terp/no-inline-styling");
136
+ expect(await lint('import "./Board.module.css";')).toContain("terp/no-style-imports");
137
+ expect(await lint('export * from "./Board.module.css";')).toContain("terp/no-style-imports");
138
+ expect(await lint(prefix + 'export const W = () => <div className={layout.boarrd} />;')).toContain("terp/no-inline-styling");
139
+ expect(await lint(prefix + 'export const W = () => <Button className={layout.board} />;')).toContain("terp/no-inline-styling");
140
+ fs.writeFileSync(sheet, "@media (width < 40rem) { .board:hover, .lane { color: var(--color-fg-default); } }");
141
+ expect(await lint(prefix + 'export const W = () => <div className={layout.lane} />;')).toEqual([]);
142
+ for (const decl of ["color: white", "background: #fff", "background: currentColor", "border: 1px solid red", "color: var(--color-fg-default, white)",
143
+ "--color-fg-default: white", "outline: none", "background-image: linear-gradient(red, red)", "padding: 1px !important"]) {
144
+ fs.writeFileSync(sheet, `.board { ${decl} }`);
145
+ const marked = "// terp-allow-no-style-imports: approved import edge\n" + prefix;
146
+ expect(await lint(marked), decl).toEqual(["terp/no-style-imports"]);
147
+ }
148
+ // Each refusal names its cause and the remedy, not only that a line is unsupported.
149
+ fs.writeFileSync(sheet, [".board { padding: 1px !important; }", ".lane { color: white; }", ".card { outline: none; }"].join("\n"));
150
+ const lines = (await lintMessages(prefix + 'export const W = () => <div className={layout.board} />;'))
151
+ .filter((text) => text.includes("Board.module.css:"));
152
+ expect(lines).toEqual([
153
+ expect.stringContaining("Board.module.css:1: drop !important from padding"),
154
+ expect.stringContaining("Board.module.css:2: color takes an ink token, one of var(--color-fg-default), var(--color-fg-muted), var(--color-fg-subtle), with no fallback, or currentColor or inherit."),
155
+ expect.stringContaining("Board.module.css:3: outline is not among the properties a CSS Module may set"),
156
+ ]);
157
+ // A border longhand, a keyword the property does not take, a string marker (copy no catalog
158
+ // translates) and a class script cannot name: each refusal says what would be admitted.
159
+ fs.writeFileSync(sheet, [".board { border-top-color: var(--color-border-default); }",
160
+ ".lane { background: none; list-style-type: 'Pay now '; }", ".task-card { display: grid }"].join("\n"));
161
+ expect((await lintMessages(prefix + 'export const W = () => <div className={layout.board} />;'))
162
+ .filter((text) => text.includes("Board.module.css:"))).toEqual([
163
+ expect.stringContaining("Board.module.css:1: border-top-color is not among the properties a CSS Module may set (layout, typography, and paint through color, background, background-color, border-color and the border shorthands); what it would style belongs to the react-core component that owns it, or to a token or prop asked of the framework."),
164
+ expect.stringContaining("Board.module.css:2: background takes a surface token, one of var(--color-bg-canvas), var(--color-bg-surface), var(--color-bg-subtle), with no fallback, or transparent."),
165
+ expect.stringContaining("Board.module.css:2: list-style-type takes a counter style keyword, such as disc or decimal; a string or symbols() puts copy on screen that no catalog translates"),
166
+ expect.stringContaining("Board.module.css:3: .task-card cannot be named from script, since className reads a class as styles.<name>; call it .taskCard."),
167
+ ]);
168
+ // Paint takes its role: an ink as a surface, a surface or a brand fill as ink, and a border
169
+ // shorthand outside the border tokens are each refused with the tokens the role takes.
170
+ fs.writeFileSync(sheet, [".board { color: var(--color-brand-primary); }", ".lane { background: var(--color-fg-default); }",
171
+ ".card { border: 1px solid var(--color-fg-accent); }", ".tag { color: var(--color-bg-canvas); }"].join("\n"));
172
+ expect((await lintMessages(prefix + 'export const W = () => <div className={layout.board} />;'))
173
+ .filter((text) => text.includes("Board.module.css:"))).toEqual([
174
+ expect.stringContaining("Board.module.css:1: color takes an ink token"),
175
+ expect.stringContaining("Board.module.css:2: background takes a surface token"),
176
+ expect.stringContaining("Board.module.css:3: border takes none, or a width, a style and a border token, such as 1px solid var(--color-border-default)."),
177
+ expect.stringContaining("Board.module.css:4: color takes an ink token"),
178
+ ]);
179
+ // A selector outside the grammar names the one it may use and the route for a state.
180
+ fs.writeFileSync(sheet, ".board[aria-current] { display: grid }");
181
+ expect(await lintMessages(prefix + 'export const W = () => <div className={layout.board} />;')).toEqual([
182
+ expect.stringContaining("Board.module.css:1: .board[aria-current] is not a selector a CSS Module may use: select one of its own classes, optionally with :hover, :focus, :focus-visible, :focus-within, :active or :disabled. For a state the component knows, give the element another class: className={active ? styles.active : styles.lane}."),
183
+ ]);
184
+ // A missing sheet and one that does not parse are told apart, the second by its line and reason.
185
+ fs.writeFileSync(sheet, ".board { display: grid");
186
+ expect(await lintMessages(prefix + 'export const W = () => <div className={layout.board} />;')).toEqual([
187
+ expect.stringContaining("Board.module.css:1: Unclosed block; fix the CSS on that line."),
188
+ ]);
189
+ expect(await lintMessages('import layout from "./Missing.module.css"; export const W = () => <div className={layout.board} />;')).toEqual([
190
+ expect.stringContaining("Missing.module.css is not beside this component: create it there, or import the sibling module that is."),
191
+ ]);
192
+ fs.writeFileSync(sheet, ".board { display: grid }\n.active { display: grid }");
193
+ expect(await lintMessages('import { board } from "./Board.module.css"; export const W = () => <div className={board} />;')).toContain(
194
+ 'Import the sibling CSS Module with one static default binding: import styles from "./Board.module.css".',
195
+ );
196
+ // A state chooses between two of the module's classes; any other expression is refused by name.
197
+ expect(await lint(prefix + 'export const W = ({ on }) => <div className={on ? layout.active : layout.board} />;')).toEqual([]);
198
+ for (const expression of ['on ? layout.active : "x"', "`${layout.board}`", "layout?.board"]) {
199
+ expect(await lintMessages(prefix + `export const W = ({ on }) => <div className={${expression}} />;`), expression).toEqual([
200
+ "className takes one class of a sibling CSS Module: className={styles.board}, after " +
201
+ 'import styles from "./Board.module.css". For a style that follows a state, choose between ' +
202
+ "two of its classes: className={active ? styles.active : styles.board}.",
203
+ ]);
204
+ }
205
+ expect(await lintMessages(prefix + 'export const W = () => <Button className={layout.board} />;')).toEqual([
206
+ "A module class goes on a native element, never on <Button>: a framework component takes its props, " +
207
+ "and keeps the styling and focus treatment it ships with.",
208
+ ]);
209
+ // The binding is read in a className and nowhere else: a spread, a call or a variable would
210
+ // carry the class to a framework control past every check above.
211
+ for (const code of [
212
+ "export const W = () => <Button {...{ className: layout.board }} />;",
213
+ "const props = { className: layout.board }; export const W = () => <Input {...props} />;",
214
+ 'import { createElement } from "react"; export const W = () => createElement(Button, { className: layout.board });',
215
+ // The conditional's test chooses a class; it must not read the binding, or it could store it
216
+ // or pass it on while the branches stay valid.
217
+ "let stash; export const W = ({ on }) => <><div className={(stash = layout, on) ? layout.active : layout.board} /><Button {...{ className: stash.board }} /></>;",
218
+ 'import { createElement } from "react"; export const W = ({ on }) => <div className={createElement(Button, { className: layout.board }) && on ? layout.active : layout.board} />;',
219
+ ]) {
220
+ expect(await lintMessages(prefix + code), code).toContain(
221
+ "layout is read only in a className on a native element: className={layout.board}, or " +
222
+ "className={active ? layout.active : layout.board}. A module class passed on through a spread, " +
223
+ "a call or a variable could reach a framework control.",
224
+ );
225
+ }
226
+ // Ink and type are inherited: set on an element that holds anything but the app's own text,
227
+ // they would restyle text the framework owns, so they go on the element that holds that text.
228
+ fs.writeFileSync(sheet, ".lane { color: var(--color-fg-muted); text-transform: uppercase; }\n.board { display: grid }");
229
+ expect(await lintMessages(prefix + "export const W = ({ t }) => <section className={layout.lane}><Card title={t} /></section>;")).toEqual([
230
+ ".lane sets color, text-transform, which <Card> inside this element would inherit: ink and type go on an " +
231
+ "element that holds only the app's own text (words, expressions, Trans, and native elements around them), " +
232
+ "so keep the component, children or spread outside it.",
233
+ ]);
234
+ for (const [body, holder] of [
235
+ ["{items.map((i) => <li key={i}><Badge>{i}</Badge></li>)}", "<Badge>"],
236
+ ["{children}", "{children}"],
237
+ ["{open && children}", "{children}"],
238
+ ["{children ?? null}", "{children}"],
239
+ ["{props?.children}", "{props?.children}"],
240
+ ['{props["children"]}', '{props["children"]}'],
241
+ ["{Children.map(children, (c) => <li>{c}</li>)}", "{children}"],
242
+ ["{createElement(Card)}", "createElement(...)"],
243
+ ["{React.cloneElement(item)}", "React.cloneElement(...)"],
244
+ ]) {
245
+ const code = `export const W = ({ items, children, open, props, item }) => <ul className={layout.lane}>${body}</ul>;`;
246
+ expect(await lintMessages(prefix + code), body).toEqual([
247
+ expect.stringContaining(`.lane sets color, text-transform, which ${holder} inside this element would inherit`),
248
+ ]);
249
+ }
250
+ // A binding taken from children is children, and a component imported as Fragment or Trans
251
+ // is still a component: only the real Trans and Fragment are read as text.
252
+ for (const [code, holder] of [
253
+ ["export const W = ({ children: body }) => <ul className={layout.lane}>{body}</ul>;", "{body}"],
254
+ ["export const W = ({ children: body = null }) => <ul className={layout.lane}>{body}</ul>;", "{body}"],
255
+ ["export const W = (props) => { const body = props.children; return <ul className={layout.lane}>{body}</ul>; };", "{body}"],
256
+ ['import { Card as Fragment } from "@terpjs/react-core"; export const W = () => <ul className={layout.lane}><Fragment /></ul>;', "<Fragment>"],
257
+ ['import { Card as Trans } from "@terpjs/react-core"; export const W = () => <ul className={layout.lane}><Trans /></ul>;', "<Trans>"],
258
+ ]) {
259
+ // A stand-in Trans also meets the localisation rule, which reads the name; only this one matters here.
260
+ expect(await lintMessages(prefix + code), code).toContainEqual(
261
+ expect.stringContaining(`.lane sets color, text-transform, which ${holder} inside this element would inherit`),
262
+ );
263
+ }
264
+ expect(await lintMessages(prefix + "export const W = (props) => <section className={layout.lane} {...props} />;"))
265
+ .toEqual([expect.stringContaining(".lane sets color, text-transform, which a spread of props inside this element would inherit")]);
266
+ expect(await lintMessages(prefix + "export const W = ({ t }) => <section className={layout.lane} children={<Card title={t} />} />;"))
267
+ .toEqual([expect.stringContaining(".lane sets color, text-transform, which a children attribute inside this element would inherit")]);
268
+ // The app's own text, in each spelling the lint reads as text, takes ink and type.
269
+ const imports = 'import { Fragment } from "react"; import * as React from "react"; import { Trans } from "@terpjs/react-core"; ';
270
+ for (const body of ["{t}", '<Trans id="w.note" message="Nothing yet" />', "<Fragment key={t}><strong>{t}</strong></Fragment>",
271
+ "<React.Fragment key={t}>{t}</React.Fragment>", "{items.map((i) => <li key={i}>{i}</li>)}", "{text(label)}"]) {
272
+ expect(await lint(imports + prefix + `export const W = ({ t, items, text, label }) => <ul className={layout.lane}>${body}</ul>;`), body)
273
+ .toEqual([]);
274
+ }
275
+ expect(await lint(prefix + "export const W = ({ t }) => <div className={layout.board}><p className={layout.lane}>{t}</p><Card /></div>;")).toEqual([]);
276
+ // Each inherited type property is held the same way; a list marker and layout are not inherited text.
277
+ for (const decl of ["font-size: 1rem", "font-weight: 600", "font-family: serif", "line-height: 1.5",
278
+ "letter-spacing: 0.02em", "word-spacing: 1px", "white-space: nowrap", "text-align: center", "text-wrap: balance",
279
+ "overflow-wrap: anywhere", "font-style: italic", "font: inherit"]) {
280
+ fs.writeFileSync(sheet, `.lane { ${decl}; }`);
281
+ expect(await lintMessages(prefix + "export const W = () => <div className={layout.lane}><Card /></div>;"), decl)
282
+ .toEqual([expect.stringContaining(`.lane sets ${decl.split(":")[0]}, which <Card> inside this element would inherit`)]);
283
+ }
284
+ fs.writeFileSync(sheet, ".lane { list-style: none; display: grid; position: sticky; }");
285
+ expect(await lint(prefix + "export const W = ({ t }) => <ul className={layout.lane}><li><Button>{t}</Button></li></ul>;")).toEqual([]);
286
+ // position takes the values that keep an element in its own layout; fixed is the shell's.
287
+ fs.writeFileSync(sheet, ".lane { position: fixed; }");
288
+ expect(await lintMessages(prefix + "export const W = () => <div className={layout.lane} />;")).toEqual([
289
+ "Board.module.css:1: position takes static, relative, absolute or sticky.",
290
+ ]);
291
+ // A declaration outside a rule, an at-rule outside the three groups, and a nested rule each
292
+ // name what the stylesheet may hold instead.
293
+ fs.writeFileSync(sheet, ["color: var(--color-fg-default);", "@layer app { .lane { display: grid } }", ".lane { .inner { display: grid } }"].join("\n"));
294
+ expect(await lintMessages(prefix + "export const W = () => <div className={layout.lane} />;")).toEqual([
295
+ "Board.module.css:1: a declaration belongs inside a rule for one of this module's classes.",
296
+ "Board.module.css:2: @layer is refused; group rules only in @media, @container or @supports.",
297
+ "Board.module.css:3: a rule holds declarations only; nest no rule or at-rule inside it.",
298
+ ]);
299
+ // A sibling module may carry dots in its name, as Vite allows.
300
+ fs.writeFileSync(path.join(path.dirname(MODULE_FILE), "Board.lanes.module.css"), ".lane { display: grid }");
301
+ expect(await lint('import lanes from "./Board.lanes.module.css"; export const W = () => <div className={lanes.lane} />;')).toEqual([]);
302
+ // The allowance is the sibling spelling exactly: a query, another directory or another letter
303
+ // case is a stylesheet import like any other, refused as a path, and its file is never read.
304
+ for (const source of ["./Board.module.css?url", "./Board.module.css?inline", "./Board.module.css?raw",
305
+ "./parts/Board.module.css", "../Board.module.css", "./Board.MODULE.css"]) {
306
+ // The path refusal, and no stylesheet finding: the sheet beside the component holds refused
307
+ // lines, and a missing file is a finding too, so a read of either would show here.
308
+ const rules = await lint(`import layout from "${source}"; export const W = () => <div className={layout.board} />;`);
309
+ expect(rules, source).toContain("no-restricted-imports");
310
+ expect(rules, source).not.toContain("terp/no-style-imports");
311
+ // Under a marker the path refusal is waived and nothing reads the file: no stylesheet finding.
312
+ const marked = `// terp-allow-no-style-imports: legacy path\nimport layout from "${source}"; export const W = () => <div className={layout.board} />;`;
313
+ expect(await lint(marked), source).not.toContain("terp/no-style-imports");
314
+ }
315
+ fs.writeFileSync(sheet, ".board { display: grid }\n.lane { display: grid }");
316
+ expect(await lintMessages(prefix + 'export const W = () => <div className={layout.card} />;')).toEqual([
317
+ expect.stringContaining("./Board.module.css defines no .card class: define it there, or use one it has (board, lane)."),
318
+ ]);
319
+ for (const css of ['@import "./global.css";', ".board, body { display: grid }",
320
+ '.board { composes: external from "./global.css" }', ".board { & ~ * { display: none } }"]) {
321
+ fs.writeFileSync(sheet, css);
322
+ expect(await lint(prefix + 'export const W = () => <div className={layout.board} />;'), css)
323
+ .toEqual(["terp/no-style-imports"]);
324
+ }
325
+ });
326
+
327
+ it("admits only inks and surfaces whose every pairing the palette declares and measures", () => {
328
+ // The claim the paint roles rest on: an app that sets any admitted ink over any admitted surface,
329
+ // on one element or across two, forms a text pair the contract's contrast gate already holds to
330
+ // AA in every theme. A token added to a role without its pairs fails here, not in a screen.
331
+ const pairs = JSON.parse(
332
+ fs.readFileSync(new URL("../../contract/token-pairs.json", import.meta.url), "utf8"),
333
+ ).textPairs.map(({ fg, bg }) => `${fg} on ${bg}`);
334
+ for (const ink of PAINT_ROLES.ink) {
335
+ for (const surface of PAINT_ROLES.surface) {
336
+ expect(pairs, `${ink} on ${surface}`).toContain(`${ink} on ${surface}`);
337
+ }
338
+ }
339
+ });
340
+
128
341
  it("flags a hardcoded colour (design tokens only)", async () => {
129
342
  expect(await lint('export const s = { color: "#ff0000" };')).toContain("no-restricted-syntax");
130
343
  });
@@ -401,9 +614,11 @@ describe("terpBoundaries", () => {
401
614
  expect(messages.some((message) => message.startsWith("dangerouslySetInnerHTML"))).toBe(true);
402
615
  expect(messages).toContain(
403
616
  "The style attribute is forbidden in app source; layout comes from the react-core " +
404
- "components (Stack, Page, ...) and styling from the design tokens.",
617
+ "components (Stack, Page, ...) and styling from the design tokens. A layout a component " +
618
+ 'owns goes in its sibling CSS Module: import styles from "./Board.module.css" and ' +
619
+ "className={styles.board} on a native element.",
405
620
  );
406
- expect(messages.some((message) => message.startsWith("The className attribute"))).toBe(true);
621
+ expect(messages.some((message) => message.startsWith("className takes one class of a sibling CSS Module"))).toBe(true);
407
622
  expect(messages.some((message) => message.includes("Button"))).toBe(true);
408
623
  });
409
624
 
@@ -529,9 +744,9 @@ describe("terpBoundaries", () => {
529
744
  ]) {
530
745
  const messages = await lintMessages(`import "${source}";\nexport {};`, BOOTSTRAP_FILE);
531
746
  expect(messages, source).toHaveLength(1);
532
- expect(messages[0], source).toContain(
533
- "App-authored stylesheets are forbidden, a library's included",
534
- );
747
+ // The refusal names both routes: the module form for a component, the three for the bootstrap.
748
+ expect(messages[0], source).toContain('import styles from "./Board.module.css"');
749
+ expect(messages[0], source).toContain("(@terpjs/contract/tokens.css, ./house-style.css, ./theme.css)");
535
750
  }
536
751
  });
537
752
 
package/src/spec.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * about, and none of them is about a directory. The one rule that *is* about a module's shape,
8
8
  * `no-cross-module-imports`, reads the module tree for itself: a module never imports a
9
9
  * sibling, and code outside every module never imports into one. The bootstrap is the one file
10
- * that may import stylesheets, and only the token pipeline's own. Framework packages
10
+ * that may import global stylesheets. App components can import sibling CSS Modules. Framework packages
11
11
  * legitimately define the primitives these rules point back to and are outside an app's
12
12
  * boundary config.
13
13
  */
@@ -20,7 +20,7 @@
20
20
  * of the toolchain build. Held equal to the pinned release by the framework gate
21
21
  * (test_check_json.py).
22
22
  */
23
- export const SPEC_VERSION = "0.46.0";
23
+ export const SPEC_VERSION = "0.50.0";
24
24
 
25
25
  /** Every script extension the bundler loads as app source (see `appFiles`). */
26
26
  const SOURCE_EXTENSIONS = ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
@@ -46,10 +46,9 @@ export const BOUNDARY_SPEC = {
46
46
  */
47
47
  bootstrapFiles: ["**/src/main.{ts,tsx}"],
48
48
  /**
49
- * The stylesheets the bootstrap may import, and the only ones any app file may: the framework's
50
- * tokens, the house style a tool manages and the app's own token overlay. Each is a layer of
51
- * the token pipeline, so a stylesheet outside this list is a side channel around it, a
52
- * library's included.
49
+ * The global stylesheets the bootstrap may import: the framework's
50
+ * tokens, the house style a tool manages and the app's own token overlay. These are the three layers of
51
+ * the global token pipeline.
53
52
  */
54
53
  bootstrapStylesheets: ["@terpjs/contract/tokens.css", "./house-style.css", "./theme.css"],
55
54
  /**
@@ -66,11 +65,6 @@ export const BOUNDARY_SPEC = {
66
65
  form: 'Stack as="form"',
67
66
  meter: "Meter",
68
67
  },
69
- /**
70
- * JSX attributes app source must not author — styling lives in the design tokens and the
71
- * react-core components (`Stack` for layout), never ad-hoc per screen. `className` would be
72
- * a side channel into hand-authored CSS, so it is refused alongside `style`.
73
- */
74
68
  /**
75
69
  * Extra guidance for an element whose named replacement does not fit every case, so the
76
70
  * refusal states what to do instead of implying something is missing.
@@ -107,6 +101,7 @@ export const BOUNDARY_SPEC = {
107
101
  "sorting, column resizing and settings, the mobile card reflow and the row-level " +
108
102
  "activation the rest of the app has.",
109
103
  },
104
+ /** Inline styles and arbitrary classes are refused. A CSS Module binding supplies a scoped class. */
110
105
  restrictedAttributes: ["style", "className"],
111
106
  /**
112
107
  * Raw in-app anchors (`<a href="/...">`) bypass the router (full reload, no role-aware
@@ -115,7 +110,7 @@ export const BOUNDARY_SPEC = {
115
110
  restrictInAppAnchors: true,
116
111
  /** Package internals app source must not deep-import (import from the package root). */
117
112
  internalImportPatterns: ["@terpjs/*/src/*", "@terpjs/*/dist/*"],
118
- /** App-authored stylesheets are refused — theming flows from the app's token source. */
113
+ /** Extensions restricted by default. A sibling CSS Module has a separate import contract. */
119
114
  styleImportPatterns: [
120
115
  "*.css",
121
116
  "**/*.css",