@cosmicdrift/kumiko-guards 0.413.1 → 0.415.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 (53) hide show
  1. package/README.md +15 -9
  2. package/package.json +4 -4
  3. package/src/_lib/agent-docs-api-nodes.ts +9 -2
  4. package/src/_lib/agent-docs-api-render.ts +31 -10
  5. package/src/_lib/agent-docs-api.ts +13 -9
  6. package/src/_lib/agent-docs-feature-imports.ts +12 -1
  7. package/src/_lib/baseline-compare.ts +1 -2
  8. package/src/_lib/doc-status.ts +8 -4
  9. package/src/_lib/dockerfile.ts +28 -5
  10. package/src/_lib/escaped-literal.ts +26 -0
  11. package/src/_lib/npm-registry.ts +2 -2
  12. package/src/_lib/run-slots.ts +4 -6
  13. package/src/_lib/security-audit.ts +22 -6
  14. package/src/_lib/test-es-raw-writes.ts +5 -3
  15. package/src/changes.json +51 -0
  16. package/src/check-security.ts +4 -3
  17. package/src/guard-app-dockerfile.ts +29 -12
  18. package/src/guard-ignore-tag-reason.ts +18 -4
  19. package/src/guard-internal-subpath-imports.ts +35 -25
  20. package/src/guard-rls-session-settings.ts +48 -6
  21. package/src/guard-schema-cli-features.ts +22 -1
  22. package/src/guard-security-plugin-suppression.ts +368 -0
  23. package/src/guard-test-es-row-writes.ts +2 -1
  24. package/src/guard-unsafe-array-param.ts +4 -7
  25. package/src/pre-push.sh +46 -6
  26. package/src/run-guards.ts +2 -28
  27. package/src/run-repo-checks.ts +0 -6
  28. package/src/run-steps-parallel.ts +4 -4
  29. package/src/run-ui-guards.ts +1 -15
  30. package/src/_lib/german-test-title.ts +0 -94
  31. package/src/_lib/primitives-access.ts +0 -23
  32. package/src/check-predicates.ts +0 -244
  33. package/src/guard-admin-api.ts +0 -138
  34. package/src/guard-direct-fetch.ts +0 -161
  35. package/src/guard-error-reasons.ts +0 -210
  36. package/src/guard-event-store-writes.ts +0 -124
  37. package/src/guard-i18n-locale-terminology.ts +0 -134
  38. package/src/guard-no-custom-primitives.ts +0 -193
  39. package/src/guard-no-date-api.ts +0 -183
  40. package/src/guard-no-direct-fs.ts +0 -346
  41. package/src/guard-no-direct-process-env.ts +0 -127
  42. package/src/guard-no-inline-styles.ts +0 -64
  43. package/src/guard-no-raw-hooks.ts +0 -80
  44. package/src/guard-no-temporal-polyfill-import.ts +0 -131
  45. package/src/guard-primitives-discipline.ts +0 -357
  46. package/src/guard-raw-classname.ts +0 -117
  47. package/src/guard-raw-interactive-elements.ts +0 -164
  48. package/src/guard-restricted-symbols.ts +0 -155
  49. package/src/guard-silent-skip.ts +0 -186
  50. package/src/guard-test-es-fixtures.ts +0 -85
  51. package/src/guard-test-title.ts +0 -159
  52. package/src/guard-thin-wrappers.ts +0 -471
  53. package/src/guard-unsafe-json-parse.ts +0 -87
