@terpjs/eslint-boundaries 0.31.0 → 0.33.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.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@terpjs/eslint-boundaries",
3
- "version": "0.31.0",
3
+ "version": "0.33.0",
4
4
  "type": "module",
5
- "description": "Terp frontend boundary rules (as data) + the ESLint adapter: no cross-module imports, no package internals, design-token-only styling (no style/className/module stylesheets), 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, 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).",
6
6
  "main": "./src/index.js",
7
7
  "bin": {
8
8
  "terp-boundaries-budget": "./src/budget.js",
@@ -26,8 +26,8 @@
26
26
  },
27
27
  "devDependencies": {
28
28
  "@terpjs/spec": "0.39.0",
29
- "eslint": "^10.11.0",
30
- "vitest": "^5.0.2"
29
+ "eslint": "^10.12.0",
30
+ "vitest": "^5.0.3"
31
31
  },
32
32
  "license": "Apache-2.0",
33
33
  "repository": {
package/src/budget.js CHANGED
@@ -23,7 +23,8 @@ import { pathToFileURL } from "node:url";
23
23
  import { BOUNDARY_SPEC } from "./spec.js";
24
24
  import { knownMarkerNames, parseAllowMarkers } from "./index.js";
25
25
 
26
- const MODULE_FILE_RE = /\.(?:ts|tsx)$/;
26
+ /** The app-source extensions the lint holds (`BOUNDARY_SPEC.sourceExtensions`), as a file test. */
27
+ const SOURCE_FILE_RE = new RegExp(`\\.(?:${BOUNDARY_SPEC.sourceExtensions.join("|")})$`);
27
28
 
28
29
  /** The `review-by:<YYYY-MM-DD>` metadata token in a marker's reason (the Terp
29
30
  * Standard's escape-hatch contract): when the exception must be re-justified.
@@ -43,7 +44,7 @@ function parsedReviewDate(value) {
43
44
  return roundTrips ? date : null;
44
45
  }
45
46
 
46
- /** Every app-authored `src/**` TypeScript file under *root*, recursively. */
47
+ /** Every app-authored `src/**` source file under *root*, recursively. */
47
48
  function sourceFiles(root) {
48
49
  const sourceRoot = path.join(root, "src");
49
50
  if (!fs.existsSync(sourceRoot)) {
@@ -56,7 +57,7 @@ function sourceFiles(root) {
56
57
  if (entry.isDirectory()) {
57
58
  if (full === path.join(sourceRoot, "api")) continue;
58
59
  walk(full);
59
- } else if (MODULE_FILE_RE.test(entry.name)) {
60
+ } else if (SOURCE_FILE_RE.test(entry.name)) {
60
61
  files.push(full);
61
62
  }
62
63
  }
@@ -68,6 +68,16 @@ describe("countMarkers", () => {
68
68
  expect(countMarkers(root)).toEqual({ "terp-allow-no-untranslated-ui": 1 });
69
69
  });
70
70
 
71
+ it("counts markers in every source extension the lint holds, not only .ts/.tsx", () => {
72
+ // The lint covers .mts/.cts/.js/.jsx/.mjs/.cjs under src (ADR 0175); a marker in one of
73
+ // them waives a real finding, so the ratchet has to see it or it is an unbudgeted waiver.
74
+ const files = Object.fromEntries(
75
+ ["mts", "cts", "js", "jsx", "mjs", "cjs"].map((extension) => [`a/x.${extension}`, MARKED]),
76
+ );
77
+ const root = appRoot({ ...files, "a/notes.md": MARKED });
78
+ expect(countMarkers(root)).toEqual({ "terp-allow-token-styled-elements": 6 });
79
+ });
80
+
71
81
  it("is empty for an app with no source directory", () => {
72
82
  const root = path.join(scratchRoot, `case-${rootCounter++}`);
73
83
  fs.rmSync(root, { recursive: true, force: true });
@@ -13,7 +13,10 @@ import path from "node:path";
13
13
 
14
14
  import { ESLint } from "eslint";
15
15
 
16
- import terpBoundaries, { LAYOUT_CONTRACT_FILE, catalogRuleId } from "./index.js";
16
+ import terpBoundaries, { BOUNDARY_SPEC, LAYOUT_CONTRACT_FILE, catalogRuleId } from "./index.js";
17
+
18
+ /** The source files a case carries, by the same extensions the lint holds in an app. */
19
+ const SOURCE_FILE_RE = new RegExp(`\\.(?:${BOUNDARY_SPEC.sourceExtensions.join("|")})$`);
17
20
 
18
21
  /** Every file below *caseDir*, recursively. */
19
22
  export function caseFiles(caseDir) {
@@ -51,7 +54,9 @@ export async function lintCaseFindings(caseDir) {
51
54
  : [
52
55
  ...terpBoundaries,
53
56
  {
54
- files: ["**/modules/**/*.{ts,tsx}"],
57
+ // The scope of every other rule (ADR 0175): a case file outside modules/ is held
58
+ // to the opted-in contract exactly as an app file there would be.
59
+ files: BOUNDARY_SPEC.appFiles,
55
60
  rules: { "terp/layout-contract": ["error", { contract }] },
56
61
  },
57
62
  ];
@@ -62,7 +67,7 @@ export async function lintCaseFindings(caseDir) {
62
67
  const eslint = new ESLint({ cwd: caseDir, overrideConfigFile: true, overrideConfig });
63
68
  const findings = [];
64
69
  for (const file of caseFiles(caseDir)) {
65
- if (!/\.tsx?$/.test(file)) continue; // config carriers (layout-contract.json) are not linted
70
+ if (!SOURCE_FILE_RE.test(file)) continue; // config carriers (layout-contract.json) are not linted
66
71
  // Use the physical case path so declaration-backed rules can find checked-in
67
72
  // carriers such as i18n.json by walking upward from the real file.
68
73
  const filePath = file;
package/src/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The ESLint (React stack) adapter that realises {@link BOUNDARY_SPEC}. This is the frontend analog
3
- * of the backend `terp.arch` harness: it keeps app modules independent and on the centralized
4
- * contract, so a non-technical user or a coding agent cannot introduce drift or a security gap.
3
+ * of the backend `terp.arch` harness: it keeps all app source on the centralized contract and app
4
+ * modules independent, so a non-technical user or a coding agent cannot introduce drift or a
5
+ * security gap.
5
6
  *
6
7
  * There are no modes and no severity dial — every rule is an error, always (exactly like the
7
8
  * backend gate). The only pressure valve is the governed escape hatch: a justified
@@ -26,6 +27,9 @@ import {
26
27
  } from "./layouts.js";
27
28
  import { BOUNDARY_SPEC } from "./spec.js";
28
29
 
30
+ /** The usual ways an app imports its own source by a root-anchored path (`@/`, `~/`, `/`, `src/`). */
31
+ const APP_ROOT_ALIAS = /^(?:@\/|~\/|\/|src\/)/;
32
+
29
33
  /** The app-module name a file/import path belongs to (the segment after `modules/`), or null. */
30
34
  function moduleOf(filePath) {
31
35
  const parts = String(filePath).split(/[/\\]/);
@@ -37,37 +41,53 @@ function moduleOf(filePath) {
37
41
  * A module never imports a sibling module (leaf domains stay independent) — the frontend analog of
38
42
  * `terp.arch`'s `no_cross_module_imports`. Relative imports are resolved before the check, so
39
43
  * `../other/thing` from `modules/a/` is caught as a `modules/other` import, not hidden by its spelling.
44
+ *
45
+ * Code outside every module never imports into one either (ADR 0175). Shared code is what modules
46
+ * depend on, never the other way round, and the reverse edge is a laundering route: a helper that
47
+ * re-exports `modules/billing/internal` hands billing's internals to every module that imports the
48
+ * helper, and the module-to-module check never sees a sibling path. The bootstrap discovers modules
49
+ * with `import.meta.glob`, which is not an import edge, so composing the app is untouched.
40
50
  */
41
51
  const noCrossModuleImports = {
42
52
  meta: {
43
53
  type: "problem",
44
- docs: { description: "Disallow imports between sibling app modules (leaf independence)." },
54
+ docs: {
55
+ description:
56
+ "Disallow imports between sibling app modules, and from code outside every module into one.",
57
+ },
45
58
  schema: [],
46
59
  },
47
60
  create(context) {
48
61
  // physicalFilename: the on-disk file (the escape-hatch processor lints a virtual block).
49
62
  const filename = context.physicalFilename || context.filename;
50
63
  const own = moduleOf(filename);
51
- if (own === null) {
52
- return {};
53
- }
54
64
  const check = (node) => {
55
65
  const source = node.source && node.source.value;
56
66
  if (typeof source !== "string") {
57
67
  return;
58
68
  }
69
+ // A relative path is resolved; a non-relative one names the app only through an app-root
70
+ // alias. Any other bare specifier is a dependency, and a `modules` segment in a package's
71
+ // own path (`core-js/modules/es.promise`) is not an app module.
59
72
  const target = source.startsWith(".")
60
73
  ? path.resolve(path.dirname(filename), source)
61
- : source;
62
- const other = moduleOf(target);
63
- if (other !== null && other !== own) {
64
- context.report({
65
- node,
66
- message:
67
- `App module "${own}" must not import sibling module "${other}"; modules stay ` +
68
- "independent (share through the framework packages, not each other).",
69
- });
74
+ : APP_ROOT_ALIAS.test(source)
75
+ ? source
76
+ : null;
77
+ const other = target === null ? null : moduleOf(target);
78
+ if (other === null || other === own) {
79
+ return;
70
80
  }
81
+ context.report({
82
+ node,
83
+ message:
84
+ own === null
85
+ ? `Code outside every module must not import from module "${other}"; modules ` +
86
+ "depend on shared code, never the other way round. Move what both need out of " +
87
+ "the module (or into the framework packages), or keep it inside the module."
88
+ : `App module "${own}" must not import sibling module "${other}"; modules stay ` +
89
+ "independent (share through the framework packages, not each other).",
90
+ });
71
91
  };
72
92
  return {
73
93
  ImportDeclaration: check,
@@ -1163,8 +1183,32 @@ const randomUuidMessage =
1163
1183
  const deepImportMessage =
1164
1184
  "Import from the package root (@terpjs/react-core, @terpjs/contract), not its internals.";
1165
1185
  const styleImportMessage =
1166
- "Module-authored stylesheets are forbidden; theming flows from the design tokens " +
1186
+ "App-authored stylesheets are forbidden, a library's included; theming flows from the " +
1187
+ "design tokens, which only the bootstrap loads (tokens.css, house-style.css, theme.css), " +
1167
1188
  "and layout from the react-core components (Stack, the page archetypes).";
1189
+ const dynamicStyleImportMessage =
1190
+ "A stylesheet loaded through import() or import.meta.glob is a stylesheet import like any " +
1191
+ "other, and is refused the same way: theming flows from the design tokens, which only the " +
1192
+ "bootstrap loads, statically (tokens.css, house-style.css, theme.css), and layout from the " +
1193
+ "react-core components (Stack, the page archetypes).";
1194
+
1195
+ /**
1196
+ * The stylesheet extensions the boundary refuses, read off `BOUNDARY_SPEC.styleImportPatterns`
1197
+ * (`*.css` -> `css`), so every spelling below refuses exactly the declared set.
1198
+ */
1199
+ const STYLESHEET_EXTENSIONS = [
1200
+ ...new Set(
1201
+ BOUNDARY_SPEC.styleImportPatterns.map(
1202
+ (pattern) => pattern.replace(/\?\*$/, "").match(/\.([a-z]+)$/)[1],
1203
+ ),
1204
+ ),
1205
+ ];
1206
+ const STYLESHEET_ALTERNATION = STYLESHEET_EXTENSIONS.join("|");
1207
+
1208
+ /** `s` with every regular-expression metacharacter escaped, for an exact match. */
1209
+ function escapeRegExp(s) {
1210
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1211
+ }
1168
1212
 
1169
1213
  /**
1170
1214
  * The `no-restricted-syntax` realisation of the BOUNDARY_SPEC families, each entry tagged
@@ -1187,7 +1231,7 @@ function restrictedSyntaxWithCatalogIds() {
1187
1231
  catalogId: "frontend/no-inline-styling",
1188
1232
  selector: `JSXAttribute[name.name='${attribute}']`,
1189
1233
  message:
1190
- `The ${attribute} attribute is forbidden in app modules; layout comes from the ` +
1234
+ `The ${attribute} attribute is forbidden in app source; layout comes from the ` +
1191
1235
  "react-core components (Stack, Page, ...) and styling from the design tokens.",
1192
1236
  }));
1193
1237
  const inAppAnchors = BOUNDARY_SPEC.restrictInAppAnchors
@@ -1260,12 +1304,40 @@ function restrictedSyntaxWithCatalogIds() {
1260
1304
  },
1261
1305
  ]
1262
1306
  : [];
1307
+ // A stylesheet reached without an import declaration, which no-restricted-imports never
1308
+ // sees: `import("lib/style.css")`, `import(`./themes/${name}.css`)`, and a Vite
1309
+ // `import.meta.glob` whose pattern names a stylesheet (a string, or a string in the array
1310
+ // form; a negated `!` pattern excludes files and is left alone). Any letter case, as the
1311
+ // static patterns match.
1312
+ const stylesheetSpecifier = `/\\.(?:${STYLESHEET_ALTERNATION})(?:\\?.*)?$/i`;
1313
+ const stylesheetGlob = `/^(?!!).*(?:\\.|[{,])(?:${STYLESHEET_ALTERNATION})(?:$|[?,}])/i`;
1314
+ const importMetaGlob =
1315
+ "CallExpression[callee.type='MemberExpression'][callee.object.type='MetaProperty']" +
1316
+ "[callee.object.meta.name='import'][callee.object.property.name='meta']" +
1317
+ "[callee.property.name='glob']";
1318
+ const dynamicStyleImports = [
1319
+ {
1320
+ catalogId: "frontend/no-style-imports",
1321
+ selector:
1322
+ `ImportExpression[source.type='Literal'][source.value=${stylesheetSpecifier}], ` +
1323
+ `ImportExpression > TemplateLiteral > TemplateElement[tail=true][value.raw=${stylesheetSpecifier}]`,
1324
+ message: dynamicStyleImportMessage,
1325
+ },
1326
+ {
1327
+ catalogId: "frontend/no-style-imports",
1328
+ selector:
1329
+ `${importMetaGlob}[arguments.0.type='Literal'][arguments.0.value=${stylesheetGlob}], ` +
1330
+ `${importMetaGlob} > ArrayExpression > Literal[value=${stylesheetGlob}]`,
1331
+ message: dynamicStyleImportMessage,
1332
+ },
1333
+ ];
1263
1334
  return [
1264
1335
  ...rawElements,
1265
1336
  ...rawAttributes,
1266
1337
  ...inAppAnchors,
1267
1338
  ...rawClipboard,
1268
1339
  ...rawRandomUuid,
1340
+ ...dynamicStyleImports,
1269
1341
  {
1270
1342
  catalogId: "frontend/no-dom-html-injection",
1271
1343
  selector: "JSXAttribute[name.name='dangerouslySetInnerHTML']",
@@ -1518,11 +1590,54 @@ function escapeHatchProcessor() {
1518
1590
  }
1519
1591
 
1520
1592
  /**
1521
- * The Terp frontend boundary config (an ESLint flat-config array), scoped to app modules. Spread it
1522
- * into a repo's `eslint.config.js`:
1593
+ * The `no-restricted-imports` entry: deep imports are refused everywhere, and so is every
1594
+ * stylesheet except the ones `allowedStylesheets` names.
1595
+ *
1596
+ * With no allowance, the stylesheet refusal is the declared glob group, which ESLint matches in
1597
+ * any letter case. An allowance cannot be a negated glob in that group: the negation would match
1598
+ * case-insensitively too, so `./THEME.css` would pass as `./theme.css`. It is a regular
1599
+ * expression instead, matched case-sensitively, that refuses a specifier ending in a stylesheet
1600
+ * extension in any letter case unless it is exactly one of the allowed specifiers. Exact
1601
+ * specifiers, so the allowance is never a shape a library's stylesheet, a nested `theme.css` or a
1602
+ * `?inline` / `?url` / `?raw` variant could also match.
1603
+ */
1604
+ function restrictedImports(allowedStylesheets = []) {
1605
+ const anyCase = (extension) =>
1606
+ [...extension].map((letter) => `[${letter.toLowerCase()}${letter.toUpperCase()}]`).join("");
1607
+ const stylesheets =
1608
+ allowedStylesheets.length === 0
1609
+ ? { group: BOUNDARY_SPEC.styleImportPatterns }
1610
+ : {
1611
+ regex:
1612
+ `^(?!(?:${allowedStylesheets.map(escapeRegExp).join("|")})$)` +
1613
+ `.*\\.(?:${STYLESHEET_EXTENSIONS.map(anyCase).join("|")})(?:\\?.*)?$`,
1614
+ caseSensitive: true,
1615
+ };
1616
+ return [
1617
+ "error",
1618
+ {
1619
+ patterns: [
1620
+ {
1621
+ group: BOUNDARY_SPEC.internalImportPatterns,
1622
+ message: deepImportMessage,
1623
+ },
1624
+ { ...stylesheets, message: styleImportMessage },
1625
+ ],
1626
+ },
1627
+ ];
1628
+ }
1629
+
1630
+ /**
1631
+ * The Terp frontend boundary config (an ESLint flat-config array) over all app-authored source.
1632
+ * Spread it into a repo's `eslint.config.js`:
1523
1633
  *
1524
1634
  * import terpBoundaries from "@terpjs/eslint-boundaries";
1525
1635
  * export default [{ ignores: ["dist/**", "src/api/**"] }, ...terpBoundaries];
1636
+ *
1637
+ * One block holds every rule, over every file under `src/` (ADR 0175). It used to be two, and
1638
+ * the structural and security rules sat in the second, scoped to `modules/`: a component beside
1639
+ * the modules carried a stylesheet, `style`, `className`, a raw element and `eval` with no
1640
+ * finding, and a module imported it. The bootstrap block after it widens one thing only.
1526
1641
  */
1527
1642
  export function terpBoundaries() {
1528
1643
  return [
@@ -1542,21 +1657,8 @@ export function terpBoundaries() {
1542
1657
  plugins: { terp: terpPlugin },
1543
1658
  rules: {
1544
1659
  "terp/locale-catalogs-complete": "error",
1545
- // Across src, not only modules: a replaced framework screen (a custom sign-in passed
1546
- // to renderTerpApp) can live beside the bootstrap, outside any module.
1547
1660
  "terp/no-framework-markers": "error",
1548
1661
  "terp/no-untranslated-ui": "error",
1549
- },
1550
- },
1551
- {
1552
- files: BOUNDARY_SPEC.moduleFiles,
1553
- linterOptions: { noInlineConfig: true },
1554
- languageOptions: {
1555
- parser: tseslint.parser,
1556
- parserOptions: { ecmaFeatures: { jsx: true }, sourceType: "module" },
1557
- },
1558
- plugins: { terp: terpPlugin },
1559
- rules: {
1560
1662
  "terp/layout-contract": "error",
1561
1663
  "terp/no-cross-module-imports": "error",
1562
1664
  "terp/no-dom-html-injection": "error",
@@ -1571,21 +1673,18 @@ export function terpBoundaries() {
1571
1673
  message: generatedClientMessage,
1572
1674
  })),
1573
1675
  ],
1574
- "no-restricted-imports": [
1575
- "error",
1576
- {
1577
- patterns: [
1578
- {
1579
- group: BOUNDARY_SPEC.internalImportPatterns,
1580
- message: deepImportMessage,
1581
- },
1582
- {
1583
- group: BOUNDARY_SPEC.styleImportPatterns,
1584
- message: styleImportMessage,
1585
- },
1586
- ],
1587
- },
1588
- ],
1676
+ "no-restricted-imports": restrictedImports(),
1677
+ },
1678
+ },
1679
+ {
1680
+ // The bootstrap loads the token pipeline, which is three stylesheets, and nothing else
1681
+ // changes for it: it is held to every other rule like any app file. It is the app's own
1682
+ // src/main.tsx and no other: `**/src/main.tsx` alone also matches a main.tsx a module
1683
+ // nests under a src/ of its own, so those are ignored here and keep the full refusal.
1684
+ files: BOUNDARY_SPEC.bootstrapFiles,
1685
+ ignores: ["**/modules/**", "**/src/**/src/**"],
1686
+ rules: {
1687
+ "no-restricted-imports": restrictedImports(BOUNDARY_SPEC.bootstrapStylesheets),
1589
1688
  },
1590
1689
  },
1591
1690
  ];
package/src/index.test.js CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { ESLint } from "eslint";
5
5
  import { afterAll, describe, expect, it } from "vitest";
6
6
 
7
- import terpBoundaries from "./index.js";
7
+ import terpBoundaries, { catalogRuleId } from "./index.js";
8
8
 
9
9
  // The frontend analog of the arch harness's meta-tests: prove each boundary rule actually fires on
10
10
  // a violating fixture (and stays quiet on clean, out-of-module code), so "enforced" is real.
@@ -18,7 +18,8 @@ fs.writeFileSync(
18
18
  JSON.stringify({ sourceLocale: "en", locales: { en: {} } }),
19
19
  );
20
20
  const MODULE_FILE = path.join(LINT_ROOT, "src/modules/widgets/Widget.tsx");
21
- const OUTSIDE_FILE = path.join(LINT_ROOT, "src/main.tsx");
21
+ const BOOTSTRAP_FILE = path.join(LINT_ROOT, "src/main.tsx");
22
+ const HELPER_FILE = path.join(LINT_ROOT, "src/diagram/Canvas.tsx");
22
23
 
23
24
  afterAll(() => fs.rmSync(LINT_ROOT, { recursive: true, force: true }));
24
25
 
@@ -341,11 +342,272 @@ describe("terpBoundaries", () => {
341
342
  expect(await lint(code)).toContain("no-restricted-imports");
342
343
  });
343
344
 
344
- it("does not apply the module rules outside src/modules/", async () => {
345
- // A non-module file matches no config block, so the boundary rules never fire on it.
346
- const rules = await lint("export const W = () => <button>x</button>;", OUTSIDE_FILE);
347
- expect(rules).not.toContain("no-restricted-syntax");
348
- expect(rules).not.toContain("terp/no-cross-module-imports");
345
+ it("holds app source outside modules/ to the same boundary (ADR 0175)", async () => {
346
+ // The hole this closes: a component beside the modules, imported by one, carried a
347
+ // stylesheet, style, className, a raw element and the security sinks with no finding.
348
+ const code = [
349
+ 'import "some-diagram-lib/dist/style.css";',
350
+ 'import "./canvas.css";',
351
+ "export const load = () => fetch(\"/api/nodes\");",
352
+ "export const run = (code) => eval(code);",
353
+ "export const paint = (el, html) => { el.innerHTML = html; };",
354
+ "export const Canvas = ({ html }) => (",
355
+ ' <div style={{ height: 600 }} className="canvas">',
356
+ " <button>x</button>",
357
+ " <div dangerouslySetInnerHTML={{ __html: html }} />",
358
+ " </div>",
359
+ ");",
360
+ ].join("\n");
361
+ const messages = await lintMessages(code, HELPER_FILE);
362
+ const rules = await lint(code, HELPER_FILE);
363
+ expect(rules.filter((rule) => rule === "no-restricted-imports")).toHaveLength(2);
364
+ expect(rules).toContain("no-restricted-globals");
365
+ expect(rules).toContain("terp/no-eval");
366
+ expect(rules).toContain("terp/no-dom-html-injection");
367
+ expect(messages.some((message) => message.startsWith("dangerouslySetInnerHTML"))).toBe(true);
368
+ expect(messages).toContain(
369
+ "The style attribute is forbidden in app source; layout comes from the react-core " +
370
+ "components (Stack, Page, ...) and styling from the design tokens.",
371
+ );
372
+ expect(messages.some((message) => message.startsWith("The className attribute"))).toBe(true);
373
+ expect(messages.some((message) => message.includes("Button"))).toBe(true);
374
+ });
375
+
376
+ it("holds every script extension under src, not only .ts and .tsx", async () => {
377
+ // Renaming a helper to .mts or .jsx must not take it out of the boundary.
378
+ const script = 'import "./canvas.css";\nexport const run = (code) => eval(code);';
379
+ for (const extension of ["mts", "cts", "js", "mjs", "cjs"]) {
380
+ const file = path.join(LINT_ROOT, `src/diagram/helper.${extension}`);
381
+ const rules = await lint(script, file);
382
+ expect(rules, extension).toContain("no-restricted-imports");
383
+ expect(rules, extension).toContain("terp/no-eval");
384
+ }
385
+ for (const extension of ["jsx", "tsx"]) {
386
+ const file = path.join(LINT_ROOT, `src/diagram/Canvas.${extension}`);
387
+ const rules = await lint(`${script}\nexport const W = () => <button>x</button>;`, file);
388
+ expect(rules, extension).toContain("no-restricted-imports");
389
+ expect(rules, extension).toContain("terp/no-eval");
390
+ expect(rules, extension).toContain("no-restricted-syntax");
391
+ }
392
+ });
393
+
394
+ it("refuses code outside every module importing into one (no laundering through shared code)", async () => {
395
+ // The route the module-to-module check never sees: a shared file re-exports a module's
396
+ // internals, and a sibling module imports the shared file instead of the module.
397
+ const bridge = path.join(LINT_ROOT, "src/shared/bridge.ts");
398
+ for (const code of [
399
+ 'export { secret } from "../modules/billing/internal/secret";',
400
+ 'export * from "../modules/billing/internal/secret";',
401
+ 'import { secret } from "../modules/billing/internal/secret";\nexport const s = secret;',
402
+ 'export const load = () => import("../modules/billing/internal/secret");',
403
+ ]) {
404
+ expect(await lint(code, bridge), code).toEqual(["terp/no-cross-module-imports"]);
405
+ }
406
+ expect(
407
+ await lintMessages('export { secret } from "../modules/billing/internal/secret";', bridge),
408
+ ).toEqual([
409
+ 'Code outside every module must not import from module "billing"; modules depend on ' +
410
+ "shared code, never the other way round. Move what both need out of the module (or " +
411
+ "into the framework packages), or keep it inside the module.",
412
+ ]);
413
+ // A helper beside the modules is still shared code, whatever its folder is called.
414
+ expect(await lint('import { W } from "./modules/widgets/Widget";\nexport const X = W;', HELPER_FILE))
415
+ .toEqual(["terp/no-cross-module-imports"]);
416
+ // An app-root alias names the app's own modules as surely as a relative path does.
417
+ expect(await lint('export { secret } from "@/modules/billing/internal/secret";', bridge)).toEqual([
418
+ "terp/no-cross-module-imports",
419
+ ]);
420
+ });
421
+
422
+ it("does not take a package's own modules folder for an app module", async () => {
423
+ // A polyfill path has a `modules` segment and is a dependency, from shared code and from a
424
+ // module alike: the rule is about the app's modules, not every path with the word in it.
425
+ const bridge = path.join(LINT_ROOT, "src/shared/polyfills.ts");
426
+ const orders = path.join(LINT_ROOT, "src/modules/orders/Orders.tsx");
427
+ for (const file of [bridge, orders, BOOTSTRAP_FILE]) {
428
+ expect(await lint('import "core-js/modules/es.promise";\nexport {};', file), file).not.toContain(
429
+ "terp/no-cross-module-imports",
430
+ );
431
+ }
432
+ // A module reaching a sibling through the alias is still refused.
433
+ expect(
434
+ await lint('import { secret } from "@/modules/billing/internal/secret";\nexport const s = secret;', orders),
435
+ ).toContain("terp/no-cross-module-imports");
436
+ });
437
+
438
+ it("lets a module import shared code beside the modules", async () => {
439
+ const orders = path.join(LINT_ROOT, "src/modules/orders/Orders.tsx");
440
+ const code = 'import { secret } from "../../shared/bridge";\nexport const s = secret;';
441
+ expect(await lint(code, orders)).toEqual([]);
442
+ });
443
+
444
+ it("still refuses a module importing a sibling module", async () => {
445
+ const orders = path.join(LINT_ROOT, "src/modules/orders/Orders.tsx");
446
+ const code = 'import { secret } from "../billing/internal/secret";\nexport const s = secret;';
447
+ expect(await lintMessages(code, orders)).toEqual([
448
+ 'App module "orders" must not import sibling module "billing"; modules stay independent ' +
449
+ "(share through the framework packages, not each other).",
450
+ ]);
451
+ });
452
+
453
+ it("leaves the bootstrap's module discovery alone (import.meta.glob is not an import)", async () => {
454
+ const code = [
455
+ 'import { renderTerpApp } from "@terpjs/react-core";',
456
+ 'renderTerpApp({ modules: import.meta.glob("./modules/*/module.tsx", { eager: true }) });',
457
+ ].join("\n");
458
+ expect(await lint(code, BOOTSTRAP_FILE)).toEqual([]);
459
+ });
460
+
461
+ it("lets the bootstrap import exactly the token pipeline's stylesheets", async () => {
462
+ const code = [
463
+ 'import "@terpjs/contract/tokens.css";',
464
+ 'import "./house-style.css";',
465
+ 'import "./theme.css";',
466
+ "export {};",
467
+ ].join("\n");
468
+ expect(await lint(code, BOOTSTRAP_FILE)).toEqual([]);
469
+ });
470
+
471
+ it("refuses any other stylesheet in the bootstrap, a library's included", async () => {
472
+ for (const source of ["some-diagram-lib/dist/style.css", "./app.css", "./theme.scss"]) {
473
+ expect(await lint(`import "${source}";\nexport {};`, BOOTSTRAP_FILE)).toEqual([
474
+ "no-restricted-imports",
475
+ ]);
476
+ }
477
+ });
478
+
479
+ it("allows the three by exact specifier, never by shape, query or letter case", async () => {
480
+ // Each of these is one edit away from an allowed specifier. An allowance written as a
481
+ // shape (`**/theme.css`), as a prefix, or matched case-insensitively would pass one.
482
+ for (const source of [
483
+ "./theme.css?inline",
484
+ "./theme.css?raw",
485
+ "./theme.css?url",
486
+ "../src/theme.css",
487
+ "./sub/theme.css",
488
+ "@terpjs/contract/tokens.css?url",
489
+ "some-lib/theme.css",
490
+ "some-lib/house-style.css",
491
+ "./THEME.css",
492
+ "./theme.CSS",
493
+ "./House-Style.css",
494
+ "@TERPJS/contract/tokens.css",
495
+ ]) {
496
+ const messages = await lintMessages(`import "${source}";\nexport {};`, BOOTSTRAP_FILE);
497
+ expect(messages, source).toHaveLength(1);
498
+ expect(messages[0], source).toContain(
499
+ "App-authored stylesheets are forbidden, a library's included",
500
+ );
501
+ }
502
+ });
503
+
504
+ it("gives the allowance to the bootstrap only, not to a file that imports the same sheet", async () => {
505
+ const helper = path.join(LINT_ROOT, "src/diagram/x.tsx");
506
+ expect(await lint('import "./theme.css";\nexport {};', helper)).toEqual([
507
+ "no-restricted-imports",
508
+ ]);
509
+ });
510
+
511
+ it("gives the allowance to the app's own src/main.tsx, not a nested one", async () => {
512
+ // `**/src/main.tsx` alone matches a main.tsx a module nests under a src/ of its own.
513
+ for (const nested of ["src/modules/w/src/main.tsx", "src/modules/src/main.tsx", "src/lib/src/main.tsx"]) {
514
+ expect(
515
+ await lint('import "./theme.css";\nexport {};', path.join(LINT_ROOT, nested)),
516
+ nested,
517
+ ).toEqual(["no-restricted-imports"]);
518
+ }
519
+ });
520
+
521
+ it("keeps refusing deep imports in the bootstrap", async () => {
522
+ // The bootstrap block replaces no-restricted-imports wholesale, so it must carry the
523
+ // deep-import group as well as its own stylesheet allowance.
524
+ const code = 'import "./theme.css";\nimport x from "@terpjs/react-core/src/x";\nexport { x };';
525
+ expect(await lintMessages(code, BOOTSTRAP_FILE)).toEqual([
526
+ expect.stringContaining(
527
+ "Import from the package root (@terpjs/react-core, @terpjs/contract), not its internals.",
528
+ ),
529
+ ]);
530
+ });
531
+
532
+ it("refuses a stylesheet in any letter case outside the bootstrap", async () => {
533
+ for (const source of ["./canvas.CSS", "./Canvas.Scss", "lib/STYLE.LESS?inline"]) {
534
+ expect(await lint(`import "${source}";\nexport {};`, HELPER_FILE), source).toEqual([
535
+ "no-restricted-imports",
536
+ ]);
537
+ }
538
+ });
539
+
540
+ it("refuses a stylesheet loaded through import() or import.meta.glob", async () => {
541
+ // Not an import declaration, so no-restricted-imports never sees it; the bundler loads
542
+ // the sheet all the same. Attributed to the same catalog rule as a static import.
543
+ for (const filePath of [HELPER_FILE, MODULE_FILE, BOOTSTRAP_FILE]) {
544
+ for (const code of [
545
+ 'export const load = () => import("lib/style.css");',
546
+ 'export const load = () => import("./theme.css");',
547
+ 'export const load = () => import("./canvas.SCSS?inline");',
548
+ "export const load = (name) => import(`./themes/${name}.css`);",
549
+ 'export const sheets = import.meta.glob("/x/*.css", { eager: true });',
550
+ 'export const sheets = import.meta.glob("./styles/**/*.{css,scss}");',
551
+ 'export const sheets = import.meta.glob(["./a/*.ts", "./b/*.less"]);',
552
+ ]) {
553
+ const messages = await lintMessages(code, filePath);
554
+ expect(messages, `${filePath}: ${code}`).toEqual([
555
+ expect.stringContaining("is a stylesheet import like any other"),
556
+ ]);
557
+ const eslint = new ESLint({ cwd: LINT_ROOT, overrideConfigFile: true, overrideConfig: terpBoundaries });
558
+ const [result] = await eslint.lintText(code, { filePath });
559
+ expect(result.messages.map(catalogRuleId), code).toEqual(["frontend/no-style-imports"]);
560
+ }
561
+ }
562
+ });
563
+
564
+ it("leaves import() and import.meta.glob of anything but a stylesheet alone", async () => {
565
+ for (const code of [
566
+ 'export const load = () => import("./Widget");',
567
+ 'export const load = (name) => import(`./widgets/${name}.tsx`);',
568
+ 'export const all = import.meta.glob("./modules/*/module.tsx", { eager: true });',
569
+ 'export const all = import.meta.glob(["./a/*.ts", "!**/*.css"]);',
570
+ 'export const all = import.meta.glob("./docs/*.md", { query: "?raw" });',
571
+ ]) {
572
+ expect(await lint(code, HELPER_FILE), code).toEqual([]);
573
+ }
574
+ });
575
+
576
+ it("waives a dynamic stylesheet import with the same catalog marker as a static one", async () => {
577
+ const code = [
578
+ "// terp-allow-no-style-imports: print-only sheet loaded on demand",
579
+ 'export const load = () => import("./print.css");',
580
+ ].join("\n");
581
+ expect(await lint(code, HELPER_FILE)).toEqual([]);
582
+ });
583
+
584
+ it("holds the bootstrap to every other rule", async () => {
585
+ const code = [
586
+ 'import "./theme.css";',
587
+ "export const run = (code) => eval(code);",
588
+ "export const W = () => <button>x</button>;",
589
+ ].join("\n");
590
+ const rules = await lint(code, BOOTSTRAP_FILE);
591
+ expect(rules).toContain("terp/no-eval");
592
+ expect(rules).toContain("no-restricted-syntax");
593
+ });
594
+
595
+ it("lints the template's own bootstrap clean", async () => {
596
+ // The allowance is exactly as wide as the bootstrap a generated app starts from: a
597
+ // stylesheet the template adds is refused here before an app ever meets it.
598
+ const template = fs.readFileSync(
599
+ path.resolve("../../../template/project/frontend/src/main.tsx.jinja"),
600
+ "utf-8",
601
+ );
602
+ // Strip the Jinja tags and keep what they wrap, so every optional line is linted too;
603
+ // a tag left behind, or a placeholder this does not fill, fails here rather than parsing
604
+ // as something else.
605
+ const rendered = template
606
+ .replaceAll("{{ project_name }}", "Demo")
607
+ .replace(/\{%-?[\s\S]*?-?%\}/g, "");
608
+ expect(rendered).not.toContain("{{");
609
+ expect(rendered).not.toContain("{%");
610
+ expect(await lintMessages(rendered, BOOTSTRAP_FILE)).toEqual([]);
349
611
  });
350
612
 
351
613
  it("suppresses a violation with a justified terp-allow marker on the line above", async () => {
package/src/layouts.js CHANGED
@@ -45,6 +45,8 @@ export const LAYOUT_CONTRACTS = {
45
45
  "collection; a split " +
46
46
  "body is two SplitPanes and nothing else; and a dashboard body is its figures and " +
47
47
  "charts in Grid sections, the collection they summarise and the framework states. " +
48
+ "A workspace body is one CanvasHost, the surface that fills the screen, the " +
49
+ "framework states and a ConfirmDialog. " +
48
50
  "A screen that needs no contract " +
49
51
  "composes the plain Page, whose body this contract deliberately leaves unconstrained. " +
50
52
  "Every page, the plain one included, keeps two rules of its frame: its summary band " +
@@ -123,6 +125,16 @@ export const LAYOUT_CONTRACTS = {
123
125
  ConfirmDialog: "dialog",
124
126
  },
125
127
  },
128
+ WorkspacePage: {
129
+ components: {
130
+ CanvasHost: "canvas-host",
131
+ EmptyState: "empty-state",
132
+ ErrorState: "error-state",
133
+ LoadingState: "loading-state",
134
+ Alert: "alert",
135
+ ConfirmDialog: "dialog",
136
+ },
137
+ },
126
138
  DetailPage: {
127
139
  components: {
128
140
  DetailList: "detail-list",
@@ -124,6 +124,18 @@ describe("terp/layout-contract — the page frame's two rules (ADR 0169 §4)", (
124
124
  ]);
125
125
  });
126
126
 
127
+ it("governs a workspace's body: one canvas passes, a hand-sized box is refused (ADR 0179)", async () => {
128
+ // What is drawn ON the canvas is the app's: the svg below is the host's child, not the slot's.
129
+ const code =
130
+ 'import { CanvasHost, EmptyState, WorkspacePage } from "@terpjs/react-core";\n' +
131
+ "export const W = ({title}) => <WorkspacePage title={title}><CanvasHost label={title}><svg viewBox=\"0 0 10 10\" /></CanvasHost></WorkspacePage>;\n" +
132
+ "export const L = ({title}) => <WorkspacePage title={title}><EmptyState title={title} /></WorkspacePage>;\n" +
133
+ "export const X = ({title}) => <WorkspacePage title={title}><div /></WorkspacePage>;";
134
+ expect((await lint(code, configWithContract("standard"))).map((m) => m.message)).toEqual([
135
+ slotViolationMessage("standard", "WorkspacePage", "<div>"),
136
+ ]);
137
+ });
138
+
127
139
  it("passes a status history in the summary", async () => {
128
140
  const code =
129
141
  'import { Page, StatusHistory } from "@terpjs/react-core";\n' +
package/src/spec.js CHANGED
@@ -3,8 +3,11 @@
3
3
  * ./index.js realises them for the React stack; a future stack (e.g. Svelte) can realise the same
4
4
  * spec with its own adapter. The *rules* are shared; only the *enforcement adapter* is per-stack.
5
5
  *
6
- * Structural/security boundaries apply to `src/modules/**`; localization and the refusal of
7
- * react-core's `data-terp` markers apply to all app-authored `src/**`. Framework packages
6
+ * Every rule applies to all app-authored `src/**` (ADR 0175): a rule's scope follows what it is
7
+ * about, and none of them is about a directory. The one rule that *is* about a module's shape,
8
+ * `no-cross-module-imports`, reads the module tree for itself: a module never imports a
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
8
11
  * legitimately define the primitives these rules point back to and are outside an app's
9
12
  * boundary config.
10
13
  */
@@ -19,16 +22,38 @@
19
22
  */
20
23
  export const SPEC_VERSION = "0.39.0";
21
24
 
25
+ /** Every script extension the bundler loads as app source (see `appFiles`). */
26
+ const SOURCE_EXTENSIONS = ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
27
+
22
28
  export const BOUNDARY_SPEC = {
23
29
  /**
24
- * Every app-authored TypeScript source file: its user-facing copy must be cataloged, and it
25
- * never writes react-core's markers.
30
+ * Every app-authored source file, and so every file the boundary applies to. A module, a
31
+ * helper beside the modules and the bootstrap are held alike (ADR 0175), and so is every
32
+ * script extension the bundler loads: a `.jsx` or `.mts` file is app source too, and leaving
33
+ * one out would make renaming a file an escape hatch.
34
+ */
35
+ appFiles: [`**/src/**/*.{${SOURCE_EXTENSIONS.join(",")}}`],
36
+ /**
37
+ * The extensions `appFiles` names, for the tools that walk `src/` themselves rather than
38
+ * through the ESLint config (the escape-hatch budget, the corpus harness), so the files they
39
+ * count are the files the lint holds.
40
+ */
41
+ sourceExtensions: SOURCE_EXTENSIONS,
42
+ /**
43
+ * The app's bootstrap: the file that mounts the app and loads the token pipeline. TypeScript
44
+ * only, as the template ships it: this names an allowance, so it stays as narrow as the file
45
+ * it was written for, and a bootstrap in another extension meets the stricter rule.
46
+ */
47
+ bootstrapFiles: ["**/src/main.{ts,tsx}"],
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.
26
53
  */
27
- appFiles: ["**/src/**/*.{ts,tsx}"],
28
- /** App module files the boundary + frontend security defaults apply to. */
29
- moduleFiles: ["**/modules/**/*.{ts,tsx}"],
54
+ bootstrapStylesheets: ["@terpjs/contract/tokens.css", "./house-style.css", "./theme.css"],
30
55
  /**
31
- * Raw HTML elements an app module must not author directly, mapped to the token-styled
56
+ * Raw HTML elements app source must not author directly, mapped to the token-styled
32
57
  * `@terpjs/react-core` replacement (accessible + theme-consistent by construction).
33
58
  */
34
59
  restrictedElements: {
@@ -42,7 +67,7 @@ export const BOUNDARY_SPEC = {
42
67
  meter: "Meter",
43
68
  },
44
69
  /**
45
- * JSX attributes an app module must not author — styling lives in the design tokens and the
70
+ * JSX attributes app source must not author — styling lives in the design tokens and the
46
71
  * react-core components (`Stack` for layout), never ad-hoc per screen. `className` would be
47
72
  * a side channel into hand-authored CSS, so it is refused alongside `style`.
48
73
  */
@@ -88,9 +113,9 @@ export const BOUNDARY_SPEC = {
88
113
  * guard); modules use the stack's `Link`. External `https://...` anchors stay allowed.
89
114
  */
90
115
  restrictInAppAnchors: true,
91
- /** Package internals an app module must not deep-import (import from the package root). */
116
+ /** Package internals app source must not deep-import (import from the package root). */
92
117
  internalImportPatterns: ["@terpjs/*/src/*", "@terpjs/*/dist/*"],
93
- /** Module-authored stylesheets are refused — theming flows from the app's token source. */
118
+ /** App-authored stylesheets are refused — theming flows from the app's token source. */
94
119
  styleImportPatterns: [
95
120
  "*.css",
96
121
  "**/*.css",