@mandujs/core 0.30.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.
- package/package.json +7 -1
- package/src/client/index.ts +11 -1
- package/src/client/rpc.ts +293 -140
- package/src/config/mandu.ts +107 -1
- package/src/config/validate.ts +145 -1
- package/src/contract/index.ts +18 -0
- package/src/contract/rpc.ts +443 -0
- package/src/filling/context.ts +60 -0
- package/src/guard/check.ts +225 -1
- package/src/guard/define-rule.ts +243 -0
- package/src/guard/index.ts +26 -0
- package/src/guard/rule-presets.ts +379 -0
- package/src/i18n/define.ts +126 -0
- package/src/i18n/index.ts +52 -0
- package/src/i18n/locale-resolver.ts +214 -0
- package/src/i18n/message-registry.ts +173 -0
- package/src/i18n/types.ts +112 -0
- package/src/middleware/index.ts +7 -0
- package/src/middleware/scheduler-cron.ts +96 -0
- package/src/router/fs-scanner.ts +101 -0
- package/src/router/index.ts +7 -1
- package/src/runtime/server.ts +432 -9
- package/src/runtime/ssr.ts +9 -0
- package/src/scheduler/index.ts +547 -343
- package/src/scheduler/validate.ts +169 -0
package/src/filling/context.ts
CHANGED
|
@@ -20,6 +20,8 @@ import {
|
|
|
20
20
|
type SpanAttributes,
|
|
21
21
|
type SpanOptions,
|
|
22
22
|
} from "../observability/tracing";
|
|
23
|
+
// Phase 18.μ — i18n integration.
|
|
24
|
+
import type { ResolvedLocale, Translator } from "../i18n/types";
|
|
23
25
|
|
|
24
26
|
type ContractInput<
|
|
25
27
|
TContract extends ContractSchema,
|
|
@@ -332,6 +334,18 @@ export class ManduContext {
|
|
|
332
334
|
private _deps: FillingDeps;
|
|
333
335
|
private _cacheMeta: { tags: string[]; maxAge?: number; staleWhileRevalidate?: number } = { tags: [] };
|
|
334
336
|
private _cacheHelper: CacheHelper | null = null;
|
|
337
|
+
/**
|
|
338
|
+
* Phase 18.μ — resolved active locale. `undefined` when the server has
|
|
339
|
+
* no `ManduConfig.i18n` configured (zero-overhead — the runtime never
|
|
340
|
+
* attaches this field). Populated by `runtime/server.ts` μ dispatch.
|
|
341
|
+
*/
|
|
342
|
+
private _locale: ResolvedLocale | undefined = undefined;
|
|
343
|
+
/**
|
|
344
|
+
* Phase 18.μ — typed translator bound to the active locale. `undefined`
|
|
345
|
+
* until the runtime attaches one via `_setI18n()`. User code should
|
|
346
|
+
* null-check via `ctx.t?.(...)` OR require i18n via a type predicate.
|
|
347
|
+
*/
|
|
348
|
+
private _t: Translator | undefined = undefined;
|
|
335
349
|
|
|
336
350
|
constructor(
|
|
337
351
|
public readonly request: Request,
|
|
@@ -397,6 +411,52 @@ export class ManduContext {
|
|
|
397
411
|
};
|
|
398
412
|
}
|
|
399
413
|
|
|
414
|
+
/**
|
|
415
|
+
* Phase 18.μ — active resolved locale. `undefined` when i18n is
|
|
416
|
+
* disabled at server boot (`ManduConfig.i18n` omitted). Populated by
|
|
417
|
+
* the runtime dispatcher BEFORE loader + render so downstream code
|
|
418
|
+
* can branch on it without threading state manually.
|
|
419
|
+
*
|
|
420
|
+
* @example
|
|
421
|
+
* ```ts
|
|
422
|
+
* if (ctx.locale?.code === "ko") {
|
|
423
|
+
* return ctx.redirect("/ko/welcome");
|
|
424
|
+
* }
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
get locale(): ResolvedLocale | undefined {
|
|
428
|
+
return this._locale;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Phase 18.μ — typed translator bound to `ctx.locale`. `undefined`
|
|
433
|
+
* when i18n is disabled OR no message registry was supplied to
|
|
434
|
+
* `startServer()`. Unlike `ctx.locale`, this is safe to call with an
|
|
435
|
+
* unknown key — misses fall through `fallbackLocale` → `defaultLocale`
|
|
436
|
+
* → raw key per {@link createTranslator}.
|
|
437
|
+
*
|
|
438
|
+
* @example
|
|
439
|
+
* ```ts
|
|
440
|
+
* return ctx.ok({ greeting: ctx.t?.("welcome", { name: "만두" }) });
|
|
441
|
+
* ```
|
|
442
|
+
*/
|
|
443
|
+
get t(): Translator | undefined {
|
|
444
|
+
return this._t;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Phase 18.μ — runtime-internal: attach resolved locale + translator.
|
|
449
|
+
* Exposed as a method (not a public setter) so user code can't mutate
|
|
450
|
+
* mid-request. Called exactly once by the server dispatcher before
|
|
451
|
+
* loader execution.
|
|
452
|
+
*
|
|
453
|
+
* @internal
|
|
454
|
+
*/
|
|
455
|
+
_setI18n(locale: ResolvedLocale, translator?: Translator): void {
|
|
456
|
+
this._locale = locale;
|
|
457
|
+
if (translator) this._t = translator;
|
|
458
|
+
}
|
|
459
|
+
|
|
400
460
|
/**
|
|
401
461
|
* DNA-002: 의존성 접근
|
|
402
462
|
*
|
package/src/guard/check.ts
CHANGED
|
@@ -4,6 +4,14 @@ import { validateSlotContent } from "../slot/validator";
|
|
|
4
4
|
import type { RoutesManifest } from "../spec/schema";
|
|
5
5
|
import type { GeneratedMap } from "../generator/generate";
|
|
6
6
|
import { loadManduConfig, type GuardRuleSeverity } from "../config";
|
|
7
|
+
import { extractImportsAST, extractExportsAST } from "./ast-analyzer";
|
|
8
|
+
import {
|
|
9
|
+
validateCustomRules,
|
|
10
|
+
type GuardRule as CustomGuardRule,
|
|
11
|
+
type GuardRuleContext as CustomGuardRuleContext,
|
|
12
|
+
type GuardViolation as CustomGuardViolation,
|
|
13
|
+
} from "./define-rule";
|
|
14
|
+
import type { ManduConfig } from "../config/mandu";
|
|
7
15
|
import path from "path";
|
|
8
16
|
import fs from "fs/promises";
|
|
9
17
|
|
|
@@ -445,7 +453,20 @@ export async function runGuardCheck(
|
|
|
445
453
|
violations.push(...slotContentViolations);
|
|
446
454
|
violations.push(...contractViolations);
|
|
447
455
|
|
|
448
|
-
|
|
456
|
+
// ============================================
|
|
457
|
+
// Phase 18.ν — Consumer-defined custom rules
|
|
458
|
+
// ============================================
|
|
459
|
+
const customRules = (config.guard?.rules as unknown);
|
|
460
|
+
if (Array.isArray(customRules) && customRules.length > 0) {
|
|
461
|
+
const customViolations = await runCustomRules(
|
|
462
|
+
customRules as CustomGuardRule[],
|
|
463
|
+
rootDir,
|
|
464
|
+
config
|
|
465
|
+
);
|
|
466
|
+
violations.push(...customViolations);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const resolvedViolations = applyRuleSeverity(violations, normalizeGuardConfigForSeverity(config.guard));
|
|
449
470
|
const passed = resolvedViolations.every((v) => v.severity !== "error");
|
|
450
471
|
|
|
451
472
|
return {
|
|
@@ -453,3 +474,206 @@ export async function runGuardCheck(
|
|
|
453
474
|
violations: resolvedViolations,
|
|
454
475
|
};
|
|
455
476
|
}
|
|
477
|
+
|
|
478
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
479
|
+
// Phase 18.ν — Consumer-defined Guard rules
|
|
480
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* The existing `config.guard.rules` field was a `Record<string,
|
|
484
|
+
* GuardRuleSeverity>` map for built-in rule overrides. Phase 18.ν
|
|
485
|
+
* allows consumers to also pass an array of `GuardRule` objects.
|
|
486
|
+
* `applyRuleSeverity` only understands the record shape, so we strip
|
|
487
|
+
* the array out before forwarding to it.
|
|
488
|
+
*/
|
|
489
|
+
function normalizeGuardConfigForSeverity(
|
|
490
|
+
guard: ManduConfig["guard"] | undefined
|
|
491
|
+
): { rules?: Record<string, GuardRuleSeverity>; contractRequired?: GuardRuleSeverity } {
|
|
492
|
+
if (!guard) return {};
|
|
493
|
+
const rulesField = guard.rules as unknown;
|
|
494
|
+
const rules =
|
|
495
|
+
rulesField && !Array.isArray(rulesField) && typeof rulesField === "object"
|
|
496
|
+
? (rulesField as Record<string, GuardRuleSeverity>)
|
|
497
|
+
: undefined;
|
|
498
|
+
return {
|
|
499
|
+
rules,
|
|
500
|
+
contractRequired: (guard as { contractRequired?: GuardRuleSeverity }).contractRequired,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Parallel scan cap for `runCustomRules()`. Matches `safeBuild` default
|
|
506
|
+
* (`MANDU_BUN_BUILD_CONCURRENCY`) semantics — tunable via
|
|
507
|
+
* `MANDU_GUARD_CUSTOM_CONCURRENCY` positive integer env var.
|
|
508
|
+
*/
|
|
509
|
+
function customRuleConcurrency(): number {
|
|
510
|
+
const raw = process.env.MANDU_GUARD_CUSTOM_CONCURRENCY;
|
|
511
|
+
if (!raw) return 8;
|
|
512
|
+
const parsed = Number.parseInt(raw, 10);
|
|
513
|
+
if (!Number.isFinite(parsed) || parsed < 1) return 8;
|
|
514
|
+
return parsed;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Default source directories scanned for custom rules. */
|
|
518
|
+
const CUSTOM_RULE_SOURCE_DIRS = ["packages", "src", "app"];
|
|
519
|
+
|
|
520
|
+
async function collectCustomRuleSourceFiles(rootDir: string): Promise<string[]> {
|
|
521
|
+
const files = await Promise.all(
|
|
522
|
+
CUSTOM_RULE_SOURCE_DIRS.map((d) => scanTsFiles(path.join(rootDir, d)))
|
|
523
|
+
);
|
|
524
|
+
// Deduplicate paths (a file could in theory live under multiple roots
|
|
525
|
+
// if a consumer symlinks, which the walker doesn't follow but we
|
|
526
|
+
// guard anyway).
|
|
527
|
+
return Array.from(new Set(files.flat()));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Convert a consumer-defined `GuardViolation` into the standard Guard
|
|
532
|
+
* report `GuardViolation` shape. Adds the `custom:<id>` ruleId prefix
|
|
533
|
+
* so the reporter can attribute each entry unambiguously.
|
|
534
|
+
*/
|
|
535
|
+
function toReportViolation(
|
|
536
|
+
rule: CustomGuardRule,
|
|
537
|
+
violation: CustomGuardViolation
|
|
538
|
+
): GuardViolation {
|
|
539
|
+
const severity: "error" | "warning" =
|
|
540
|
+
rule.severity === "error" ? "error" : "warning";
|
|
541
|
+
return {
|
|
542
|
+
ruleId: `custom:${rule.id}`,
|
|
543
|
+
file: violation.file,
|
|
544
|
+
message: violation.message,
|
|
545
|
+
suggestion: violation.hint ?? violation.docsUrl ?? "",
|
|
546
|
+
line: violation.line,
|
|
547
|
+
severity,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Execute every consumer-defined rule against every source file under
|
|
553
|
+
* `rootDir`. Rules are awaited per-file with a concurrency cap; a
|
|
554
|
+
* single rule throwing is caught and reported as a `custom:<id>`
|
|
555
|
+
* violation so the rest of the scan still completes.
|
|
556
|
+
*
|
|
557
|
+
* Exported for tests; not re-exported via `guard/index.ts` to keep the
|
|
558
|
+
* public surface small.
|
|
559
|
+
*/
|
|
560
|
+
export async function runCustomRules(
|
|
561
|
+
rules: readonly CustomGuardRule[],
|
|
562
|
+
rootDir: string,
|
|
563
|
+
config: ManduConfig
|
|
564
|
+
): Promise<GuardViolation[]> {
|
|
565
|
+
const { duplicates, malformed } = validateCustomRules(rules);
|
|
566
|
+
const results: GuardViolation[] = [];
|
|
567
|
+
|
|
568
|
+
if (malformed.length > 0) {
|
|
569
|
+
for (const idx of malformed) {
|
|
570
|
+
results.push({
|
|
571
|
+
ruleId: "custom:__invalid__",
|
|
572
|
+
file: "mandu.config",
|
|
573
|
+
message: `guard.rules[${idx}] is not a valid GuardRule (missing \`id\` or \`check()\`).`,
|
|
574
|
+
suggestion:
|
|
575
|
+
"Wrap the rule with defineGuardRule({...}) or import a preset from @mandujs/core/guard/define-rule.",
|
|
576
|
+
severity: "error",
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (duplicates.length > 0) {
|
|
582
|
+
for (const dup of duplicates) {
|
|
583
|
+
// Warning-level so duplicates don't gate CI but still surface in the
|
|
584
|
+
// report. Matches the "soft failure" convention used by config-guard.
|
|
585
|
+
results.push({
|
|
586
|
+
ruleId: `custom:${dup.id}`,
|
|
587
|
+
file: "mandu.config",
|
|
588
|
+
message: `Duplicate guard.rules id "${dup.id}" at indices [${dup.indices.join(", ")}] — only the first instance will be enforced.`,
|
|
589
|
+
suggestion: "Give each rule a unique \`id\`, or remove the duplicate.",
|
|
590
|
+
severity: "warning",
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Deduplicate rules by id (keep first occurrence). Matches the
|
|
596
|
+
// warning emitted above.
|
|
597
|
+
const seen = new Set<string>();
|
|
598
|
+
const uniqueRules = rules.filter((r) => {
|
|
599
|
+
if (!r || typeof r !== "object" || typeof (r as CustomGuardRule).id !== "string") return false;
|
|
600
|
+
const id = (r as CustomGuardRule).id;
|
|
601
|
+
if (seen.has(id)) return false;
|
|
602
|
+
seen.add(id);
|
|
603
|
+
return true;
|
|
604
|
+
});
|
|
605
|
+
if (uniqueRules.length === 0) return results;
|
|
606
|
+
|
|
607
|
+
const files = await collectCustomRuleSourceFiles(rootDir);
|
|
608
|
+
if (files.length === 0) return results;
|
|
609
|
+
|
|
610
|
+
const cap = customRuleConcurrency();
|
|
611
|
+
let cursor = 0;
|
|
612
|
+
|
|
613
|
+
async function worker(): Promise<GuardViolation[]> {
|
|
614
|
+
const local: GuardViolation[] = [];
|
|
615
|
+
while (true) {
|
|
616
|
+
const index = cursor++;
|
|
617
|
+
if (index >= files.length) return local;
|
|
618
|
+
const filePath = files[index];
|
|
619
|
+
|
|
620
|
+
// Skip __generated__ and build output.
|
|
621
|
+
if (filePath.includes("__generated__") || filePath.includes(".mandu/")) continue;
|
|
622
|
+
|
|
623
|
+
let content: string;
|
|
624
|
+
try {
|
|
625
|
+
content = await Bun.file(filePath).text();
|
|
626
|
+
} catch {
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
let imports: ReturnType<typeof extractImportsAST>;
|
|
631
|
+
let exportsAst: ReturnType<typeof extractExportsAST>;
|
|
632
|
+
try {
|
|
633
|
+
imports = extractImportsAST(content);
|
|
634
|
+
exportsAst = extractExportsAST(content);
|
|
635
|
+
} catch {
|
|
636
|
+
// Tokenizer failure on an exotic file — skip rather than abort.
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const relFile = path.relative(rootDir, filePath) || filePath;
|
|
641
|
+
const ctx: CustomGuardRuleContext = {
|
|
642
|
+
sourceFile: relFile.replace(/\\/g, "/"),
|
|
643
|
+
content,
|
|
644
|
+
imports,
|
|
645
|
+
exports: exportsAst,
|
|
646
|
+
config,
|
|
647
|
+
projectRoot: rootDir,
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
for (const rule of uniqueRules) {
|
|
651
|
+
try {
|
|
652
|
+
const violations = await rule.check(ctx);
|
|
653
|
+
if (!Array.isArray(violations)) continue;
|
|
654
|
+
for (const v of violations) {
|
|
655
|
+
if (!v || typeof v !== "object") continue;
|
|
656
|
+
local.push(toReportViolation(rule, v));
|
|
657
|
+
}
|
|
658
|
+
} catch (err) {
|
|
659
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
660
|
+
local.push({
|
|
661
|
+
ruleId: `custom:${rule.id}`,
|
|
662
|
+
file: ctx.sourceFile,
|
|
663
|
+
message: `Rule "${rule.id}" threw: ${message}`,
|
|
664
|
+
suggestion: "Fix the rule's check() implementation or wrap it in a try/catch.",
|
|
665
|
+
severity: rule.severity === "error" ? "error" : "warning",
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const workerCount = Math.min(cap, files.length);
|
|
673
|
+
const workers: Promise<GuardViolation[]>[] = [];
|
|
674
|
+
for (let i = 0; i < workerCount; i++) workers.push(worker());
|
|
675
|
+
const chunks = await Promise.all(workers);
|
|
676
|
+
for (const chunk of chunks) results.push(...chunk);
|
|
677
|
+
|
|
678
|
+
return results;
|
|
679
|
+
}
|
|
@@ -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
|
+
}
|
package/src/guard/index.ts
CHANGED
|
@@ -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
|
// ═══════════════════════════════════════════════════════════════════════════
|