@starci/eslint-canon-fe 5.1.2 → 6.0.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +78 -2
  2. package/README.md +17 -18
  3. package/brand-values.mjs +1 -3
  4. package/class-names.mjs +9 -9
  5. package/client-boundary.mjs +125 -37
  6. package/comments.mjs +14 -21
  7. package/docs/client-boundary.md +26 -1
  8. package/docs/grammar-boundary.md +33 -0
  9. package/docs/hygiene.md +15 -4
  10. package/docs/lint-escape-hatch.md +3 -1
  11. package/docs/next-conventions.md +26 -0
  12. package/docs/size-growth.md +29 -0
  13. package/docs/spec-quality.md +15 -7
  14. package/docs/status-colors.md +32 -0
  15. package/docs/translation.md +4 -0
  16. package/docs/transport.md +36 -9
  17. package/e2e-shape.mjs +20 -23
  18. package/env-owner.mjs +1 -1
  19. package/file-layout.mjs +105 -103
  20. package/formatting.mjs +2 -4
  21. package/grammar-boundary.mjs +85 -9
  22. package/hooks-folder.mjs +17 -16
  23. package/hygiene.mjs +370 -92
  24. package/icon.mjs +21 -20
  25. package/index.mjs +27 -85
  26. package/landmark.mjs +0 -11
  27. package/lib/bindings.mjs +144 -0
  28. package/lib/config.mjs +79 -0
  29. package/lib/hfs.mjs +48 -0
  30. package/lib/next.mjs +6 -0
  31. package/lib/platform.mjs +66 -0
  32. package/lib/react.mjs +28 -0
  33. package/lib/scope.mjs +119 -19
  34. package/lib/status-tones.generated.mjs +9 -0
  35. package/lib/types.mjs +63 -0
  36. package/lib/why.mjs +41 -11
  37. package/lint-escape-hatch.mjs +17 -15
  38. package/loading.mjs +9 -16
  39. package/naming.mjs +8 -2
  40. package/next-conventions.mjs +109 -25
  41. package/package.json +9 -4
  42. package/props-and-slots.mjs +19 -13
  43. package/runtime/engine/plain-object.mjs +5 -0
  44. package/runtime/engine/runtime-root.mjs +32 -0
  45. package/runtime/engine/yaml.mjs +161 -0
  46. package/runtime/knowledge/hfs/slots.yaml +1072 -0
  47. package/runtime/scripts/lib/git.mjs +53 -0
  48. package/runtime/scripts/lib/glob.mjs +23 -0
  49. package/runtime/scripts/lib/hfs-allows.mjs +42 -0
  50. package/runtime/scripts/lib/hfs-slots.mjs +722 -0
  51. package/runtime/scripts/lib/hfs-view.mjs +68 -0
  52. package/runtime/scripts/lib/next-contract.mjs +14 -0
  53. package/runtime/scripts/lib/path-key.mjs +17 -0
  54. package/runtime/scripts/lib/recorded-lines.mjs +27 -0
  55. package/served-locale.mjs +30 -16
  56. package/shape-slot.mjs +22 -20
  57. package/size-and-state-budget.mjs +41 -23
  58. package/size-growth.mjs +58 -0
  59. package/spec-quality.mjs +95 -16
  60. package/status-colors.mjs +139 -0
  61. package/the-split.mjs +13 -13
  62. package/tokens.mjs +26 -34
  63. package/translation.mjs +52 -19
  64. package/transport.mjs +437 -89
  65. package/type-safety.mjs +8 -17
  66. package/typography.mjs +7 -11
  67. package/vendor-boundary.mjs +5 -27
  68. package/lint-adoption.mjs +0 -79
