@mandujs/core 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -1
- package/src/bundler/build.ts +29 -1
- package/src/bundler/generate-static-params.ts +302 -290
- package/src/bundler/prerender.ts +446 -368
- package/src/bundler/types.ts +20 -0
- package/src/config/mandu.ts +58 -1
- package/src/config/validate.ts +119 -1
- package/src/diagnose/__tests__/checks.test.ts +378 -0
- package/src/diagnose/checks.ts +599 -0
- package/src/diagnose/index.ts +15 -0
- package/src/diagnose/run.ts +87 -0
- package/src/diagnose/types.ts +53 -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/graph.ts +898 -0
- package/src/guard/index.ts +40 -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/plugins/__tests__/lifecycle-integration.test.ts +272 -0
- package/src/plugins/__tests__/runner.test.ts +409 -0
- package/src/plugins/define.ts +124 -0
- package/src/plugins/examples/dep-check-plugin.ts +80 -0
- package/src/plugins/examples/prerender-cache-plugin.ts +111 -0
- package/src/plugins/examples/sitemap-plugin.ts +65 -0
- package/src/plugins/hooks.ts +297 -64
- package/src/plugins/index.ts +80 -41
- package/src/plugins/runner.ts +361 -0
- package/src/router/fs-routes.ts +64 -1
- package/src/router/fs-scanner.ts +101 -0
- package/src/router/index.ts +7 -1
- package/src/runtime/server.ts +409 -10
- package/src/runtime/ssr.ts +9 -0
- package/src/spec/schema.ts +25 -0
- package/src/testing/__tests__/reporter.test.ts +454 -0
- package/src/testing/index.ts +29 -0
- package/src/testing/reporter.ts +676 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Diagnose — aggregator.
|
|
3
|
+
*
|
|
4
|
+
* Runs all registered checks in parallel (they are pure I/O, no shared
|
|
5
|
+
* mutable state) and builds a unified `DiagnoseReport`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { DiagnoseCheckResult, DiagnoseReport } from "./types";
|
|
9
|
+
import {
|
|
10
|
+
checkManifestFreshness,
|
|
11
|
+
checkPrerenderPollution,
|
|
12
|
+
checkCloneElementWarnings,
|
|
13
|
+
checkDevArtifactsInProd,
|
|
14
|
+
checkPackageExportGaps,
|
|
15
|
+
} from "./checks";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Registered extended checks (Issue #215). These are the five checks that
|
|
19
|
+
* supplement the legacy guard/contract/manifest/kitchen validation in MCP.
|
|
20
|
+
*
|
|
21
|
+
* Order matters for display purposes only — result aggregation is
|
|
22
|
+
* order-independent.
|
|
23
|
+
*/
|
|
24
|
+
export const EXTENDED_CHECKS = [
|
|
25
|
+
{ name: "manifest_freshness", run: checkManifestFreshness },
|
|
26
|
+
{ name: "prerender_pollution", run: checkPrerenderPollution },
|
|
27
|
+
{ name: "cloneelement_warnings", run: checkCloneElementWarnings },
|
|
28
|
+
{ name: "dev_artifacts_in_prod", run: checkDevArtifactsInProd },
|
|
29
|
+
{ name: "package_export_gaps", run: checkPackageExportGaps },
|
|
30
|
+
] as const;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Run every extended check in parallel and return the aggregate report.
|
|
34
|
+
*
|
|
35
|
+
* Legacy checks (kitchen_errors, guard_check, contract_validation,
|
|
36
|
+
* manifest_validation) are NOT run here — they live in the MCP tool
|
|
37
|
+
* surface and have different dependency requirements. Instead, the MCP
|
|
38
|
+
* `mandu.diagnose` composite combines the extended checks with the
|
|
39
|
+
* legacy ones and normalizes both into a single unified report.
|
|
40
|
+
*/
|
|
41
|
+
export async function runExtendedDiagnose(rootDir: string): Promise<DiagnoseReport> {
|
|
42
|
+
const checks = await Promise.all(
|
|
43
|
+
EXTENDED_CHECKS.map(async ({ run }) => {
|
|
44
|
+
try {
|
|
45
|
+
return await run(rootDir);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
// Defensive fallback — individual checks shouldn't throw, but if
|
|
48
|
+
// one does, we surface it as an error rather than crashing the
|
|
49
|
+
// whole diagnose run.
|
|
50
|
+
return {
|
|
51
|
+
ok: false,
|
|
52
|
+
rule: "diagnose_internal_error",
|
|
53
|
+
severity: "error" as const,
|
|
54
|
+
message: `Check threw an error: ${err instanceof Error ? err.message : String(err)}`,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
return buildReport(checks);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Aggregate a pre-computed list of check results into a `DiagnoseReport`.
|
|
65
|
+
* Exported so the MCP composite can pass in both extended + legacy checks
|
|
66
|
+
* at once.
|
|
67
|
+
*/
|
|
68
|
+
export function buildReport(checks: DiagnoseCheckResult[]): DiagnoseReport {
|
|
69
|
+
let errorCount = 0;
|
|
70
|
+
let warningCount = 0;
|
|
71
|
+
for (const c of checks) {
|
|
72
|
+
if (c.ok) continue;
|
|
73
|
+
if (c.severity === "error") errorCount += 1;
|
|
74
|
+
else if (c.severity === "warning") warningCount += 1;
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
healthy: errorCount === 0,
|
|
78
|
+
errorCount,
|
|
79
|
+
warningCount,
|
|
80
|
+
checks,
|
|
81
|
+
summary: {
|
|
82
|
+
total: checks.length,
|
|
83
|
+
passed: checks.filter((c) => c.ok).length,
|
|
84
|
+
failed: checks.filter((c) => !c.ok).length,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Diagnose — unified check result shape.
|
|
3
|
+
*
|
|
4
|
+
* Every diagnose check returns a `DiagnoseCheckResult`. Severity semantics:
|
|
5
|
+
*
|
|
6
|
+
* - `error` : blocks deploy. CI should fail. Example: stale dev-mode
|
|
7
|
+
* manifest shipped to prod, package export gap, empty bundles
|
|
8
|
+
* with islands declared.
|
|
9
|
+
* - `warning` : degraded UX or future risk. Does NOT block deploy, but
|
|
10
|
+
* surfaces for operator attention. Example: suspicious
|
|
11
|
+
* prerendered routes, many cloneElement warnings.
|
|
12
|
+
* - `info` : neutral observation, no action required.
|
|
13
|
+
*
|
|
14
|
+
* The `rule` field is a stable machine-readable identifier. The `message`
|
|
15
|
+
* field is human-readable and MAY include route paths or counts. The
|
|
16
|
+
* optional `suggestion` field is a single actionable next step.
|
|
17
|
+
*/
|
|
18
|
+
export type DiagnoseSeverity = "error" | "warning" | "info";
|
|
19
|
+
|
|
20
|
+
export interface DiagnoseCheckResult {
|
|
21
|
+
/** Overall pass/fail for this check. `true` = healthy. */
|
|
22
|
+
ok: boolean;
|
|
23
|
+
/** Stable machine-readable rule id, e.g. `manifest_freshness`. */
|
|
24
|
+
rule: string;
|
|
25
|
+
/** Severity when `ok === false`. Omitted when `ok === true`. */
|
|
26
|
+
severity?: DiagnoseSeverity;
|
|
27
|
+
/** Human-readable summary. */
|
|
28
|
+
message: string;
|
|
29
|
+
/** Single-line actionable next step, e.g. `"Run mandu build"`. */
|
|
30
|
+
suggestion?: string;
|
|
31
|
+
/** Structured details (route list, counts, file paths). */
|
|
32
|
+
details?: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Aggregated report across all checks for a single diagnose run.
|
|
37
|
+
*/
|
|
38
|
+
export interface DiagnoseReport {
|
|
39
|
+
/** `true` when no check has `ok: false` with `severity: 'error'`. */
|
|
40
|
+
healthy: boolean;
|
|
41
|
+
/** Count of checks returning `ok: false` with `severity: 'error'`. */
|
|
42
|
+
errorCount: number;
|
|
43
|
+
/** Count of checks returning `ok: false` with `severity: 'warning'`. */
|
|
44
|
+
warningCount: number;
|
|
45
|
+
/** Individual check results in registration order. */
|
|
46
|
+
checks: DiagnoseCheckResult[];
|
|
47
|
+
/** Summary statistics. */
|
|
48
|
+
summary: {
|
|
49
|
+
total: number;
|
|
50
|
+
passed: number;
|
|
51
|
+
failed: number;
|
|
52
|
+
};
|
|
53
|
+
}
|
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
|
+
}
|