@mandujs/core 0.31.0 → 0.32.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.
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Phase 18.ν — Consumer-defined Guard rules.
3
+ *
4
+ * Ships `defineGuardRule()` + `GuardRule` / `GuardRuleContext` /
5
+ * `GuardViolation` types so consumers can extend Mandu's architecture
6
+ * guard without forking the framework. Rules declared via
7
+ * `mandu.config.ts` `guard.rules` are merged into the standard Guard
8
+ * report alongside Mandu's built-in presets (fsd/clean/hexagonal/atomic/
9
+ * cqrs/mandu).
10
+ *
11
+ * @module guard/define-rule
12
+ *
13
+ * @example Project-local "no axios" rule.
14
+ * ```ts
15
+ * // mandu.config.ts
16
+ * import { defineGuardRule } from "@mandujs/core/guard/define-rule";
17
+ *
18
+ * export default {
19
+ * guard: {
20
+ * rules: [
21
+ * defineGuardRule({
22
+ * id: "forbid-axios",
23
+ * severity: "error",
24
+ * description: "Use native fetch() instead of axios.",
25
+ * check: (ctx) => ctx.imports
26
+ * .filter((imp) => imp.path === "axios" || imp.path.startsWith("axios/"))
27
+ * .map((imp) => ({
28
+ * file: ctx.sourceFile,
29
+ * line: imp.line,
30
+ * message: `axios import at line ${imp.line} — use fetch().`,
31
+ * hint: "Replace with globalThis.fetch() or a thin wrapper.",
32
+ * })),
33
+ * }),
34
+ * ],
35
+ * },
36
+ * };
37
+ * ```
38
+ */
39
+
40
+ import type { ExportInfo as AstExportInfo } from "./ast-analyzer";
41
+ import type { ImportInfo as AstImportInfo } from "./types";
42
+ import type { ManduConfig } from "../config/mandu";
43
+
44
+ /**
45
+ * Severity emitted by a consumer-defined rule when it flags a file.
46
+ *
47
+ * - `"error"` — fails `mandu guard check` (non-zero exit code).
48
+ * - `"warning"` — surfaces in the report but keeps the exit code clean.
49
+ * - `"info"` — purely informational; useful for migration-phase
50
+ * rules that should not gate CI yet.
51
+ *
52
+ * The built-in `applyRuleSeverity()` downgrades `"info"` → `"warning"`
53
+ * when emitted through the unified report so the rest of the pipeline
54
+ * (reporter, CI formatter) does not have to special-case a third level.
55
+ */
56
+ export type GuardRuleSeverity = "error" | "warning" | "info";
57
+
58
+ /**
59
+ * Information about a single import statement in the file being
60
+ * checked. Shape matches {@link AstImportInfo} from the Guard AST
61
+ * analyzer so rules can consume the two interchangeably.
62
+ */
63
+ export type ImportInfo = AstImportInfo;
64
+
65
+ /**
66
+ * Information about a single export declaration in the file being
67
+ * checked. Shape matches {@link AstExportInfo}.
68
+ */
69
+ export type ExportInfo = AstExportInfo;
70
+
71
+ /**
72
+ * Violation record emitted by a consumer-defined rule. The Guard
73
+ * runner prefixes `ruleId` with `custom:<rule.id>` when merging into
74
+ * the standard report, so the originating rule is always traceable in
75
+ * CI output.
76
+ */
77
+ export interface GuardViolation {
78
+ /** Relative (preferred) or absolute file path where the violation occurs. */
79
+ file: string;
80
+ /** 1-indexed line number, if known. */
81
+ line?: number;
82
+ /** 1-indexed column number, if known. */
83
+ column?: number;
84
+ /** Human-readable message surfaced in the reporter. */
85
+ message: string;
86
+ /** Optional remediation hint. Shown alongside `message` in the CLI report. */
87
+ hint?: string;
88
+ /** Optional docs URL (rendered as a clickable link in supported terminals). */
89
+ docsUrl?: string;
90
+ }
91
+
92
+ /**
93
+ * Per-file execution context handed to a rule's `check()` function.
94
+ * The runner parses imports/exports up front with the Guard AST
95
+ * analyzer so every rule gets a pre-tokenized view without paying the
96
+ * parse cost N times.
97
+ */
98
+ export interface GuardRuleContext {
99
+ /** Absolute path of the file being checked. */
100
+ sourceFile: string;
101
+ /** Raw file content (UTF-8). */
102
+ content: string;
103
+ /** Parsed import statements (AST-level, comments/strings stripped). */
104
+ imports: ImportInfo[];
105
+ /** Parsed export declarations (AST-level). */
106
+ exports: ExportInfo[];
107
+ /** Resolved Mandu config — useful for rules that branch on project settings. */
108
+ config: ManduConfig;
109
+ /** Project root (absolute). Useful for computing relative paths for `file`. */
110
+ projectRoot: string;
111
+ }
112
+
113
+ /**
114
+ * A consumer-defined Guard rule. Register an array of these under
115
+ * `mandu.config.ts` `guard.rules`.
116
+ *
117
+ * Rules are executed once per source file scanned by
118
+ * `checkInvalidGeneratedImport()`'s source-dir walker (packages/, src/,
119
+ * app/). Each rule's `check()` may be synchronous or asynchronous —
120
+ * the runner awaits both uniformly.
121
+ *
122
+ * @see {@link defineGuardRule}
123
+ */
124
+ export interface GuardRule {
125
+ /**
126
+ * Stable rule identifier, e.g. `"company-no-axios"`. The runner
127
+ * prefixes this with `custom:` when emitting violations, so the final
128
+ * `ruleId` in the report is `custom:company-no-axios`.
129
+ *
130
+ * Must be unique within a config; duplicate ids trigger a
131
+ * config-load-time warning via `validateCustomRules()`.
132
+ */
133
+ id: string;
134
+ /** Default severity for violations emitted by this rule. */
135
+ severity: GuardRuleSeverity;
136
+ /** One-line description surfaced in the reporter and in `mandu guard explain`. */
137
+ description: string;
138
+ /**
139
+ * Predicate that returns zero or more violations for the given file.
140
+ * May be sync or async; the runner awaits uniformly with a
141
+ * concurrency-limited `Promise.all`.
142
+ *
143
+ * Throwing inside `check()` is non-fatal — the runner catches the
144
+ * error, emits a `custom:<id>` violation with the thrown message,
145
+ * and continues scanning the rest of the files. This keeps one
146
+ * malformed rule from tearing down the whole report.
147
+ */
148
+ check: (ctx: GuardRuleContext) => GuardViolation[] | Promise<GuardViolation[]>;
149
+ }
150
+
151
+ /**
152
+ * Identity helper that returns the rule it was given. The only
153
+ * behavior-bearing piece is the type guard — `defineGuardRule()`
154
+ * validates the minimum shape (`id`, `severity`, `check`) at runtime
155
+ * so typos in a plain-JS `mandu.config.js` surface immediately instead
156
+ * of hiding inside the Guard runner.
157
+ *
158
+ * @throws `TypeError` when `rule` is missing a required field, or
159
+ * when `severity` is not one of `"error" | "warning" | "info"`.
160
+ */
161
+ export function defineGuardRule(rule: GuardRule): GuardRule {
162
+ if (!rule || typeof rule !== "object") {
163
+ throw new TypeError("defineGuardRule: argument must be an object.");
164
+ }
165
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
166
+ throw new TypeError("defineGuardRule: `id` must be a non-empty string.");
167
+ }
168
+ if (rule.severity !== "error" && rule.severity !== "warning" && rule.severity !== "info") {
169
+ throw new TypeError(
170
+ `defineGuardRule: \`severity\` must be one of "error" | "warning" | "info" (got ${JSON.stringify(rule.severity)}).`
171
+ );
172
+ }
173
+ if (typeof rule.check !== "function") {
174
+ throw new TypeError("defineGuardRule: `check` must be a function (sync or async).");
175
+ }
176
+ if (typeof rule.description !== "string") {
177
+ throw new TypeError("defineGuardRule: `description` must be a string.");
178
+ }
179
+ return rule;
180
+ }
181
+
182
+ /**
183
+ * Structural check used by the Zod `z.custom<GuardRule>()` guard in
184
+ * `config/validate.ts` and by `validateCustomRules()` at load time.
185
+ * Kept deliberately loose — we only reject values that are obviously
186
+ * not `GuardRule` objects; deeper validation (severity enum,
187
+ * description type) happens in `defineGuardRule()` for the clearest
188
+ * DX error, or in the runner (`check` throws) where the violation is
189
+ * reported in-band.
190
+ */
191
+ export function isGuardRuleLike(value: unknown): value is GuardRule {
192
+ if (typeof value !== "object" || value === null) return false;
193
+ const obj = value as Record<string, unknown>;
194
+ if (typeof obj.id !== "string" || obj.id.length === 0) return false;
195
+ if (typeof obj.check !== "function") return false;
196
+ return true;
197
+ }
198
+
199
+ /**
200
+ * Duplicate-id result returned by {@link validateCustomRules}.
201
+ */
202
+ export interface DuplicateRuleId {
203
+ id: string;
204
+ /** Zero-indexed positions in the original array where the id appears. */
205
+ indices: number[];
206
+ }
207
+
208
+ /**
209
+ * Structural validation executed at config-load. Returns the list of
210
+ * duplicate ids plus a list of entries that failed {@link isGuardRuleLike}.
211
+ * The CLI prints a warning per duplicate; malformed rules are surfaced
212
+ * via Zod's standard error path.
213
+ */
214
+ export function validateCustomRules(rules: readonly unknown[]): {
215
+ duplicates: DuplicateRuleId[];
216
+ malformed: number[];
217
+ } {
218
+ const duplicates: DuplicateRuleId[] = [];
219
+ const malformed: number[] = [];
220
+ const seen = new Map<string, number[]>();
221
+
222
+ for (let i = 0; i < rules.length; i++) {
223
+ const rule = rules[i];
224
+ if (!isGuardRuleLike(rule)) {
225
+ malformed.push(i);
226
+ continue;
227
+ }
228
+ const existing = seen.get(rule.id);
229
+ if (existing) {
230
+ existing.push(i);
231
+ } else {
232
+ seen.set(rule.id, [i]);
233
+ }
234
+ }
235
+
236
+ for (const [id, indices] of seen) {
237
+ if (indices.length > 1) {
238
+ duplicates.push({ id, indices });
239
+ }
240
+ }
241
+
242
+ return { duplicates, malformed };
243
+ }
@@ -275,6 +275,32 @@ export {
275
275
  type SemanticSlotValidationResult,
276
276
  } from "./semantic-slots";