@@ -0,0 +1,68 @@
1
+ // hfs-view.mjs - the frozen view of one repository's HFS slots that the lint factories hand their rules
2
+ // (`settings.starci.hfs`). Both @starci/eslint-canon-be and @starci/eslint-canon-fe ship a byte copy of this file in their
3
+ // runtime/ bundle (packages/hfs/scripts/sync-runtime.mjs), so a path-scoped rule in either package asks the SAME resolver the
4
+ // architecture machine and `hfs check` use, and never tests a path with a regular expression of its own.
5
+ import path from 'node:path';
6
+ import { allowsFile } from './hfs-allows.mjs';
7
+ import { openHfs } from './hfs-slots.mjs';
8
+
9
+ const posix = (p) => String(p).replace(/\\/g, '/');
10
+ const isAbsoluteAny = (text) => path.isAbsolute(text) || /^[A-Za-z]:\//.test(text);
11
+
12
+ /**
13
+ * The view rules read, over an opened resolver.
14
+ *
15
+ * @param {object} opened - The result of `openHfs` (manifest, repo and resolver methods).
16
+ * @param {string} repoRoot - The absolute repository root.
17
+ * @returns {object} The frozen view: profile, apps, connections, ruleParams, relative, classify, slotOf, tierOf, ownerOf, slot.
18
+ */
19
+ export function hfsView(opened, repoRoot) {
20
+ const rel = (file) => {
21
+ const text = posix(file);
22
+ if (!isAbsoluteAny(text)) return text.replace(/^\.\//, '');
23
+ return posix(path.relative(repoRoot, file));
24
+ };
25
+ const slotCache = new Map();
26
+ const classify = (file) => {
27
+ const key = rel(file);
28
+ if (!slotCache.has(key)) slotCache.set(key, opened.classifyPath(key));
29
+ return slotCache.get(key);
30
+ };
31
+ return Object.freeze({
32
+ repoRoot,
33
+ profile: opened.repo.profile,
34
+ apps: opened.repo.apps,
35
+ connections: opened.repo.connections,
36
+ ruleParams: opened.ruleParams(),
37
+ /** The repository-relative, forward-slash form of a linted filename. */
38
+ relative: rel,
39
+ /** The classification of a file: `{ slot, tier, owner?, bindings? ... }` or a no-slot status. */
40
+ classify,
41
+ /** The slot id that owns a file, or null when no slot does. */
42
+ slotOf: (file) => classify(file).slot ?? null,
43
+ /** The tier of a file, or null. */
44
+ tierOf: (file) => opened.tierOf(rel(file)) ?? null,
45
+ /** The owner root of a file, or null. */
46
+ ownerOf: (file) => opened.ownerOf(rel(file))?.root ?? null,
47
+ /** What the slot that owns a file says about it: `{ slot, root, relative, allowed, entry?, forbiddenBy?, allows }`, or null when the slot names no `allows`. */
48
+ allows: (file) => allowsFile(opened, rel(file)),
49
+ /** A slot definition by id. */
50
+ slot: (id) => opened.slot(id),
51
+ });
52
+ }
53
+
54
+ /**
55
+ * The view of the repository on disk whose root is `repoRoot`, against the manifest under `runtimeRoot`.
56
+ *
57
+ * @param {{ runtimeRoot: string, repoRoot: string }} input - Where the manifest copy lives and the repository root.
58
+ * @returns {object} The frozen view.
59
+ */
60
+ export const openHfsView = ({ runtimeRoot, repoRoot }) => hfsView(openHfs({ root: runtimeRoot, repoRoot }), repoRoot);
61
+
62
+ /**
63
+ * The view of an in-memory declaration (rule tests): no file is read except the manifest.
64
+ *
65
+ * @param {{ runtimeRoot: string, declaration: object, repoRoot: string }} input - Manifest root, hfs.json object, linted root.
66
+ * @returns {object} The frozen view.
67
+ */
68
+ export const declaredHfsView = ({ runtimeRoot, declaration, repoRoot }) => hfsView(openHfs({ root: runtimeRoot, declaration }), repoRoot);
@@ -0,0 +1,14 @@
1
+ // next-contract.mjs - Next.js's own contract for route segment files, stated once. The architecture machine
2
+ // (scripts/checks/code-patterns/next.mjs) and @starci/eslint-canon-fe (its runtime/ copy, lib/next.mjs) read it here, so a
3
+ // naming or aliasing law never asks an author to spell a framework-reserved export differently.
4
+
5
+ /** Exports Next reads by name from a route segment file. */
6
+ export const NEXT_RESERVED_EXPORTS = Object.freeze(new Set([
7
+ 'dynamic', 'dynamicParams', 'fetchCache', 'generateMetadata', 'generateStaticParams', 'generateViewport',
8
+ 'maxDuration', 'metadata', 'preferredRegion', 'revalidate', 'runtime', 'viewport',
9
+ ]));
10
+
11
+ /** The file stems Next mounts as a segment file under a route tree. */
12
+ export const NEXT_ROUTE_SEGMENT_STEMS = Object.freeze(new Set([
13
+ 'default', 'error', 'global-error', 'layout', 'loading', 'not-found', 'page', 'route', 'template',
14
+ ]));
@@ -0,0 +1,17 @@
1
+ // path-key.mjs — spelling and comparing paths the way this host's filesystem does.
2
+ import path from 'node:path';
3
+
4
+ const WIN = process.platform === 'win32';
5
+
6
+ /** `p` with every backslash turned into a forward slash; null and undefined read as ''. */
7
+ export const slash = (p) => String(p ?? '').replaceAll('\\', '/');
8
+ /** A relative path in git's spelling: forward slashes, no leading './'. */
9
+ export const posixPath = (p) => slash(p).replace(/^\.\//, '');
10
+ /** Whether posix `file` is `prefix` itself or under it (`file === prefix || file` starts with `prefix/`). */
11
+ export const sameOrUnder = (file, prefix) => file === prefix || file.startsWith(`${prefix}/`);
12
+ /** `p` case-folded where the filesystem ignores case (Windows). */
13
+ export const foldCase = (p) => (WIN ? p.toLowerCase() : p);
14
+ /** Whether two spellings name the same path on this host's filesystem. */
15
+ export const samePath = (a, b) => foldCase(a) === foldCase(b);
16
+ /** A path's comparable identity: absolute, forward slashes, no trailing slash, case-folded on Windows. */
17
+ export const pathKey = (p) => foldCase(slash(path.resolve(p)).replace(/\/+$/, ''));
@@ -0,0 +1,27 @@
1
+ // recorded-lines.mjs - the one home of the file-size ratchet's arithmetic (R20 HFS_SIZE_GROWTH), shared by the back-end
2
+ // and front-end lint canons (each ships a byte copy in its runtime/ bundle, kept by packages/hfs/scripts/sync-runtime.mjs).
3
+ import path from 'node:path';
4
+ import { runGit } from './git.mjs';
5
+
6
+ /** The line count of a text; a trailing newline does not open a line. */
7
+ export const lineCount = (text) => {
8
+ const lines = String(text).split(/\r?\n/);
9
+ return lines.at(-1) === '' ? lines.length - 1 : lines.length;
10
+ };
11
+
12
+ /** The line count above which a file may not grow: the soft budget when `hardGrowth` holds, else no limit. */
13
+ export const hardGrowthLines = ({ soft, hardGrowth }) => (hardGrowth ? soft : Number.POSITIVE_INFINITY);
14
+
15
+ /**
16
+ * The line count of a file at a git revision, or null when the file did not exist there or git is absent.
17
+ *
18
+ * @param {string} filename - Absolute path of the file.
19
+ * @param {string} ref - The revision, `HEAD` by default (the parent of the commit being made).
20
+ * @returns {number | null} The recorded line count.
21
+ */
22
+ export const recordedLines = (filename, ref = 'HEAD') => {
23
+ const r = runGit(['show', `${ref}:./${path.basename(filename)}`], { dir: path.dirname(filename), maxBuffer: 64 * 1024 * 1024 });
24
+ // no repository, no such revision, or a new file: all mean there is no recorded size to compare with
25
+ if (r.error || r.status !== 0) return null;
26
+ return lineCount(r.stdout);
27
+ };
package/served-locale.mjs CHANGED
@@ -18,8 +18,8 @@
18
18
  * unconditionally satisfies both and is wrong. That case is a review question and LOCALE-2 is where
19
19
  * it is argued; pretending otherwise would be the rule claiming a guarantee it does not have.
20
20
  *
21
- * WHY THE FIRST RULE KEYS ON THE TERMINAL LINK RATHER THAN ON THE FILE PATH. A repository may name
22
- * its client folder anything, and a path pattern that guessed wrong would either miss the real chain
21
+ * WHY THE FIRST RULE KEYS ON THE TERMINAL LINK RATHER THAN ON THE SLOT. A repository may name
22
+ * its client folder anything below `modules/api`, and a pattern that guessed wrong would either miss the real chain
23
23
  * or fire on every helper beside it. The chain is identifiable by what it does: it builds the link
24
24
  * that talks to the network.
25
25
  *
@@ -31,17 +31,36 @@
31
31
  * link; a chain is assembled elsewhere, which is where the locale belongs.
32
32
  */
33
33
 
34
- /** Forward-slash form of a filename, so Windows paths compare like every other path. */
35
- const normalize = (filename) => String(filename || "").replace(/\\/g, "/")
34
+ import { hfsOf } from "./lib/hfs.mjs"
35
+ import { fileOf, inSlot, isSpecFile, stem } from "./lib/scope.mjs"
36
+
37
+ /** The slots that hold transport: the app's `modules/api` and the shared api package. Neither slot names its links, see the note on `linkFileName`. */
38
+ const TRANSPORT_SLOTS = ["fe.modules.api", "fe.package.api"]
39
+
40
+ /**
41
+ * The name of the file when it sits directly in a `links/` folder of a transport slot, else null.
42
+ *
43
+ * NO SLOT NAMES A LINK. `fe.modules.api` and `fe.package.api` own their whole tree, so the transport slots decide WHERE a
44
+ * link may be (a transport file) and the folder called `links` is the one fact left to the rule; the manifest would
45
+ * carry it as a role (`locale-link: links/locale.ts`) and this function would ask for that role instead.
46
+ */
47
+ const linkFileName = (context) => {
48
+ if (!inSlot(context, ...TRANSPORT_SLOTS)) return null
49
+ const parts = hfsOf(context).relative(fileOf(context)).split("/")
50
+ return parts.at(-2) === "links" ? parts.at(-1) : null
51
+ }
36
52
 
37
53
  /**
38
54
  * The link file that owns the locale header.
39
55
  *
40
- * This is the ONE file allowed to write it, and it is recognised by path rather than by content:
41
- * the point of the second rule is that the header appears in one place, so that place has to be
42
- * named somewhere, and a name is what the law and the rule can both refer to.
56
+ * This is the ONE file allowed to write it: the `locale` link of a transport slot. The point of the second rule is that
57
+ * the header appears in one place, so that place has to be named somewhere, and a name is what the law and the rule can
58
+ * both refer to.
43
59
  */
44
- export const isLocaleLinkFile = (filename) => /\/links\/locale\.[cm]?tsx?$/.test(normalize(filename))
60
+ const isLocaleLinkFile = (context) => {
61
+ const name = linkFileName(context)
62
+ return name !== null && stem(name) === "locale"
63
+ }
45
64
 
46
65
  /**
47
66
  * One link's own implementation, rather than a chain of them.
@@ -55,10 +74,7 @@ export const isLocaleLinkFile = (filename) => /\/links\/locale\.[cm]?tsx?$/.test
55
74
  * A file under `links/` is one link. A chain is assembled somewhere else, which is exactly where the
56
75
  * locale belongs.
57
76
  */
58
- export const isLinkImplementationFile = (filename) => /\/links\/[^/]+$/.test(normalize(filename))
59
-
60
- /** A spec or test file - it asserts about production shapes rather than being one. */
61
- export const isTestFile = (filename) => /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(normalize(filename))
77
+ const isLinkImplementationFile = (context) => linkFileName(context) !== null
62
78
 
63
79
  /** The header a request declares its language in. */
64
80
  export const LOCALE_HEADER = "x-locale"
@@ -105,11 +121,10 @@ export const rules = {
105
121
  },
106
122
  },
107
123
  create(context) {
108
- const filename = context.filename || context.getFilename()
109
124
  // A single link's implementation is not a chain - `links/http.ts` constructs the terminal link
110
125
  // because defining it IS its job, and there is no correct way to attach a locale there. A
111
126
  // spec asserts about a chain rather than being one.
112
- if (isLinkImplementationFile(filename) || isTestFile(filename)) return {}
127
+ if (isLinkImplementationFile(context) || isSpecFile(fileOf(context))) return {}
113
128
  let terminalNode = null
114
129
  let attachesLocale = false
115
130
  const note = (node) => {
@@ -144,8 +159,7 @@ export const rules = {
144
159
  },
145
160
  },
146
161
  create(context) {
147
- const filename = context.filename || context.getFilename()
148
- if (isLocaleLinkFile(filename)) return {}
162
+ if (isLocaleLinkFile(context)) return {}
149
163
  return {
150
164
  Property(node) {
151
165
  if (propertyKeyOf(node) === LOCALE_HEADER) {
package/shape-slot.mjs CHANGED
@@ -19,18 +19,21 @@
19
19
  * never wrong, beyond it.
20
20
  */
21
21
 
22
- import { normalizePath } from "./lib/path.mjs"
22
+ import { hfsOf } from "./lib/hfs.mjs"
23
+ import { classifyImport, fileOf, inSlot, isSpecFile, kindOfFile, roleOfFile } from "./lib/scope.mjs"
23
24
 
24
- /** The pure half of a split tier, and which tier it is. */
25
- const pureHalf = (filename) => {
26
- const match = normalizePath(filename).match(
27
- /\/src\/(?:components|features)\/(blocks|pages|layouts|overlays)\/(?:[^/]+\/)*[A-Z][A-Za-z0-9]*\/component\.tsx$/,
28
- )
29
- return match ? match[1] : null
30
- }
25
+ /** The layers and feature kinds that split into a connected `index.tsx` and a pure `component.tsx`; a shared package's layers never split. */
26
+ const SPLIT_KINDS = new Set(["blocks", "pages", "layouts", "overlays"])
27
+
28
+ /** The folder name of the linted file: the surface a `component.tsx` or `index.tsx` belongs to. */
29
+ const surfaceName = (context) => hfsOf(context).relative(fileOf(context)).split("/").slice(-2)[0]
30
+
31
+ /** Whether the linted file sits in a component or feature owner of a split kind. */
32
+ const inSplitTier = (context) => inSlot(context, "fe.components", "fe.feature") && SPLIT_KINDS.has(kindOfFile(context))
31
33
 
32
- /** Specs render the pure half from fixtures; that is the point of it. */
33
- const isSpec = (filename) => /\.(spec|test)\.[cm]?[jt]sx?$/.test(normalizePath(filename))
34
+ /** The pure half of a split tier (the drawing role of a surface folder), and which tier it is. */
35
+ const pureHalf = (context) =>
36
+ inSplitTier(context) && roleOfFile(context) === "drawing" && /^[A-Z][A-Za-z0-9]*$/.test(surfaceName(context)) ? kindOfFile(context) : null
34
37
 
35
38
  /** Type names that carry a rendered tree rather than data. */
36
39
  const NON_ATOM_TYPE = /^(?:ReactNode|ReactElement|ReactPortal|JSX\.Element|Element|ComponentType|FC|FunctionComponent|ElementType|ComponentProps|RenderFunction)$/
@@ -94,7 +97,7 @@ export const basePropsAtom = {
94
97
  },
95
98
  },
96
99
  create(context) {
97
- const tier = pureHalf(context.filename || context.getFilename())
100
+ const tier = pureHalf(context)
98
101
  if (!tier) return {}
99
102
  let types = new Map()
100
103
 
@@ -202,16 +205,15 @@ export const baseImportPair = {
202
205
  },
203
206
  },
204
207
  create(context) {
205
- const filename = normalizePath(context.filename || context.getFilename())
206
- const base = filename.split("/").pop() || ""
207
- const isOwnIndex = base === "index.tsx"
208
- const spec = isSpec(filename)
209
- const inTier = /\/src\/(?:components|features)\/(blocks|pages|layouts|overlays)\//.test(filename)
210
- const reachesPure = (source) => /(?:^|\/)component(?:\.tsx)?$/.test(source)
208
+ const isOwnIndex = roleOfFile(context) === "entry"
209
+ const spec = isSpecFile(fileOf(context))
210
+ const inTier = inSplitTier(context)
211
+ // An import reaches a pure half when the file it resolves to has the `drawing` role of its slot.
212
+ const reachesPure = (source) => classifyImport(context, source)?.role === "drawing"
211
213
 
212
214
  const check = (node, source) => {
213
215
  if (typeof source !== "string" || !reachesPure(source)) return
214
- const isSibling = source === "./component" || source === "./component.tsx"
216
+ const isSibling = /^\.\/[^/]+$/.test(source)
215
217
  if (isSibling && (isOwnIndex || spec)) return
216
218
  if (isSibling && !inTier) return
217
219
  context.report({ node, messageId: "reach", data: { source } })
@@ -260,7 +262,7 @@ export const noDataStatusShape = {
260
262
  },
261
263
  },
262
264
  create(context) {
263
- if (!pureHalf(context.filename || context.getFilename())) return {}
265
+ if (!pureHalf(context)) return {}
264
266
  const check = (name, node) => {
265
267
  const members = node?.type === "TSUnionType" ? node.types : [node]
266
268
  for (const member of members) {
@@ -308,7 +310,7 @@ export const slotStatusThroughSlotView = {
308
310
  },
309
311
  },
310
312
  create(context) {
311
- if (pureHalf(context.filename || context.getFilename()) !== "blocks") return {}
313
+ if (pureHalf(context) !== "blocks") return {}
312
314
  const check = (node, test) => {
313
315
  const flag = statusFlagOf(test)
314
316
  if (flag) context.report({ node, messageId: "branch", data: { flag } })
@@ -18,17 +18,30 @@
18
18
  * socket), so the loop in a component is always the wrong one.
19
19
  */
20
20
 
21
- import { isSpecFile } from "./lib/scope.mjs"
22
- import { normalizePath } from "./lib/path.mjs"
21
+ import { hfsOf } from "./lib/hfs.mjs"
22
+ import { fileOf, isSpecFile, roleOfFile, slotOfFile } from "./lib/scope.mjs"
23
23
 
24
- /** The largest a component file may be. */
25
- export const MAX_COMPONENT_LINES = 300
26
-
27
- /** The most `useState` calls one connected unit may hold. */
28
- export const MAX_STATE_HOOKS = 6
24
+ /**
25
+ * The budget the slot of the linted file states (`budget` in knowledge/hfs/slots.yaml), or an empty one when no slot owns the file
26
+ * or the slot states none. The numbers live in the manifest only: a rule that kept its own copy would drift from it.
27
+ */
28
+ const budgetOf = (context) => {
29
+ const id = slotOfFile(context)
30
+ return id === null ? {} : hfsOf(context).slot(id)?.budget ?? {}
31
+ }
29
32
 
30
- /** The most data hooks one connected unit may read. */
31
- export const MAX_DATA_HOOKS = 6
33
+ /**
34
+ * The line limit of the linted file: the budget keyed by the file name its role has in the slot (`component.tsx` for the drawing,
35
+ * `index.tsx` for the entry), else the slot's `file` budget (hooks 200, modules 400), else null.
36
+ */
37
+ const lineBudgetOf = (context) => {
38
+ const role = roleOfFile(context)
39
+ const id = slotOfFile(context)
40
+ const fileName = role === null || id === null ? undefined : hfsOf(context).slot(id)?.roles?.[role]
41
+ const budget = budgetOf(context)
42
+ const limit = fileName !== undefined && typeof budget[fileName] === "number" ? budget[fileName] : budget.file
43
+ return typeof limit === "number" ? limit : null
44
+ }
32
45
 
33
46
  /** A hook that reads remote data. */
34
47
  const DATA_HOOK = /^use\w*(?:Swr|SWR|Query|Mutation|Fetch|Infinite|Subscription)\w*$/
@@ -58,26 +71,28 @@ const isUnitName = (name) => Boolean(name) && (/^[A-Z]/.test(name) || /^use[A-Z0
58
71
 
59
72
  // -- BUDGET-1 --------------------------------------------------------------------------------------
60
73
 
61
- /** A component file is at most 300 lines. */
74
+ /** A file is within the line budget its slot states for its role (`component.tsx`, `index.tsx`) or for every file (`file`). */
62
75
  export const componentLineBudget = {
63
76
  meta: {
64
77
  type: "suggestion",
65
- docs: { description: `A component file has at most ${MAX_COMPONENT_LINES} lines.` },
78
+ docs: { description: "A file stays within the line budget its slot states (`component.tsx`, `index.tsx`, `file`)." },
66
79
  schema: [],
67
80
  messages: {
68
81
  lines:
69
- "This component file has {{count}} lines; the budget is {{max}}. A file this size is several units in one: split the drawing from the data, and the sections from each other, so each part can be named, tested and reviewed on its own.",
82
+ "This file has {{count}} lines; the budget is {{max}}. A file this size is several units in one: split the drawing from the data, and the sections from each other, so each part can be named, tested and reviewed on its own.",
70
83
  },
71
84
  },
72
85
  create(context) {
73
- const filename = normalizePath(context.filename || context.getFilename())
74
- if (!filename.endsWith(".tsx") || isSpecFile(filename) || !filename.includes("/src/")) return {}
86
+ // A spec is not held to a budget; a file has one when its role or its slot states it.
87
+ if (isSpecFile(fileOf(context))) return {}
88
+ const max = lineBudgetOf(context)
89
+ if (max === null) return {}
75
90
  const source = context.sourceCode || context.getSourceCode()
76
91
  return {
77
92
  Program(node) {
78
93
  // A trailing newline is not a line of code.
79
94
  const count = source.lines.length - (source.lines[source.lines.length - 1] === "" ? 1 : 0)
80
- if (count > MAX_COMPONENT_LINES) context.report({ node, messageId: "lines", data: { count, max: MAX_COMPONENT_LINES } })
95
+ if (count > max) context.report({ node, messageId: "lines", data: { count, max } })
81
96
  },
82
97
  }
83
98
  },
@@ -85,11 +100,11 @@ export const componentLineBudget = {
85
100
 
86
101
  // -- BUDGET-2 --------------------------------------------------------------------------------------
87
102
 
88
- /** A connected unit holds at most six state hooks and reads at most six data hooks. */
103
+ /** A connected unit holds at most the slot's `useState` budget of state hooks and reads at most its `dataHooks` budget of data hooks. */
89
104
  export const unitHookBudget = {
90
105
  meta: {
91
106
  type: "suggestion",
92
- docs: { description: `A unit has at most ${MAX_STATE_HOOKS} state hooks and ${MAX_DATA_HOOKS} data hooks.` },
107
+ docs: { description: "A unit stays within the state-hook and data-hook budget its slot states (`useState`, `dataHooks`)." },
93
108
  schema: [],
94
109
  messages: {
95
110
  state:
@@ -99,7 +114,10 @@ export const unitHookBudget = {
99
114
  },
100
115
  },
101
116
  create(context) {
102
- if (isSpecFile(context.filename || context.getFilename())) return {}
117
+ if (isSpecFile(fileOf(context))) return {}
118
+ // A slot that states no `useState` / `dataHooks` budget puts no bound on that count: the rule refuses to invent one.
119
+ const { useState: maxState, dataHooks: maxData } = budgetOf(context)
120
+ if (typeof maxState !== "number" && typeof maxData !== "number") return {}
103
121
  /** One frame per function being walked; only a component or hook frame accumulates. */
104
122
  const frames = []
105
123
  const enter = (node) => frames.push({ node, name: functionName(node), state: 0, data: 0 })
@@ -107,11 +125,11 @@ export const unitHookBudget = {
107
125
  const frame = frames.pop()
108
126
  if (!frame || !isUnitName(frame.name)) return
109
127
  const at = frame.node.id || frame.node
110
- if (frame.state > MAX_STATE_HOOKS) {
111
- context.report({ node: at, messageId: "state", data: { name: frame.name, count: frame.state, max: MAX_STATE_HOOKS } })
128
+ if (typeof maxState === "number" && frame.state > maxState) {
129
+ context.report({ node: at, messageId: "state", data: { name: frame.name, count: frame.state, max: maxState } })
112
130
  }
113
- if (frame.data > MAX_DATA_HOOKS) {
114
- context.report({ node: at, messageId: "data", data: { name: frame.name, count: frame.data, max: MAX_DATA_HOOKS } })
131
+ if (typeof maxData === "number" && frame.data > maxData) {
132
+ context.report({ node: at, messageId: "data", data: { name: frame.name, count: frame.data, max: maxData } })
115
133
  }
116
134
  }
117
135
  return {
@@ -163,7 +181,7 @@ export const noHandRolledPolling = {
163
181
  },
164
182
  },
165
183
  create(context) {
166
- if (isSpecFile(context.filename || context.getFilename())) return {}
184
+ if (isSpecFile(fileOf(context))) return {}
167
185
  const source = context.sourceCode || context.getSourceCode()
168
186
  return {
169
187
  CallExpression(node) {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The rule that holds the file size budget (HFS R20 `HFS_SIZE_GROWTH`, the file-level half).
3
+ *
4
+ * A source file has a hard-growth budget of `fileLines.soft` lines while `fileLines.hardGrowth` holds
5
+ * (`ruleParams.fe.fileLines` of the slot manifest, read through the slot view `hfsOf(context).ruleParams`). `file-size-growth` is the ratchet and
6
+ * fails only on a file that must not be this long: a NEW file over the budget, or an existing file over the budget that
7
+ * is longer than its recorded size. The recorded size is the file's line count at the parent commit
8
+ * (`git show HEAD:<file>`). A file may stay as large as it is; it may not grow, and it may not be born large. The rule
9
+ * takes no option: the budget is the manifest's, the baseline is git's.
10
+ *
11
+ * There is no baseline file and no allowlist: the record is the repository's own history. A spec and an e2e file are
12
+ * source files like any other; a declaration file (`*.d.ts`) carries no behaviour and is not governed. Component,
13
+ * hook and state budgets are stricter still where they apply (`size-and-state-budget`); this ratchet is the one that
14
+ * needs the previous revision.
15
+ */
16
+ import { hfsOf } from "./lib/hfs.mjs"
17
+ import { hardGrowthLines, lineCount, recordedLines } from "./runtime/scripts/lib/recorded-lines.mjs"
18
+
19
+ /** Whether a file is a source file this budget governs. */
20
+ const governed = (filename) => /\.[cm]?tsx?$/.test(filename) && !/\.d\.[cm]?ts$/.test(filename)
21
+
22
+ /** The ratchet: a file over the budget must not be new and must not grow. */
23
+ export const fileSizeGrowth = {
24
+ meta: {
25
+ type: "problem",
26
+ docs: { description: "A source file over the budget is neither new nor longer than its recorded size." },
27
+ schema: [],
28
+ messages: {
29
+ born: "This new file has {{lines}} lines, over the budget of {{max}}. A new file starts within the budget: split it by responsibility.",
30
+ grew: "This file has {{lines}} lines, over the budget of {{max}}, and it was {{recorded}} at the parent commit. A file over the budget may not grow: move the new code into its own file.",
31
+ },
32
+ },
33
+ create(context) {
34
+ const filename = context.filename || context.getFilename()
35
+ if (!governed(filename)) return {}
36
+ const max = hardGrowthLines(hfsOf(context).ruleParams.fileLines)
37
+ return {
38
+ "Program:exit"(node) {
39
+ const lines = lineCount((context.sourceCode || context.getSourceCode()).text)
40
+ if (lines <= max) return
41
+ const recorded = recordedLines(filename)
42
+ const loc = { line: 1, column: 0 }
43
+ if (recorded === null) context.report({ node, loc, messageId: "born", data: { lines, max } })
44
+ else if (lines > recorded) context.report({ node, loc, messageId: "grew", data: { lines, max, recorded } })
45
+ },
46
+ }
47
+ },
48
+ }
49
+
50
+ /** The rules this law contributes to the plugin. */
51
+ export const rules = {
52
+ "file-size-growth": fileSizeGrowth,
53
+ }
54
+
55
+ /** The ratchet is an error. */
56
+ export const recommended = {
57
+ "starci-fe/file-size-growth": "error",
58
+ }