@@ -1,210 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Guard: `details.reason` strings and the first arg to UnprocessableError /
4
- * failUnprocessable must follow the reason convention:
5
- *
6
- * ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$
7
- *
8
- * That is: lowercase ASCII, underscores for word breaks, optional dot
9
- * namespaces for feature-scoped reasons (e.g. `order.already_cancelled`).
10
- * No spaces, no camelCase, no dashes, no leading digits.
11
- *
12
- * Why: reason codes survive the wire + logs + i18n lookup. Clients key off
13
- * them. Any drift (camelCase, typos like `stale_stat`) means a missed
14
- * branch in the SDK. Catching it at commit time is dramatically cheaper
15
- * than discovering a client-side dead branch in prod.
16
- *
17
- * What this checks:
18
- * 1. `new UnprocessableError(X, ...)` — X must be a string-literal reason
19
- * that matches the regex, OR a reference to a known Reasons const
20
- * (FrameworkReasons.*, <Anything>Reasons.*, TenantErrors.*, etc.).
21
- * 2. `failUnprocessable(X, ...)` — same rule.
22
- * 3. Object literals containing `reason: "X"` — same rule for the X.
23
- * Skips `openToAll: { reason: "..." }` / `escapeHatch: { reason: "..." }` /
24
- * `grants: { unsafeRaw: { reason: "..." } }` (every escape-hatch grant)
25
- * and `declareEscapeHatch({ reason: "..." })` — those are prose
26
- * access-declaration justifications, enforced instead by
27
- * the boot validator and the runtime reasonProblem check.
28
- *
29
- * Non-literal reasons (computed, template strings with interpolation,
30
- * identifier references) are assumed to be typed-from-a-const and pass.
31
- * A stricter version could walk to the declaration; v1 stays pragmatic.
32
- *
33
- * Usage:
34
- * bun guards/guard-error-reasons.ts
35
- */
36
-
37
- import * as path from "node:path";
38
- import { ESCAPE_HATCH_GRANTS } from "@cosmicdrift/kumiko-types/handlers";
39
- import { type Node, type SourceFile, SyntaxKind } from "ts-morph";
40
- import { type AstGuard, runStandalone, type ScanSpec } from "./_lib/guard-kit";
41
-
42
- const ROOT = process.cwd();
43
-
44
- const SCAN: ScanSpec = {
45
- scope: "source",
46
- extensions: ["ts"],
47
- frameworkWithin: ["packages/*/src/**", "samples/**"],
48
- };
49
-
50
- // Excluded: test files (they may legitimately fabricate broken reasons to
51
- // prove the guard catches them) and the classes.ts / reasons.ts definitions
52
- // themselves (message text in constructor defaults isn't a reason).
53
- const EXCLUDE =
54
- /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$|errors\/classes\.ts$|errors\/reasons\.ts$|node_modules)/;
55
-
56
- const REASON_RE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
57
-
58
- // Calls whose first positional arg is a reason string.
59
- const UNPROC_CALL_NAMES = new Set(["UnprocessableError", "failUnprocessable"]);
60
-
61
- // Property names whose `{ reason: "..." }` is a prose access-declaration
62
- // justification, not an error-reason code.
63
- // `grants: { <grant>: { reason } }` carries the grant names of EscapeHatchDeclaration; deriving them
64
- // keeps a new grant from being reported as an error code.
65
- const ACCESS_DECLARATION_NAMES = new Set<string>([
66
- "openToAll",
67
- "escapeHatch",
68
- "unsafeAllTenants",
69
- ...ESCAPE_HATCH_GRANTS,
70
- ]);
71
-
72
- // Calls whose object-literal argument carries a prose `reason` for an
73
- // access grant / escape hatch / system-mode TenantDb.
74
- const ACCESS_DECLARATION_CALLS = new Set([
75
- "declareEscapeHatch",
76
- "withUnsafeRawGrant",
77
- "createTenantDb",
78
- ]);
79
-
80
- interface Violation {
81
- readonly file: string;
82
- readonly line: number;
83
- readonly kind: "unproc-arg" | "details-reason";
84
- readonly value: string;
85
- }
86
-
87
- function scanFile(sf: SourceFile): Violation[] {
88
- const violations: Violation[] = [];
89
-
90
- // ---------- (1) + (2): UnprocessableError / failUnprocessable calls ----------
91
- for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
92
- const callee = call.getExpression();
93
- // Strip `new `, drop qualifying module access. We only need the final
94
- // identifier for the call name check.
95
- const text = callee.getText();
96
- const name = text.split(".").pop() ?? text;
97
-
98
- // Also catch `new UnprocessableError(...)` — ts-morph models that as a
99
- // NewExpression, but class-ref-as-callable in our codebase is exercised
100
- // only in tests/internal, so the NewExpression pass below handles it.
101
- if (!UNPROC_CALL_NAMES.has(name)) continue;
102
-
103
- const arg = call.getArguments()[0];
104
- const bad = checkReasonNode(arg);
105
- if (bad !== null) {
106
- violations.push({
107
- file: path.relative(ROOT, sf.getFilePath()),
108
- line: call.getStartLineNumber(),
109
- kind: "unproc-arg",
110
- value: bad,
111
- });
112
- }
113
- }
114
-
115
- for (const neu of sf.getDescendantsOfKind(SyntaxKind.NewExpression)) {
116
- const callee = neu.getExpression();
117
- const text = callee.getText();
118
- const name = text.split(".").pop() ?? text;
119
- if (name !== "UnprocessableError") continue;
120
-
121
- const arg = neu.getArguments()[0];
122
- const bad = checkReasonNode(arg);
123
- if (bad !== null) {
124
- violations.push({
125
- file: path.relative(ROOT, sf.getFilePath()),
126
- line: neu.getStartLineNumber(),
127
- kind: "unproc-arg",
128
- value: bad,
129
- });
130
- }
131
- }
132
-
133
- // ---------- (3): object literals with `reason: "..."` ----------
134
- for (const prop of sf.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {
135
- const name = prop.getName();
136
- if (name !== "reason") continue;
137
- if (isAccessDeclarationReason(prop)) continue;
138
-
139
- const initializer = prop.getInitializer();
140
- const bad = checkReasonNode(initializer);
141
- if (bad !== null) {
142
- violations.push({
143
- file: path.relative(ROOT, sf.getFilePath()),
144
- line: prop.getStartLineNumber(),
145
- kind: "details-reason",
146
- value: bad,
147
- });
148
- }
149
- }
150
-
151
- return violations;
152
- }
153
-
154
- // A `reason` PropertyAssignment whose object literal is the initializer of
155
- // an `openToAll` / `escapeHatch` PropertyAssignment, or an argument
156
- // object of a bare `declareEscapeHatch(...)` / `withUnsafeRawGrant(...)` call, is an access-declaration
157
- // justification, not an error-reason code.
158
- export function isAccessDeclarationReason(prop: Node): boolean {
159
- const objectLiteral = prop.getParent();
160
- if (!objectLiteral?.isKind(SyntaxKind.ObjectLiteralExpression)) return false;
161
- const owner = objectLiteral.getParent();
162
- if (owner?.isKind(SyntaxKind.PropertyAssignment)) {
163
- return ACCESS_DECLARATION_NAMES.has(owner.getName());
164
- }
165
- if (owner?.isKind(SyntaxKind.CallExpression)) {
166
- const callee = owner.getExpression();
167
- return callee.isKind(SyntaxKind.Identifier) && ACCESS_DECLARATION_CALLS.has(callee.getText());
168
- }
169
- return false;
170
- }
171
-
172
- // Returns the offending string if this node is a string literal that does
173
- // NOT match the reason regex; null otherwise (including for non-literals —
174
- // those are assumed to come from a typed const and slip through).
175
- function checkReasonNode(node: Node | undefined): string | null {
176
- if (!node) return null;
177
- if (node.isKind(SyntaxKind.StringLiteral)) {
178
- const lit = node.getLiteralText();
179
- return REASON_RE.test(lit) ? null : lit;
180
- }
181
- if (node.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)) {
182
- const lit = node.getLiteralText();
183
- return REASON_RE.test(lit) ? null : lit;
184
- }
185
- return null;
186
- }
187
-
188
- export const guard: AstGuard = {
189
- name: "Error-Reasons Guard",
190
- scan: SCAN,
191
- hint: `reason strings must match ${REASON_RE} (snake_case ASCII, optional dot-namespaced). Reusable? Add a const to FrameworkReasons/<Feature>Reasons.`,
192
- run(files) {
193
- const violations: Array<{ file: string; line: number; message: string }> = [];
194
- for (const sf of files) {
195
- if (EXCLUDE.test(sf.getFilePath())) continue;
196
- for (const v of scanFile(sf)) {
197
- const where =
198
- v.kind === "unproc-arg" ? "UnprocessableError/failUnprocessable" : "details.reason";
199
- violations.push({
200
- file: v.file,
201
- line: v.line,
202
- message: `${where} "${v.value}"`,
203
- });
204
- }
205
- }
206
- return { violations };
207
- },
208
- };
209
-
210
- if (import.meta.main) runStandalone(guard);
@@ -1,124 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Guard: flags string/template literals containing UPDATE/DELETE FROM/INSERT
4
- * INTO against kumiko_events, kumiko_snapshots or kumiko_archived_streams
5
- * outside the event store's own files.
6
- *
7
- * These three tables ARE the event store. A direct write from elsewhere
8
- * bypasses its invariants (version-unique index, archive markers, tenant
9
- * boundary). Tenant moves go through `transferAggregateStreams`
10
- * (event-store/transfer.ts); any other need belongs in
11
- * db/queries/event-store*.ts.
12
- *
13
- * Usage:
14
- * bun packages/guards/src/guard-event-store-writes.ts
15
- */
16
-
17
- import { type SourceFile, SyntaxKind } from "ts-morph";
18
- import {
19
- type AstGuard,
20
- type GuardViolation,
21
- relFromRepoRoot,
22
- runStandalone,
23
- type ScanSpec,
24
- } from "./_lib/guard-kit";
25
- import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
26
-
27
- const SCAN: ScanSpec = { scope: "source", extensions: ["ts"] };
28
-
29
- // Tests fabricate their own fixture rows directly — they are the primary
30
- // verifiers of the event-store primitives, not a write surface this guard
31
- // needs to police.
32
- const EXCLUDE = /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$)/;
33
-
34
- // Files allowed to write these three tables directly:
35
- // - event-store/** — the primitive's own home (transfer.ts, event-store.ts,
36
- // snapshot.ts, archive.ts, admin-api.ts, rebuild-dead-letter.ts, ...).
37
- // - db/queries/event-store*.ts — the raw-SQL backing queries the primitives
38
- // call (event-store.ts, event-store-admin.ts, event-store-transfer.ts).
39
- // - db/queries/backfill-pii.ts — the one-time pre-KMS plaintext backfill;
40
- // rewrites payload/deletes stale snapshots in place, framework-owned.
41
- // - shared/stream-tenant-backfill.ts — a one-time stream-ownership
42
- // migration that predates this guard; already carries its own
43
- // RAW_SQL_ALLOWLIST entry, kept here for the same reason.
44
- const ALLOWLIST: readonly RegExp[] = [
45
- /^packages\/framework\/src\/event-store\//,
46
- /^packages\/framework\/src\/db\/queries\/event-store.*\.ts$/,
47
- /^packages\/framework\/src\/db\/queries\/backfill-pii\.ts$/,
48
- /^packages\/bundled-features\/src\/shared\/stream-tenant-backfill\.ts$/,
49
- ];
50
-
51
- const ES_TABLES = "kumiko_events|kumiko_snapshots|kumiko_archived_streams";
52
- // One string/template literal must carry both the write verb AND the table
53
- // name — a keyword in one concatenated piece and the table name (behind a
54
- // variable) in another is indirection this guard does not see through; the
55
- // event store's own queries are the only place that literal belongs.
56
- const WRITE_RE = new RegExp(
57
- `\\b(UPDATE|DELETE\\s+FROM|INSERT\\s+INTO)\\b[\\s\\S]*?["'\`]?(${ES_TABLES})["'\`]?`,
58
- "i",
59
- );
60
-
61
- const LITERAL_KINDS = [
62
- SyntaxKind.StringLiteral,
63
- SyntaxKind.NoSubstitutionTemplateLiteral,
64
- SyntaxKind.TemplateExpression,
65
- ];
66
-
67
- export type Violation = {
68
- readonly file: string;
69
- readonly line: number;
70
- readonly snippet: string;
71
- };
72
-
73
- export function isAllowed(relativePath: string): boolean {
74
- return ALLOWLIST.some((re) => re.test(relativePath));
75
- }
76
-
77
- export function collectViolations(
78
- sourceFile: SourceFile,
79
- roots: readonly RepoRoot[] = resolveRepoRoots(),
80
- ): Violation[] {
81
- const violations: Violation[] = [];
82
- // Repo-root-relative, not `process.cwd()`-relative — a multi-repo runner
83
- // (e.g. invoked from the parent workspace dir) would otherwise carry a
84
- // leading `kumiko-framework/` segment that the ALLOWLIST regexes (anchored
85
- // on `^packages/...`) never match, wrongly flagging every allowed file.
86
- const relativePath = relFromRepoRoot(sourceFile.getFilePath(), roots);
87
- if (isAllowed(relativePath)) return violations;
88
-
89
- for (const kind of LITERAL_KINDS) {
90
- for (const node of sourceFile.getDescendantsOfKind(kind)) {
91
- const text = node.getText();
92
- const match = WRITE_RE.exec(text);
93
- if (!match) continue;
94
- violations.push({
95
- file: relativePath,
96
- line: node.getStartLineNumber(),
97
- snippet: match[0].replace(/\s+/g, " ").trim().slice(0, 120),
98
- });
99
- }
100
- }
101
- return violations;
102
- }
103
-
104
- export const guard: AstGuard = {
105
- name: "Event-Store-Writes Guard",
106
- scan: SCAN,
107
- hint:
108
- "kumiko_events/kumiko_snapshots/kumiko_archived_streams may only be written from " +
109
- "packages/framework/src/event-store/** and their db/queries/event-store*.ts backing. " +
110
- "Use transferAggregateStreams (event-store/transfer.ts) for a tenant move, or add a " +
111
- "new event-store primitive instead of writing these tables from feature code.",
112
- run(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
113
- const violations: GuardViolation[] = [];
114
- for (const sf of files) {
115
- if (EXCLUDE.test(sf.getFilePath())) continue;
116
- for (const v of collectViolations(sf, roots)) {
117
- violations.push({ file: v.file, line: v.line, message: v.snippet });
118
- }
119
- }
120
- return { violations };
121
- },
122
- };
123
-
124
- if (import.meta.main) runStandalone(guard);
@@ -1,134 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Guard: locale bundle values must follow Mandant/Organización terminology.
4
- *
5
- * German UI copy always says "Mandant" (never "Tenant"/"Organisation"); Spanish, French
6
- * and Italian always say "Organización"/"organisation"/"organizzazione" (never the
7
- * "tenant" loanword). Only translation *values* are
8
- * checked — JSON key names like `tenant.members.*` are ignored. Role identifiers
9
- * such as TenantAdmin/SystemAdmin in prose are allowed.
10
- *
11
- * Usage:
12
- * bun guards/guard-i18n-locale-terminology.ts
13
- *
14
- * Ignore: // kumiko-lint-ignore i18n-locale-terminology
15
- */
16
-
17
- import { type Node, type SourceFile, SyntaxKind } from "ts-morph";
18
- import {
19
- type AstGuard,
20
- type GuardViolation,
21
- isLocalFinding,
22
- relFromRepoRoot,
23
- runStandalone,
24
- type ScanSpec,
25
- } from "./_lib/guard-kit";
26
- import { hasIgnoreTag } from "./_lib/ignore-tag";
27
- import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
28
-
29
- const SCAN: ScanSpec = {
30
- scope: "source",
31
- extensions: ["ts"],
32
- kinds: ["framework"],
33
- frameworkWithin: [
34
- "packages/locale-de/src/strings.ts",
35
- "packages/locale-es/src/strings.ts",
36
- "packages/locale-fr/src/strings.ts",
37
- "packages/locale-it/src/strings.ts",
38
- ],
39
- };
40
- const IGNORE_TAG = "kumiko-lint-ignore i18n-locale-terminology";
41
-
42
- type LocaleRule = {
43
- readonly preferred: string;
44
- readonly forbidden: readonly RegExp[];
45
- };
46
-
47
- type TerminologyLocale = "de" | "es" | "fr" | "it";
48
-
49
- const RULES: Record<TerminologyLocale, LocaleRule> = {
50
- de: {
51
- preferred: "Mandant",
52
- // Tenants? covers plural; Organisation(en|s)? without trailing \b so
53
- // compounds like Organisations-ID / Organisationsstruktur still match.
54
- // TenantAdmin stays safe: \b after Tenant fails on 'A'.
55
- forbidden: [/\bTenants?\b/i, /\bOrganisation(en|s)?/i],
56
- },
57
- es: {
58
- preferred: "Organización",
59
- forbidden: [/\btenants?\b/i],
60
- },
61
- fr: {
62
- preferred: "organisation",
63
- forbidden: [/\btenants?\b/i],
64
- },
65
- it: {
66
- preferred: "organizzazione",
67
- forbidden: [/\btenants?\b/i],
68
- },
69
- };
70
-
71
- function localeFromPath(filePath: string): TerminologyLocale | undefined {
72
- if (filePath.includes("locale-de/src/strings.ts")) return "de";
73
- if (filePath.includes("locale-es/src/strings.ts")) return "es";
74
- if (filePath.includes("locale-fr/src/strings.ts")) return "fr";
75
- if (filePath.includes("locale-it/src/strings.ts")) return "it";
76
- return undefined;
77
- }
78
-
79
- function stringLiteralText(node: Node): string | undefined {
80
- if (node.isKind(SyntaxKind.StringLiteral)) return node.getLiteralText();
81
- if (node.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)) return node.getLiteralValue();
82
- return undefined;
83
- }
84
-
85
- function forbiddenTerm(text: string, rule: LocaleRule): string | undefined {
86
- for (const re of rule.forbidden) {
87
- const match = text.match(re);
88
- if (match !== null) return match[0];
89
- }
90
- return undefined;
91
- }
92
-
93
- export function findViolations(files: readonly SourceFile[]): GuardViolation[] {
94
- const violations: GuardViolation[] = [];
95
-
96
- for (const sf of files) {
97
- const locale = localeFromPath(sf.getFilePath());
98
- if (locale === undefined) continue;
99
- const rule = RULES[locale];
100
-
101
- for (const prop of sf.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {
102
- if (hasIgnoreTag(prop, IGNORE_TAG)) continue;
103
- const init = prop.getInitializer();
104
- if (init === undefined) continue;
105
- const text = stringLiteralText(init);
106
- if (text === undefined) continue;
107
-
108
- const hit = forbiddenTerm(text, rule);
109
- if (hit !== undefined) {
110
- violations.push({
111
- file: sf.getFilePath(),
112
- line: prop.getStartLineNumber(),
113
- message: `[${locale}] forbidden term "${hit}" in translation value — use "${rule.preferred}" (fw#2200).`,
114
- });
115
- }
116
- }
117
- }
118
-
119
- return violations;
120
- }
121
-
122
- export const guard: AstGuard = {
123
- name: "i18n-Locale-Terminology Guard",
124
- scan: SCAN,
125
- hint: "DE: Mandant instead of Tenant/Organisation; ES/FR/IT: Organización/organisation/organizzazione instead of the tenant loanword. Roles like TenantAdmin are fine.",
126
- run(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
127
- const violations = findViolations(files)
128
- .map((v) => ({ ...v, file: relFromRepoRoot(v.file, roots) }))
129
- .filter(isLocalFinding);
130
- return { violations };
131
- },
132
- };
133
-
134
- if (import.meta.main) runStandalone(guard);
@@ -1,193 +0,0 @@
1
- #!/usr/bin/env bun
2
- // Apps no longer build their own UI primitives: components with primitive
3
- // names (…Card, …Table, …Badge, …Button, …Chart, ProgressBar, MiniStat, …)
4
- // exist in the framework (usePrimitives() resp. widgets/) — app rebuilds
5
- // drift visually and cost every migration twice.
6
- //
7
- // Second rule: raw form HTML (<input>/<select>/<textarea>/
8
- // <label>) in app/feature web code, regardless of what the file imports —
9
- // an import gate here previously let the designer's raw <input>s pass just
10
- // by importing from @cosmicdrift/kumiko-renderer (types only) instead of
11
- // -renderer-web, without ever touching a framework primitive. Baseline-
12
- // ratcheted (freeze the existing backlog, no half-ratchet). Deviating from
13
- // the usual "no baseline file = warn-only until --write-baseline": the
14
- // measured backlog is 0 in every locally checked repo, so this fails
15
- // closed against an empty baseline while no baseline file exists —
16
- // otherwise the rule would stay silent in every app repo until someone
17
- // manually runs --write-baseline there.
18
-
19
- import { existsSync } from "node:fs";
20
- import * as path from "node:path";
21
- import { type SourceFile, SyntaxKind } from "ts-morph";
22
- import {
23
- type AstGuard,
24
- baselineRatchet,
25
- buildSharedProject,
26
- compareToBaseline,
27
- filesForGuard,
28
- type GuardViolation,
29
- relativeToCwd,
30
- runStandalone,
31
- type ScanSpec,
32
- } from "./_lib/guard-kit";
33
- import { hasIgnoreTag } from "./_lib/ignore-tag";
34
-
35
- const ROOT = process.cwd();
36
-
37
- const SCAN: ScanSpec = {
38
- scope: "source",
39
- extensions: ["tsx"],
40
- frameworkWithin: ["packages/bundled-features/src/**"],
41
- };
42
- const EXCLUDE = /(__tests__|\.test\.tsx?$|\.integration\.tsx?$|\.d\.ts$)/;
43
- const IGNORE_TAG = "kumiko-lint-ignore no-custom-primitives";
44
-
45
- // PascalCase + primitive suffix, or a known widget name.
46
- const PRIMITIVE_NAME =
47
- /^[A-Z]\w*(Card|Table|Badge|Button|Chart|Modal|Dialog|Tooltip|Spinner|Sparkline)$|^(ProgressBar|MiniStat|StatCard|EmptyState|LoadingState|ErrorState|ModeSwitch|Collapsible\w*|DetailList|MessageThread|MessageReader|StepList|MobileTopBar|ClampedText|AttachmentChip|AttachmentCard|HtmlMailFrame|SenderSheet|SenderFrame|AiSurface)$/;
48
-
49
- const RAW_FORM_TAGS = new Set(["input", "select", "textarea", "label"]);
50
-
51
- type RawFormFinding = {
52
- readonly file: string;
53
- readonly line: number;
54
- readonly tag: string;
55
- };
56
-
57
- function collectRawFormHtml(sf: SourceFile): RawFormFinding[] {
58
- const findings: RawFormFinding[] = [];
59
- const elements = [
60
- ...sf.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),
61
- ...sf.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement),
62
- ];
63
- for (const el of elements) {
64
- const tag = el.getTagNameNode().getText();
65
- if (!RAW_FORM_TAGS.has(tag)) continue;
66
- if (hasIgnoreTag(el, IGNORE_TAG)) continue;
67
- findings.push({
68
- file: relativeToCwd(sf.getFilePath()),
69
- line: el.getStartLineNumber(),
70
- tag,
71
- });
72
- }
73
- return findings;
74
- }
75
-
76
- function countByFile(findings: readonly RawFormFinding[]): Record<string, number> {
77
- const counts: Record<string, number> = {};
78
- for (const f of findings) counts[f.file] = (counts[f.file] ?? 0) + 1;
79
- return counts;
80
- }
81
-
82
- const BASELINE_FILE = ".kumiko-no-custom-primitives-baseline.json";
83
- const BASELINE_PATH = path.join(ROOT, BASELINE_FILE);
84
- const rawFormHtmlBaseline = baselineRatchet({
85
- file: BASELINE_PATH,
86
- formatVersion: 1,
87
- unit: "raw form HTML finding(s)",
88
- });
89
- const RAW_FORM_HTML_REMEDIATION =
90
- "Use a framework widget (@cosmicdrift/kumiko-renderer/web: Field/Input, ComboboxInput, …) " +
91
- `or usePrimitives(). Real exception: // ${IGNORE_TAG} <reason>`;
92
-
93
- // The rule is new: measured backlog is 0 in every locally checked repo
94
- // . Without a baseline file, check fail-closed against an empty
95
- // baseline instead of (as usual) warn-only until the first
96
- // `--write-baseline` — otherwise the rule would stay silent in every app
97
- // repo until it separately commits its own baseline file (every baseline
98
- // file is repo-local, see .kumiko-comment-lang-baseline.json etc.).
99
- function checkRawFormHtmlBaseline(findings: readonly RawFormFinding[]): GuardViolation[] {
100
- const resolveLine = (file: string): number => findings.find((f) => f.file === file)?.line ?? 1;
101
- const current = countByFile(findings);
102
- if (!existsSync(BASELINE_PATH)) {
103
- const { regressions } = compareToBaseline(current, {});
104
- return regressions.map((r) => ({
105
- file: r.file,
106
- line: resolveLine(r.file),
107
- message: `${r.current} raw form HTML finding(s) (no baseline — existing backlog is 0). ${RAW_FORM_HTML_REMEDIATION}`,
108
- }));
109
- }
110
- return rawFormHtmlBaseline.check(current, RAW_FORM_HTML_REMEDIATION, {
111
- formatDriftRemediation: "Run `bun guards/guard-no-custom-primitives.ts --write-baseline` once.",
112
- resolveLine,
113
- });
114
- }
115
-
116
- function analyse(
117
- files: readonly SourceFile[],
118
- compareBaseline: boolean,
119
- ): { violations: GuardViolation[] } {
120
- const violations: GuardViolation[] = [];
121
- const rawFormFindings: RawFormFinding[] = [];
122
- for (const sf of files) {
123
- if (EXCLUDE.test(sf.getFilePath())) continue;
124
- const candidates: {
125
- name: string;
126
- line: number;
127
- node: Parameters<typeof hasIgnoreTag>[0];
128
- }[] = [];
129
- for (const fn of sf.getFunctions()) {
130
- const name = fn.getName();
131
- if (name !== undefined) candidates.push({ name, line: fn.getStartLineNumber(), node: fn });
132
- }
133
- for (const v of sf.getVariableDeclarations()) {
134
- const init = v.getInitializer();
135
- if (init === undefined) continue;
136
- const kind = init.getKind();
137
- if (kind !== SyntaxKind.ArrowFunction && kind !== SyntaxKind.FunctionExpression) continue;
138
- candidates.push({
139
- name: v.getName(),
140
- line: v.getStartLineNumber(),
141
- node: v,
142
- });
143
- }
144
- for (const c of candidates) {
145
- if (!PRIMITIVE_NAME.test(c.name)) continue;
146
- if (hasIgnoreTag(c.node, IGNORE_TAG)) continue;
147
- violations.push({
148
- file: relativeToCwd(sf.getFilePath()),
149
- line: c.line,
150
- message: `App-local UI primitive "${c.name}" — use a framework widget/primitive`,
151
- });
152
- }
153
- rawFormFindings.push(...collectRawFormHtml(sf));
154
- }
155
- if (!compareBaseline) {
156
- console.log(" Baseline comparison skipped (--no-baseline).");
157
- } else {
158
- violations.push(...checkRawFormHtmlBaseline(rawFormFindings));
159
- }
160
- return { violations };
161
- }
162
-
163
- export const guard: AstGuard = {
164
- name: "No-Custom-Primitives Guard (App-Repos)",
165
- scan: SCAN,
166
- hint:
167
- "Use a framework widget (@cosmicdrift/kumiko-renderer/web: StatCard, SectionCard, StatusBadge, QueryTable, Charts, …) " +
168
- `or usePrimitives(). Real domain component without a framework equivalent: // ${IGNORE_TAG} <reason>`,
169
- run: (files: readonly SourceFile[]) => analyse(files, true),
170
- };
171
-
172
- // Flags are read ONLY here, not in run() — the shared runner
173
- // (run-guards.ts/run-ui-guards.ts) runs every guard with the same argv, a
174
- // --write-baseline there must not silently rewrite the baseline.
175
- //
176
- // No --no-baseline: this guard has a
177
- // second, non-baselined rule (PRIMITIVE_NAME) — a --no-baseline that
178
- // discards analyse()'s return and exits 0 would silence that too. Nobody
179
- // reads the flag (the shared runner only calls run()).
180
- if (import.meta.main) {
181
- const args = process.argv.slice(2);
182
- if (args.includes("--write-baseline")) {
183
- const project = buildSharedProject([guard]);
184
- const findings: RawFormFinding[] = [];
185
- for (const sf of filesForGuard(project, guard)) {
186
- if (EXCLUDE.test(sf.getFilePath())) continue;
187
- findings.push(...collectRawFormHtml(sf));
188
- }
189
- rawFormHtmlBaseline.write(countByFile(findings));
190
- process.exit(0);
191
- }
192
- runStandalone(guard);
193
- }