277
277
 
278
+ // ═══════════════════════════════════════════════════════════════════════════
279
+ // Custom Guard Rules (Phase 18.ν) - Consumer-defined rules
280
+ // ═══════════════════════════════════════════════════════════════════════════
281
+
282
+ export {
283
+ defineGuardRule,
284
+ isGuardRuleLike,
285
+ validateCustomRules,
286
+ type GuardRule as CustomGuardRule,
287
+ type GuardRuleContext as CustomGuardRuleContext,
288
+ type GuardViolation as CustomGuardViolation,
289
+ type GuardRuleSeverity as CustomGuardRuleSeverity,
290
+ type DuplicateRuleId,
291
+ type ImportInfo as CustomRuleImportInfo,
292
+ type ExportInfo as CustomRuleExportInfo,
293
+ } from "./define-rule";
294
+
295
+ export {
296
+ forbidImport,
297
+ requireNamedExport,
298
+ requirePrefixForExports,
299
+ type ForbidImportOptions,
300
+ type RequireNamedExportOptions,
301
+ type RequirePrefixForExportsOptions,
302
+ } from "./rule-presets";
303
+
278
304
  // ═══════════════════════════════════════════════════════════════════════════
279
305
  // Architecture Negotiation - AI-Framework 협상
280
306
  // ═══════════════════════════════════════════════════════════════════════════
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Phase 18.ν — Convenience presets for consumer-defined Guard rules.
3
+ *
4
+ * Wraps {@link defineGuardRule} with the three most common project-local
5
+ * patterns observed in Mandu consumer projects:
6
+ *
7
+ * 1. `forbidImport()` — reject imports whose specifier matches a regex
8
+ * (or equals a literal string). Replaces the 90% case of
9
+ * `eslint-plugin-local` rules.
10
+ * 2. `requireNamedExport()` — require specific named exports in files
11
+ * whose paths match a glob/regex. Useful for enforcing file-based
12
+ * routing conventions (`route.ts` must export a `handler`, etc.).
13
+ * 3. `requirePrefixForExports()` — require exported functions to start
14
+ * with a given prefix (e.g. HTTP verb names for API route files).
15
+ *
16
+ * All helpers return a {@link GuardRule} so they can be pushed directly
17
+ * into `mandu.config.ts` `guard.rules: [...]`.
18
+ *
19
+ * @module guard/rule-presets
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * // mandu.config.ts
24
+ * import {
25
+ * forbidImport,
26
+ * requireNamedExport,
27
+ * requirePrefixForExports,
28
+ * } from "@mandujs/core/guard/define-rule";
29
+ *
30
+ * export default {
31
+ * guard: {
32
+ * rules: [
33
+ * forbidImport({ from: "axios", matches: /./ }),
34
+ * requireNamedExport({
35
+ * patterns: [/app\/api\/.*\/route\.ts$/],
36
+ * names: ["GET", "POST"],
37
+ * requireAny: true,
38
+ * }),
39
+ * requirePrefixForExports({
40
+ * patterns: [/app\/api\/.*\/route\.ts$/],
41
+ * prefix: /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/,
42
+ * }),
43
+ * ],
44
+ * },
45
+ * };
46
+ * ```
47
+ */
48
+
49
+ import {
50
+ defineGuardRule,
51
+ type GuardRule,
52
+ type GuardRuleContext,
53
+ type GuardRuleSeverity,
54
+ type GuardViolation,
55
+ } from "./define-rule";
56
+
57
+ // ═══════════════════════════════════════════════════════════════════════════
58
+ // Shared helpers
59
+ // ═══════════════════════════════════════════════════════════════════════════
60
+
61
+ /** Normalize a string | RegExp matcher into a `.test(value)`-capable object. */
62
+ function toRegex(matcher: string | RegExp): RegExp {
63
+ if (matcher instanceof RegExp) return matcher;
64
+ // Escape regex metacharacters for literal-string matches.
65
+ const escaped = matcher.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
+ return new RegExp(escaped);
67
+ }
68
+
69
+ /**
70
+ * Returns true when `filePath` matches at least one of the supplied
71
+ * patterns. Strings are treated as literal substrings; RegExps use
72
+ * `.test()`. Forward slashes are used throughout (the Guard runner
73
+ * already normalizes Windows backslashes upstream).
74
+ */
75
+ function matchesAny(filePath: string, patterns: ReadonlyArray<string | RegExp>): boolean {
76
+ for (const pattern of patterns) {
77
+ if (typeof pattern === "string") {
78
+ if (filePath.includes(pattern)) return true;
79
+ } else if (pattern.test(filePath)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
86
+ // ═══════════════════════════════════════════════════════════════════════════
87
+ // forbidImport
88
+ // ═══════════════════════════════════════════════════════════════════════════
89
+
90
+ /**
91
+ * Options for {@link forbidImport}.
92
+ */
93
+ export interface ForbidImportOptions {
94
+ /**
95
+ * Package name / path that triggers the rule. Matched against
96
+ * {@link ImportInfo.path} via `===` (literal) or `.test()` (regex).
97
+ * Pass a regex like `/^(node:fs|fs|fs\/promises)$/` for a set match.
98
+ */
99
+ from: string | RegExp;
100
+ /**
101
+ * Only the imports whose import path also matches this regex are
102
+ * flagged. Defaults to `/./` (all imports). Useful for cases where
103
+ * you want to forbid a package except when imported for types only.
104
+ */
105
+ matches?: RegExp;
106
+ /** Rule severity. Defaults to `"error"`. */
107
+ severity?: GuardRuleSeverity;
108
+ /** Override rule `id`. Defaults to `forbid-import:<normalized-from>`. */
109
+ id?: string;
110
+ /**
111
+ * Override rule `description`. Defaults to a human-friendly sentence
112
+ * describing the forbidden source.
113
+ */
114
+ description?: string;
115
+ /**
116
+ * Remediation hint surfaced alongside each violation. Defaults to a
117
+ * generic "Use a project-approved alternative" string.
118
+ */
119
+ hint?: string;
120
+ /** Optional docs URL surfaced with each violation. */
121
+ docsUrl?: string;
122
+ /**
123
+ * Restrict the rule to files whose path matches one of these
124
+ * patterns. When omitted, every scanned file is considered.
125
+ */
126
+ includePaths?: ReadonlyArray<string | RegExp>;
127
+ /**
128
+ * Exclude files whose path matches one of these patterns. Applied
129
+ * after `includePaths`.
130
+ */
131
+ excludePaths?: ReadonlyArray<string | RegExp>;
132
+ }
133
+
134
+ function normalizeIdFragment(value: string | RegExp): string {
135
+ const raw = value instanceof RegExp ? value.source : value;
136
+ return raw.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "import";
137
+ }
138
+
139
+ /**
140
+ * Create a rule that rejects every `import ... from "<from>"` whose
141
+ * specifier matches `matches` (default: all). Works for static,
142
+ * dynamic, and CommonJS `require()` imports.
143
+ */
144
+ export function forbidImport(options: ForbidImportOptions): GuardRule {
145
+ const fromMatcher = toRegex(options.from);
146
+ const extraMatcher = options.matches ?? /./;
147
+ const id = options.id ?? `forbid-import:${normalizeIdFragment(options.from)}`;
148
+ const description =
149
+ options.description ??
150
+ `Imports from \`${options.from instanceof RegExp ? options.from.source : options.from}\` are forbidden.`;
151
+ const hint = options.hint ?? "Use a project-approved alternative.";
152
+ const severity = options.severity ?? "error";
153
+
154
+ return defineGuardRule({
155
+ id,
156
+ severity,
157
+ description,
158
+ check(ctx: GuardRuleContext): GuardViolation[] {
159
+ if (options.includePaths && !matchesAny(ctx.sourceFile, options.includePaths)) {
160
+ return [];
161
+ }
162
+ if (options.excludePaths && matchesAny(ctx.sourceFile, options.excludePaths)) {
163
+ return [];
164
+ }
165
+
166
+ const violations: GuardViolation[] = [];
167
+ for (const imp of ctx.imports) {
168
+ if (!fromMatcher.test(imp.path)) continue;
169
+ if (!extraMatcher.test(imp.path)) continue;
170
+
171
+ violations.push({
172
+ file: ctx.sourceFile,
173
+ line: imp.line,
174
+ column: imp.column,
175
+ message: `Forbidden import: \`${imp.path}\` (${description})`,
176
+ hint,
177
+ docsUrl: options.docsUrl,
178
+ });
179
+ }
180
+ return violations;
181
+ },
182
+ });
183
+ }
184
+
185
+ // ═══════════════════════════════════════════════════════════════════════════
186
+ // requireNamedExport
187
+ // ═══════════════════════════════════════════════════════════════════════════
188
+
189
+ /**
190
+ * Options for {@link requireNamedExport}.
191
+ */
192
+ export interface RequireNamedExportOptions {
193
+ /**
194
+ * Only files whose path matches one of these patterns are checked.
195
+ * Strings are substring matches; regexes use `.test()`.
196
+ */
197
+ patterns: ReadonlyArray<string | RegExp>;
198
+ /**
199
+ * Export names that must be present. By default (`requireAny === false`)
200
+ * *all* names in this array must be exported; pass `requireAny: true`
201
+ * to require at least one.
202
+ */
203
+ names: readonly string[];
204
+ /**
205
+ * If `true`, a file passes when at least one of `names` is exported.
206
+ * Defaults to `false` (all names required).
207
+ */
208
+ requireAny?: boolean;
209
+ /** Rule severity. Defaults to `"error"`. */
210
+ severity?: GuardRuleSeverity;
211
+ /** Override rule `id`. Defaults to `require-named-export:<names.join("|")>`. */
212
+ id?: string;
213
+ /** Override rule `description`. */
214
+ description?: string;
215
+ /** Remediation hint. */
216
+ hint?: string;
217
+ /** Optional docs URL. */
218
+ docsUrl?: string;
219
+ }
220
+
221
+ /**
222
+ * Create a rule that requires specific named exports to exist in
223
+ * matching files. Useful for enforcing file-based routing conventions
224
+ * (e.g. `app/api/**\/route.ts` must export a `GET` or `POST` handler).
225
+ */
226
+ export function requireNamedExport(options: RequireNamedExportOptions): GuardRule {
227
+ if (!Array.isArray(options.names) || options.names.length === 0) {
228
+ throw new TypeError("requireNamedExport: `names` must be a non-empty array of strings.");
229
+ }
230
+ if (!Array.isArray(options.patterns) || options.patterns.length === 0) {
231
+ throw new TypeError("requireNamedExport: `patterns` must be a non-empty array.");
232
+ }
233
+
234
+ const id = options.id ?? `require-named-export:${options.names.join("|")}`;
235
+ const description =
236
+ options.description ??
237
+ (options.requireAny
238
+ ? `Files matching the pattern must export at least one of: ${options.names.join(", ")}.`
239
+ : `Files matching the pattern must export all of: ${options.names.join(", ")}.`);
240
+ const hint = options.hint ?? `Add the missing \`export\` declarations.`;
241
+ const severity = options.severity ?? "error";
242
+
243
+ return defineGuardRule({
244
+ id,
245
+ severity,
246
+ description,
247
+ check(ctx: GuardRuleContext): GuardViolation[] {
248
+ if (!matchesAny(ctx.sourceFile, options.patterns)) return [];
249
+
250
+ const exportedNames = new Set<string>();
251
+ for (const exp of ctx.exports) {
252
+ if (exp.type === "named" || exp.type === "default") {
253
+ if (exp.name) exportedNames.add(exp.name);
254
+ }
255
+ }
256
+
257
+ const missing = options.names.filter((n) => !exportedNames.has(n));
258
+
259
+ if (options.requireAny) {
260
+ if (missing.length === options.names.length) {
261
+ return [
262
+ {
263
+ file: ctx.sourceFile,
264
+ message: `Missing required export: expected at least one of [${options.names.join(", ")}], found none.`,
265
+ hint,
266
+ docsUrl: options.docsUrl,
267
+ },
268
+ ];
269
+ }
270
+ return [];
271
+ }
272
+
273
+ if (missing.length === 0) return [];
274
+ return [
275
+ {
276
+ file: ctx.sourceFile,
277
+ message: `Missing required exports: ${missing.join(", ")}.`,
278
+ hint,
279
+ docsUrl: options.docsUrl,
280
+ },
281
+ ];
282
+ },
283
+ });
284
+ }
285
+
286
+ // ═══════════════════════════════════════════════════════════════════════════
287
+ // requirePrefixForExports
288
+ // ═══════════════════════════════════════════════════════════════════════════
289
+
290
+ /**
291
+ * Options for {@link requirePrefixForExports}.
292
+ */
293
+ export interface RequirePrefixForExportsOptions {
294
+ /**
295
+ * Only files whose path matches one of these patterns are checked.
296
+ */
297
+ patterns: ReadonlyArray<string | RegExp>;
298
+ /**
299
+ * Prefix that every named export must match. String is treated as a
300
+ * literal prefix (`startsWith`); RegExp is `.test()`-ed against the
301
+ * full export name.
302
+ */
303
+ prefix: string | RegExp;
304
+ /**
305
+ * Export names to exempt from the check (e.g. `"default"`, helper
306
+ * types). Literal strings only — kept simple because this is the
307
+ * common case.
308
+ */
309
+ allowList?: readonly string[];
310
+ /**
311
+ * When `true`, only check exports whose `type` is `"named"` (skip
312
+ * `default`, `all`, and `type` re-exports). Defaults to `true`.
313
+ */
314
+ onlyNamed?: boolean;
315
+ /** Rule severity. Defaults to `"error"`. */
316
+ severity?: GuardRuleSeverity;
317
+ /** Override rule `id`. Defaults to `require-prefix:<normalized-prefix>`. */
318
+ id?: string;
319
+ /** Override rule `description`. */
320
+ description?: string;
321
+ /** Remediation hint. */
322
+ hint?: string;
323
+ /** Optional docs URL. */
324
+ docsUrl?: string;
325
+ }
326
+
327
+ /**
328
+ * Create a rule that requires every named export in matching files to
329
+ * match `prefix`. Classic use case: enforce that `app/api/**\/route.ts`
330
+ * files only export HTTP verb names (`GET`, `POST`, ...).
331
+ */
332
+ export function requirePrefixForExports(options: RequirePrefixForExportsOptions): GuardRule {
333
+ if (!Array.isArray(options.patterns) || options.patterns.length === 0) {
334
+ throw new TypeError("requirePrefixForExports: `patterns` must be a non-empty array.");
335
+ }
336
+
337
+ const prefixRegex =
338
+ options.prefix instanceof RegExp
339
+ ? options.prefix
340
+ : new RegExp(`^${options.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
341
+ const id = options.id ?? `require-prefix:${normalizeIdFragment(options.prefix)}`;
342
+ const description =
343
+ options.description ??
344
+ `Named exports in matching files must start with \`${options.prefix instanceof RegExp ? options.prefix.source : options.prefix}\`.`;
345
+ const hint =
346
+ options.hint ??
347
+ `Rename the export to match the required prefix, or move the helper to a different module.`;
348
+ const severity = options.severity ?? "error";
349
+ const allowSet = new Set(options.allowList ?? []);
350
+ const onlyNamed = options.onlyNamed ?? true;
351
+
352
+ return defineGuardRule({
353
+ id,
354
+ severity,
355
+ description,
356
+ check(ctx: GuardRuleContext): GuardViolation[] {
357
+ if (!matchesAny(ctx.sourceFile, options.patterns)) return [];
358
+
359
+ const violations: GuardViolation[] = [];
360
+ for (const exp of ctx.exports) {
361
+ if (onlyNamed && exp.type !== "named") continue;
362
+ if (!exp.name) continue;
363
+ if (allowSet.has(exp.name)) continue;
364
+ if (prefixRegex.test(exp.name)) continue;
365
+
366
+ violations.push({
367
+ file: ctx.sourceFile,
368
+ line: exp.line,
369
+ message: `Export \`${exp.name}\` does not match the required prefix ${
370
+ options.prefix instanceof RegExp ? options.prefix.source : `"${options.prefix}"`
371
+ }.`,
372
+ hint,
373
+ docsUrl: options.docsUrl,
374
+ });
375
+ }
376
+ return violations;
377
+ },
378
+ });
379
+ }