@aipanel/core 1.3.4 → 1.3.5

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.
@@ -1,29 +1,30 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
3
4
  import { execa } from "execa";
4
5
  import { createRequire } from "node:module";
5
6
  import { SEVERITY_ERROR, SEVERITY_WARN } from "../common/constants.mjs";
7
+ import {
8
+ BUILTIN_LINTERS,
9
+ COMMAND_CHECK_TIMEOUT_MS,
10
+ SOURCE_EXTENSIONS,
11
+ checkRunsInPhase,
12
+ isCommandCheck,
13
+ isLinterPreset,
14
+ isTypecheckCheck,
15
+ matchesExtensions
16
+ } from "../common/diagnostics.mjs";
6
17
  import { createLogger } from "./node-logger.mjs";
7
18
  const log = createLogger("Diagnostics");
8
- const JS_EXTENSIONS = /* @__PURE__ */ new Set([
9
- ".js",
10
- ".jsx",
11
- ".ts",
12
- ".tsx",
13
- ".mjs",
14
- ".cjs",
15
- ".mts",
16
- ".cts",
17
- ".vue"
18
- ]);
19
+ const JS_EXTENSIONS = new Set(SOURCE_EXTENSIONS);
19
20
  function isJsFile(filePath) {
20
21
  return JS_EXTENSIONS.has(path.extname(filePath));
21
22
  }
22
23
  const DIAGNOSTICS_TOOL_DESCRIPTION = [
23
- "\u8FD0\u884C Lint\uFF08ESLint / oxlint\uFF09\u4E0E TypeScript \u7C7B\u578B\u8BCA\u65AD\uFF0C\u8FD4\u56DE\u8BCA\u65AD\u7ED3\u679C\u3002",
24
+ "\u8FD0\u884C\u9879\u76EE\u914D\u7F6E\u7684\u4EE3\u7801\u68C0\u67E5\uFF08\u9ED8\u8BA4 Lint \u4E0E TypeScript \u7C7B\u578B\u8BCA\u65AD\uFF09\uFF0C\u8FD4\u56DE\u8BCA\u65AD\u7ED3\u679C\u3002",
24
25
  "",
25
26
  "**\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B**\uFF1A",
26
- `- Lint\uFF1AJavaScript / TypeScript / Vue \u6E90\u7801\uFF08${[...JS_EXTENSIONS].map((e) => `*${e}`).join(" ")}\uFF09\uFF1B\u4E24\u5F15\u64CE\u5747\u5B89\u88C5\u65F6\u5E76\u884C\u4E92\u8865\u8FD0\u884C\uFF08\u8BCA\u65AD\u6309\u6765\u6E90\u6807\u6CE8\uFF09`,
27
+ `- Lint\uFF1AJavaScript / TypeScript / Vue \u6E90\u7801\uFF08${[...JS_EXTENSIONS].map((e) => `*${e}`).join(" ")}\uFF09\uFF1B\u9879\u76EE\u540C\u65F6\u88C5\u6709 ESLint \u4E0E oxlint \u65F6\u4E92\u8865\u8FD0\u884C\uFF08\u8BCA\u65AD\u6309\u6765\u6E90\u6807\u6CE8\uFF09`,
27
28
  "- TypeScript \u7C7B\u578B\u68C0\u67E5\uFF1A*.ts *.tsx *.vue",
28
29
  "",
29
30
  "**\u4F55\u65F6\u4F7F\u7528\u6B64\u5DE5\u5177**\uFF1A",
@@ -53,53 +54,14 @@ function resolvePackageBin(basePkgJson, pkgName, binName) {
53
54
  }
54
55
  });
55
56
  }
56
- const _eslintClassByBase = /* @__PURE__ */ new Map();
57
- function loadESLint(workspace) {
58
- const basePkgJson = path.join(workspace, "package.json");
59
- return cachedResolve(_eslintClassByBase, basePkgJson, () => {
60
- log.debug("Loading eslint", { workspace });
61
- try {
62
- const req = createRequire(basePkgJson);
63
- const eslintModule = req("eslint");
64
- const eslintClass = eslintModule.ESLint ?? eslintModule.FlatESLint ?? null;
65
- log.debug("eslint loaded", { hasClass: !!eslintClass });
66
- return eslintClass;
67
- } catch (e) {
68
- log.warn("eslint not found", { error: e.message });
69
- return null;
70
- }
71
- });
72
- }
73
- async function lintFiles(pattern, cwd, warnLimit = 5) {
74
- const eslintClass = loadESLint(cwd);
75
- const [eslintOutput, oxlintOutput] = await Promise.all([
76
- eslintClass ? runEslintFiles(eslintClass, pattern, cwd, warnLimit) : Promise.resolve(null),
77
- runOxlintFiles(pattern, cwd, warnLimit)
78
- ]);
79
- const engines = [];
80
- const texts = [];
81
- const diagnostics = [];
82
- for (const output of [eslintOutput, oxlintOutput]) {
83
- if (!output) continue;
84
- engines.push(...output.engines ?? []);
85
- if (output.text) texts.push(output.text);
86
- diagnostics.push(...output.diagnostics ?? []);
87
- }
88
- if (engines.length === 0) {
89
- return {
90
- text: `[Lint] \u672A\u8FD0\u884C\uFF1A\u65E0\u6CD5\u5728 workspace "${cwd}" \u89E3\u6790\u5230 eslint \u6216 oxlint`,
91
- diagnostics: []
92
- };
93
- }
94
- return { text: texts.join("\n\n") || void 0, diagnostics, engines };
95
- }
96
- function formatLintMessages(messages, engine, warnLimit) {
97
- if (messages.length === 0) return { engines: [engine.label] };
57
+ function formatLintMessages(messages, engine, warnLimit, minSeverity = "warning") {
98
58
  const ESLINT_ERROR = 2;
99
59
  const ESLINT_WARN = 1;
60
+ const kept = minSeverity === "error" ? messages.filter((m) => m.severity === ESLINT_ERROR) : messages;
61
+ if (kept.length === 0) return {};
100
62
  const lines = [];
101
- const errors = messages.filter((m) => m.severity === ESLINT_ERROR);
102
- const warnings = messages.filter((m) => m.severity === ESLINT_WARN);
63
+ const errors = kept.filter((m) => m.severity === ESLINT_ERROR);
64
+ const warnings = kept.filter((m) => m.severity === ESLINT_WARN);
103
65
  if (errors.length > 0) {
104
66
  lines.push(
105
67
  ...errors.map(
@@ -129,35 +91,9 @@ function formatLintMessages(messages, engine, warnLimit) {
129
91
  }));
130
92
  return {
131
93
  text: lines.length > 0 ? lines.join("\n") : void 0,
132
- diagnostics,
133
- engines: [engine.label]
94
+ diagnostics
134
95
  };
135
96
  }
136
- async function runEslintFiles(eslintClass, pattern, cwd, warnLimit) {
137
- try {
138
- const eslint = new eslintClass({ cwd });
139
- const results = await eslint.lintFiles(pattern);
140
- const messages = results.flatMap(
141
- (r) => (r.messages ?? []).map((m) => ({ ...m, filePath: r.filePath }))
142
- );
143
- log.debug("ESLint lint", {
144
- pattern,
145
- fileCount: results.length,
146
- messageCount: messages.length
147
- });
148
- return formatLintMessages(messages, { label: "ESLint", source: "eslint" }, warnLimit);
149
- } catch (err) {
150
- log.warn("ESLint failed", { pattern, error: err.message });
151
- return {
152
- text: `[ESLint] \u8FD0\u884C\u5931\u8D25\uFF1A${err.message}\uFF08\u4EC5\u663E\u793A TypeScript \u8BCA\u65AD\uFF09`,
153
- diagnostics: [],
154
- engines: ["ESLint"]
155
- };
156
- }
157
- }
158
- function resolveOxlintBin(workspace) {
159
- return resolvePackageBin(path.join(workspace, "package.json"), "oxlint", "oxlint");
160
- }
161
97
  function oxlintRuleName(code) {
162
98
  if (!code) return null;
163
99
  const match = /\(([^)]*)\)$/.exec(code);
@@ -200,39 +136,6 @@ function parseOxlintOutput(stdout, cwd) {
200
136
  ];
201
137
  });
202
138
  }
203
- async function runOxlintFiles(pattern, cwd, warnLimit) {
204
- const bin = resolveOxlintBin(cwd);
205
- if (!bin) return {};
206
- const result = await execa(
207
- "node",
208
- [bin, "--format=json", "--ignore-pattern", "node_modules", pattern],
209
- { cwd, timeout: 6e4, maxBuffer: 50 * 1024 * 1024, reject: false }
210
- );
211
- if (result.timedOut || result.isTerminated || result.isMaxBuffer) {
212
- log.warn("oxlint timed out", { pattern });
213
- return {
214
- text: "[oxlint] \u8FD0\u884C\u5931\u8D25\uFF1A\u68C0\u67E5\u8D85\u65F6\uFF0C\u8BF7\u5C1D\u8BD5\u7F29\u5C0F\u68C0\u67E5\u8303\u56F4\u3002",
215
- diagnostics: [],
216
- engines: ["oxlint"]
217
- };
218
- }
219
- try {
220
- const messages = parseOxlintOutput(result.stdout, cwd);
221
- log.debug("oxlint lint", {
222
- pattern,
223
- messageCount: messages.length,
224
- stderr: result.stderr || void 0
225
- });
226
- return formatLintMessages(messages, { label: "oxlint", source: "oxlint" }, warnLimit);
227
- } catch (e) {
228
- log.warn("oxlint failed", { pattern, error: e.message });
229
- return {
230
- text: `[oxlint] \u8FD0\u884C\u5931\u8D25\uFF1A${e.message}`,
231
- diagnostics: [],
232
- engines: ["oxlint"]
233
- };
234
- }
235
- }
236
139
  const BUNDLED_ENGINE_KEY = "<bundled>";
237
140
  const _engineCache = /* @__PURE__ */ new Map();
238
141
  const _tsVersionCache = /* @__PURE__ */ new Map();
@@ -523,47 +426,9 @@ async function runTypeChecksForFiles(files, cwd) {
523
426
  }
524
427
  return results;
525
428
  }
526
- async function runAllChecks(pattern, cwd) {
527
- log.debug("runAllChecks", { pattern, cwd });
528
- const [eslintOutput, tscOutput] = await Promise.all([
529
- lintFiles(pattern, cwd),
530
- runTypeCheck(pattern, cwd)
531
- ]);
532
- return { eslintOutput, tscOutput };
533
- }
534
- async function runAllChecksForFiles(files, cwd) {
535
- const targets = [...new Set(files.map((file) => path.resolve(file)))];
536
- const tscByFile = await runTypeChecksForFiles(targets, cwd);
537
- const results = /* @__PURE__ */ new Map();
538
- for (const file of targets) {
539
- results.set(file, {
540
- eslintOutput: await lintFiles(file, cwd),
541
- tscOutput: tscByFile.get(file) ?? { rawOutput: "", exitCode: 0 }
542
- });
543
- }
544
- return results;
545
- }
546
- async function runProjectDiagnostics(workspace) {
547
- const tscDirs = fs.existsSync(path.join(workspace, "tsconfig.json")) ? [workspace] : findAllTsconfigDirs(workspace);
548
- log.debug("Tsc dirs to check", { count: tscDirs.length, dirs: tscDirs });
549
- const [eslintOutput, ...tscOutputs] = await Promise.all([
550
- lintFiles(".", workspace, 10),
551
- ...tscDirs.map((dir) => runTypeCheck(void 0, dir))
552
- ]);
553
- const mergedTsc = {
554
- rawOutput: tscOutputs.flatMap((o) => o.rawOutput).filter(Boolean).join("\n"),
555
- exitCode: tscOutputs.reduce((max, o) => Math.max(max, o.exitCode), 0),
556
- diagnostics: tscOutputs.flatMap((o) => o.diagnostics ?? []),
557
- source: tscOutputs.find((o) => o.source)?.source
558
- };
559
- return { eslintOutput, tscOutput: mergedTsc };
560
- }
561
429
  function tscSectionTitle(tscOutput) {
562
430
  return tscOutput.source ?? "tsc";
563
431
  }
564
- function lintSectionTitle(lintOutput) {
565
- return lintOutput.engines?.length ? lintOutput.engines.join(" + ") : "ESLint";
566
- }
567
432
  function omittedFindingsHint(omitted) {
568
433
  return `\u2026\u8FD8\u6709 ${omitted} \u6761\uFF0C\u5B8C\u6574\u7ED3\u679C\u8BF7\u8C03\u7528 run_diagnostics`;
569
434
  }
@@ -575,38 +440,492 @@ function boundFindings(text, maxFindings) {
575
440
  "\n"
576
441
  );
577
442
  }
578
- function formatDiagnosticsSections(title, eslintOutput, tscOutput, options = {}) {
579
- const lintLines = boundFindings(eslintOutput.text, options.maxFindingsPerSection);
580
- const tscLines = boundFindings(tscOutput.rawOutput.trim(), options.maxFindingsPerSection);
581
- const parts = [];
582
- if (!options.onlyFindings || lintLines) {
583
- parts.push(`## ${lintSectionTitle(eslintOutput)}
584
-
585
- ` + (lintLines || "\u6CA1\u6709\u53D1\u73B0\u95EE\u9898"));
443
+ function displayPath(cwd, file) {
444
+ const rel = path.relative(cwd, file);
445
+ return rel.startsWith("..") || path.isAbsolute(rel) ? file : rel;
446
+ }
447
+ function targetFiles(target) {
448
+ if (target.kind === "file") return [path.resolve(target.file)];
449
+ if (target.kind === "edited") return [...new Set(target.files.map((file) => path.resolve(file)))];
450
+ return [];
451
+ }
452
+ function splitsByFile(target) {
453
+ return target.kind === "edited";
454
+ }
455
+ function filterBySeverity(items, severity) {
456
+ return severity === "error" ? items.filter((item) => item.severity === SEVERITY_ERROR) : [...items];
457
+ }
458
+ function renderDiagnosticLines(items) {
459
+ return items.map((item) => {
460
+ const level = item.severity === SEVERITY_ERROR ? "ERROR" : "WARN";
461
+ const file = item.file ?? "";
462
+ const { line, character } = item.range.start;
463
+ return `${level} [${file}:${line + 1}:${character + 1}] ${item.message}`;
464
+ }).join("\n");
465
+ }
466
+ function entryToDiagnosticItem(entry, source) {
467
+ return {
468
+ file: entry.file,
469
+ severity: entry.severity === "error" ? SEVERITY_ERROR : SEVERITY_WARN,
470
+ range: {
471
+ start: { line: entry.line - 1, character: entry.column - 1 },
472
+ end: { line: entry.line - 1, character: entry.column - 1 }
473
+ },
474
+ message: entry.message,
475
+ source
476
+ };
477
+ }
478
+ function normalizeEntries(value, source) {
479
+ if (value === void 0) return [];
480
+ if (!Array.isArray(value)) throw new Error("diagnostics \u5FC5\u987B\u662F\u6570\u7EC4");
481
+ return value.map((raw, index) => {
482
+ const at = `diagnostics[${index}]`;
483
+ if (!raw || typeof raw !== "object") throw new Error(`${at} \u5FC5\u987B\u662F\u5BF9\u8C61`);
484
+ const entry = raw;
485
+ if (typeof entry.file !== "string" || !entry.file)
486
+ throw new Error(`${at}.file \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
487
+ if (typeof entry.line !== "number" || entry.line < 1)
488
+ throw new Error(`${at}.line \u5FC5\u987B\u662F \u2265 1 \u7684\u6570\u5B57`);
489
+ if (typeof entry.column !== "number" || entry.column < 1)
490
+ throw new Error(`${at}.column \u5FC5\u987B\u662F \u2265 1 \u7684\u6570\u5B57`);
491
+ if (entry.severity !== "error" && entry.severity !== "warning")
492
+ throw new Error(`${at}.severity \u5FC5\u987B\u662F "error" \u6216 "warning"`);
493
+ if (typeof entry.message !== "string") throw new Error(`${at}.message \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);
494
+ return entryToDiagnosticItem(entry, source);
495
+ });
496
+ }
497
+ function extractJsonValue(raw) {
498
+ const trimmed = raw.trim();
499
+ try {
500
+ return JSON.parse(trimmed);
501
+ } catch {
502
+ const starts = [raw.indexOf("{"), raw.indexOf("[")].filter((index) => index >= 0);
503
+ if (starts.length === 0) throw new Error("\u672A\u627E\u5230 JSON \u8F93\u51FA");
504
+ const start = Math.min(...starts);
505
+ const close = raw[start] === "{" ? "}" : "]";
506
+ const end = raw.lastIndexOf(close);
507
+ if (end <= start) throw new Error("\u672A\u627E\u5230 JSON \u8F93\u51FA");
508
+ return JSON.parse(raw.slice(start, end + 1));
586
509
  }
587
- if (!options.onlyFindings || tscLines) {
588
- parts.push(`## ${tscSectionTitle(tscOutput)}
589
-
590
- ` + (tscLines || "\u6CA1\u6709\u53D1\u73B0\u7C7B\u578B\u9519\u8BEF"));
510
+ }
511
+ function parseEslintJson(raw, cwd) {
512
+ const parsed = extractJsonValue(raw);
513
+ if (!Array.isArray(parsed)) throw new Error("\u9876\u5C42\u5FC5\u987B\u662F\u6570\u7EC4");
514
+ const all = parsed.flatMap(
515
+ (file) => (file.messages ?? []).map((message) => ({
516
+ ...message,
517
+ filePath: file.filePath ? path.resolve(cwd, file.filePath) : ""
518
+ }))
519
+ );
520
+ return {
521
+ messages: all.filter((message) => message.filePath && !isEslintIgnoreNotice(message)),
522
+ ignored: all.filter((message) => message.filePath && isEslintIgnoreNotice(message)).map((m) => m.filePath)
523
+ };
524
+ }
525
+ function isEslintIgnoreNotice(message) {
526
+ return (message.ruleId ?? null) === null && typeof message.message === "string" && message.message.startsWith("File ignored because");
527
+ }
528
+ function filterTscOutputBySeverity(rawOutput, minSeverity) {
529
+ if (minSeverity === "warning" || !rawOutput) return rawOutput;
530
+ const errorLinePat = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:/;
531
+ const kept = [];
532
+ let keep = false;
533
+ for (const line of rawOutput.split("\n")) {
534
+ const match = errorLinePat.exec(line);
535
+ if (match) keep = match[4] === "error";
536
+ else if (!/^\s/.test(line)) keep = false;
537
+ if (keep) kept.push(line);
591
538
  }
592
- if (parts.length === 0) return "";
593
- const body = parts.join("\n\n");
594
- return title ? `${title}
539
+ return kept.join("\n");
540
+ }
541
+ function applyTscSeverity(result, minSeverity) {
542
+ if (minSeverity === "warning") return result;
543
+ return {
544
+ ...result,
545
+ rawOutput: filterTscOutputBySeverity(result.rawOutput, minSeverity),
546
+ diagnostics: (result.diagnostics ?? []).filter((item) => item.severity === SEVERITY_ERROR)
547
+ };
548
+ }
549
+ function emptySectionText(kind, phase, severity) {
550
+ if (phase !== "manual") return void 0;
551
+ if (kind === "typecheck") return "\u6CA1\u6709\u53D1\u73B0\u7C7B\u578B\u9519\u8BEF";
552
+ return severity === "error" ? "\u6CA1\u6709\u53D1\u73B0\u9519\u8BEF" : "\u6CA1\u6709\u53D1\u73B0\u95EE\u9898";
553
+ }
554
+ function buildSection(name, target, outcome, phase, severity, kind) {
555
+ const diagnostics = filterBySeverity(outcome.diagnostics ?? [], severity);
556
+ const explicit = (outcome.text ?? "").trim();
557
+ const body = explicit || (diagnostics.length > 0 ? renderDiagnosticLines(diagnostics) : emptySectionText(kind, phase, severity) ?? "");
558
+ const notes = phase === "manual" ? (outcome.notes ?? []).filter(Boolean) : [];
559
+ const text = [body, ...notes].filter(Boolean).join("\n\n");
560
+ return {
561
+ name,
562
+ ...target ? { target } : {},
563
+ ...text ? { text } : {},
564
+ diagnostics
565
+ };
566
+ }
567
+ function resolveCommandSource(check, cwd) {
568
+ if (check.command) {
569
+ return { command: check.command, prefix: [], label: check.command };
570
+ }
571
+ const binName = check.bin;
572
+ const bin = resolvePackageBin(path.join(cwd, "package.json"), binName, binName);
573
+ if (!bin) {
574
+ return {
575
+ command: "node",
576
+ prefix: [],
577
+ label: binName,
578
+ error: `\u9879\u76EE\u91CC\u89E3\u6790\u4E0D\u5230 ${binName}\uFF08\u8BF7\u5148\u5B89\u88C5\u8BE5\u4F9D\u8D56\uFF0C\u6216\u6539\u7528 command \u6307\u5B9A\u53EF\u6267\u884C\u6587\u4EF6\uFF09`
579
+ };
580
+ }
581
+ return { command: "node", prefix: [bin], label: binName };
582
+ }
583
+ async function runCommand(check, source, argv, cwd) {
584
+ const result = await execa(source.command, [...source.prefix, ...argv], {
585
+ cwd,
586
+ timeout: check.timeoutMs ?? COMMAND_CHECK_TIMEOUT_MS,
587
+ maxBuffer: 10 * 1024 * 1024,
588
+ reject: false,
589
+ stdin: "ignore"
590
+ });
591
+ return {
592
+ stdout: String(result.stdout ?? ""),
593
+ stderr: String(result.stderr ?? ""),
594
+ exitCode: typeof result.exitCode === "number" ? result.exitCode : void 0,
595
+ failed: result.failed,
596
+ timedOut: Boolean(result.timedOut || result.isTerminated),
597
+ overflowed: Boolean(result.isMaxBuffer),
598
+ message: result.originalMessage
599
+ };
600
+ }
601
+ function commandFailureText(check, source, outcome) {
602
+ if (outcome.timedOut) {
603
+ return `[${check.name}] \u8FD0\u884C\u5931\u8D25\uFF1A\u68C0\u67E5\u8D85\u65F6\uFF08${check.timeoutMs ?? COMMAND_CHECK_TIMEOUT_MS}ms\uFF09\uFF0C\u53EF\u63D0\u9AD8 diagnostics.timeoutMs \u6216\u7F29\u5C0F\u68C0\u67E5\u8303\u56F4\u3002`;
604
+ }
605
+ if (outcome.overflowed) return `[${check.name}] \u8FD0\u884C\u5931\u8D25\uFF1A\u8F93\u51FA\u8D85\u8FC7\u4E0A\u9650\uFF0C\u8BF7\u7F29\u5C0F\u68C0\u67E5\u8303\u56F4\u3002`;
606
+ if (outcome.failed && outcome.exitCode === void 0) {
607
+ return `[${check.name}] \u8FD0\u884C\u5931\u8D25\uFF1A\u65E0\u6CD5\u6267\u884C ${source.label}\uFF08${outcome.message ?? "spawn failed"}\uFF09\u3002`;
608
+ }
609
+ return void 0;
610
+ }
611
+ function rawCommandOutput(outcome) {
612
+ return [outcome.stdout, outcome.stderr].map((text) => text.trim()).filter(Boolean).join("\n");
613
+ }
614
+ function expandArgs(args, files) {
615
+ return args.flatMap((arg) => {
616
+ if (arg === "{file}") return files[0] ? [files[0]] : [];
617
+ if (arg === "{files}") return [...files];
618
+ return [
619
+ arg.replace(
620
+ /\{file\}|\{files\}/g,
621
+ (match) => match === "{file}" ? files[0] ?? "" : files.join(" ")
622
+ )
623
+ ];
624
+ });
625
+ }
626
+ async function runAdapterModule(check, outcome, cwd, files) {
627
+ const adapterPath = path.resolve(cwd, check.adapter);
628
+ const fail = (reason) => ({
629
+ text: `[${check.name}] \u9002\u914D\u5668\u4E0D\u53EF\u7528\uFF1A${check.adapter}\uFF08${reason}\uFF09`,
630
+ diagnostics: []
631
+ });
632
+ let moduleExports;
633
+ try {
634
+ moduleExports = await import(pathToFileURL(adapterPath).href);
635
+ } catch (error) {
636
+ return fail(error instanceof Error ? error.message : String(error));
637
+ }
638
+ if (typeof moduleExports.default !== "function") {
639
+ return fail("\u6A21\u5757\u5FC5\u987B default export \u4E00\u4E2A\u9002\u914D\u5668\u51FD\u6570");
640
+ }
641
+ const input = {
642
+ name: check.name,
643
+ stdout: outcome.stdout,
644
+ stderr: outcome.stderr,
645
+ exitCode: outcome.exitCode,
646
+ files: [...files],
647
+ cwd
648
+ };
649
+ let output;
650
+ try {
651
+ output = await moduleExports.default(
652
+ input
653
+ );
654
+ } catch (error) {
655
+ return fail(error instanceof Error ? error.message : String(error));
656
+ }
657
+ if (!output || typeof output !== "object") return fail("\u9002\u914D\u5668\u5FC5\u987B\u8FD4\u56DE\u5BF9\u8C61");
658
+ try {
659
+ const diagnostics = normalizeEntries(output.diagnostics, check.name);
660
+ return { text: diagnostics.length > 0 ? void 0 : output.text, diagnostics };
661
+ } catch (error) {
662
+ return fail(error instanceof Error ? error.message : String(error));
663
+ }
664
+ }
665
+ function parseStylelintJson(raw, cwd) {
666
+ const parsed = extractJsonValue(raw);
667
+ if (!Array.isArray(parsed)) throw new Error("\u9876\u5C42\u5FC5\u987B\u662F\u6570\u7EC4");
668
+ return parsed.flatMap((file) => {
669
+ const filePath = file.source ? path.resolve(cwd, file.source) : "";
670
+ if (!filePath) return [];
671
+ return (file.warnings ?? []).map((warning) => ({
672
+ severity: warning.severity === "error" ? 2 : 1,
673
+ line: warning.line ?? 1,
674
+ column: warning.column ?? 1,
675
+ endLine: warning.endLine,
676
+ endColumn: warning.endColumn,
677
+ message: warning.text ?? "\u672A\u77E5\u8BCA\u65AD",
678
+ ruleId: warning.rule ?? null,
679
+ filePath
680
+ }));
681
+ });
682
+ }
683
+ function adaptBuiltinFormat(format, check, raw, cwd, severity) {
684
+ const lintFromMessages = (messages) => {
685
+ const output = formatLintMessages(
686
+ messages,
687
+ { label: check.name, source: check.name },
688
+ 10,
689
+ severity
690
+ );
691
+ return { text: output.text, diagnostics: output.diagnostics ?? [] };
692
+ };
693
+ switch (format) {
694
+ case "tsc":
695
+ return {
696
+ text: filterTscOutputBySeverity(raw, severity),
697
+ diagnostics: parseTscDiags(raw, void 0, cwd, check.name)
698
+ };
699
+ case "eslint-json": {
700
+ const { messages, ignored } = parseEslintJson(raw, cwd);
701
+ return {
702
+ ...lintFromMessages(messages),
703
+ notes: ignored.map((file) => `${file} \u4E0D\u5728 ESLint \u914D\u7F6E\u8303\u56F4\u5185\uFF0C\u672A\u68C0\u67E5`)
704
+ };
705
+ }
706
+ case "oxlint-json":
707
+ return lintFromMessages(parseOxlintOutput(raw, cwd));
708
+ case "stylelint-json":
709
+ return lintFromMessages(parseStylelintJson(raw, cwd));
710
+ case "aipanel-json": {
711
+ const value = extractJsonValue(raw);
712
+ const payload = Array.isArray(value) ? { diagnostics: value } : value;
713
+ const diagnostics = normalizeEntries(payload?.diagnostics, check.name);
714
+ return { text: diagnostics.length > 0 ? void 0 : payload?.text, diagnostics };
715
+ }
716
+ case "text":
717
+ default:
718
+ return { text: raw, diagnostics: [] };
719
+ }
720
+ }
721
+ function expandLinterPreset(check) {
722
+ const spec = BUILTIN_LINTERS[check.builtin];
723
+ return {
724
+ name: spec.label,
725
+ bin: spec.bin ?? spec.package,
726
+ args: check.args ?? [...spec.args],
727
+ ...check.projectArgs ?? spec.projectArgs ? { projectArgs: [...check.projectArgs ?? spec.projectArgs ?? []] } : {},
728
+ extensions: check.extensions ?? [...spec.extensions],
729
+ format: check.format ?? spec.format,
730
+ ...check.run ? { run: check.run } : {},
731
+ ...check.cwd ? { cwd: check.cwd } : {},
732
+ ...check.timeoutMs ? { timeoutMs: check.timeoutMs } : {}
733
+ };
734
+ }
735
+ async function runCommandCheck(check, target, phase, severity, optional = false) {
736
+ const cwd = check.cwd ? path.resolve(target.cwd, check.cwd) : target.cwd;
737
+ const args = check.args ?? [];
738
+ const hasPlaceholder = args.some((arg) => arg.includes("{file}") || arg.includes("{files}"));
739
+ const perFile = args.some((arg) => arg.includes("{file}"));
740
+ const split = splitsByFile(target);
741
+ const targeted = target.kind !== "project";
742
+ const files = targeted ? targetFiles(target).filter((file) => matchesExtensions(file, check.extensions)) : [];
743
+ if (targeted && hasPlaceholder && files.length === 0) {
744
+ log.debug("skip command check: no matching file target", { name: check.name, phase });
745
+ return [];
746
+ }
747
+ const source = resolveCommandSource(check, cwd);
748
+ if (source.error) {
749
+ if (optional && phase === "edit") {
750
+ log.debug("skip uninstalled builtin linter", { name: check.name });
751
+ return [];
752
+ }
753
+ const text = optional ? `[${check.name}] \u672A\u8FD0\u884C\uFF1A${source.error}` : `[${check.name}] ${source.error}`;
754
+ return [buildSection(check.name, void 0, { text }, phase, severity, "command")];
755
+ }
756
+ const execute = async (argvTemplate, fileSet) => {
757
+ const outcome = await runCommand(check, source, expandArgs(argvTemplate, fileSet), cwd);
758
+ const failure = commandFailureText(check, source, outcome);
759
+ if (failure) return { text: failure, diagnostics: [] };
760
+ const raw = rawCommandOutput(outcome);
761
+ try {
762
+ if (check.adapter) return await runAdapterModule(check, outcome, cwd, fileSet);
763
+ return adaptBuiltinFormat(check.format ?? "text", check, raw, cwd, severity);
764
+ } catch (error) {
765
+ const reason = error instanceof Error ? error.message : String(error);
766
+ const excerpt = raw.replace(/\s+/g, " ").trim().slice(0, 200);
767
+ return {
768
+ text: `[${check.name}] \u8FD0\u884C\u5931\u8D25\uFF1A\u8F93\u51FA\u89E3\u6790\u5931\u8D25\uFF08${reason}\uFF09${excerpt ? `\uFF1A${excerpt}` : ""}`,
769
+ diagnostics: []
770
+ };
771
+ }
772
+ };
773
+ const targetLabel = (file) => split ? displayPath(target.cwd, file) : void 0;
774
+ if (!hasPlaceholder) {
775
+ return [
776
+ buildSection(check.name, void 0, await execute(args, []), phase, severity, "command")
777
+ ];
778
+ }
779
+ if (target.kind === "project") {
780
+ if (!check.projectArgs) {
781
+ log.debug("skip command check: no project args", { name: check.name });
782
+ return [];
783
+ }
784
+ return [
785
+ buildSection(
786
+ check.name,
787
+ void 0,
788
+ await execute(check.projectArgs, []),
789
+ phase,
790
+ severity,
791
+ "command"
792
+ )
793
+ ];
794
+ }
795
+ if (perFile) {
796
+ const sections = [];
797
+ for (const file of files) {
798
+ const produced2 = await execute(args, [file]);
799
+ sections.push(
800
+ buildSection(check.name, targetLabel(file), produced2, phase, severity, "command")
801
+ );
802
+ }
803
+ return sections;
804
+ }
805
+ const produced = await execute(args, files);
806
+ const label = files.length === 1 ? targetLabel(files[0]) : void 0;
807
+ return [buildSection(check.name, label, produced, phase, severity, "command")];
808
+ }
809
+ async function runProjectTypeCheck(workspace, severity) {
810
+ const dirs = fs.existsSync(path.join(workspace, "tsconfig.json")) ? [workspace] : findAllTsconfigDirs(workspace);
811
+ log.debug("Tsc dirs to check", { count: dirs.length, dirs });
812
+ const results = await Promise.all(dirs.map((dir) => runTypeCheck(void 0, dir)));
813
+ return applyTscSeverity(
814
+ {
815
+ rawOutput: results.flatMap((output) => output.rawOutput).filter(Boolean).join("\n"),
816
+ exitCode: results.reduce((max, output) => Math.max(max, output.exitCode), 0),
817
+ diagnostics: results.flatMap((output) => output.diagnostics ?? []),
818
+ source: results.find((output) => output.source)?.source
819
+ },
820
+ severity
821
+ );
822
+ }
823
+ async function runTypecheckCheck(check, target, phase, severity) {
824
+ const cwd = target.cwd;
825
+ const split = splitsByFile(target);
826
+ const files = target.kind === "project" ? [] : targetFiles(target).filter(
827
+ (file) => matchesExtensions(file, check.extensions ?? SOURCE_EXTENSIONS)
828
+ );
829
+ if (target.kind !== "project" && files.length === 0) {
830
+ log.debug("skip builtin check: no matching file target", { builtin: check.builtin, phase });
831
+ return [];
832
+ }
833
+ if (split) {
834
+ const results = await runTypeChecksForFiles(files, cwd);
835
+ return files.map((file) => {
836
+ const result2 = applyTscSeverity(
837
+ results.get(path.resolve(file)) ?? { rawOutput: "", exitCode: 0 },
838
+ severity
839
+ );
840
+ return buildSection(
841
+ tscSectionTitle(result2),
842
+ displayPath(cwd, file),
843
+ { text: result2.rawOutput.trim(), diagnostics: result2.diagnostics },
844
+ phase,
845
+ severity,
846
+ "typecheck"
847
+ );
848
+ });
849
+ }
850
+ const result = target.kind === "file" ? applyTscSeverity(await runTypeCheck(files[0], cwd), severity) : await runProjectTypeCheck(cwd, severity);
851
+ return [
852
+ buildSection(
853
+ tscSectionTitle(result),
854
+ void 0,
855
+ { text: result.rawOutput.trim(), diagnostics: result.diagnostics },
856
+ phase,
857
+ severity,
858
+ "typecheck"
859
+ )
860
+ ];
861
+ }
862
+ async function runDiagnostics(target, policy, phase) {
863
+ const checks = policy.checks.filter((check) => checkRunsInPhase(check, phase));
864
+ log.debug("runDiagnostics", { phase, target: target.kind, checks: checks.length });
865
+ const results = await Promise.all(
866
+ checks.map((check) => {
867
+ if (isTypecheckCheck(check)) {
868
+ return runTypecheckCheck(check, target, phase, policy.severity);
869
+ }
870
+ if (isLinterPreset(check)) {
871
+ return runCommandCheck(expandLinterPreset(check), target, phase, policy.severity, true);
872
+ }
873
+ if (isCommandCheck(check)) {
874
+ return runCommandCheck(check, target, phase, policy.severity);
875
+ }
876
+ return Promise.resolve([]);
877
+ })
878
+ );
879
+ const sections = results.flat().filter((section) => section.text !== void 0 || section.diagnostics.length > 0);
880
+ if (sections.length === 0 && phase === "manual") {
881
+ return {
882
+ sections: [
883
+ {
884
+ name: "\u68C0\u67E5",
885
+ text: "\u6CA1\u6709\u53EF\u8FD0\u884C\u7684\u68C0\u67E5\uFF1A\u5DF2\u914D\u7F6E\u7684\u68C0\u67E5\u90FD\u4E0D\u5339\u914D\u672C\u8F6E\u76EE\u6807\uFF08\u68C0\u67E5\u7684 extensions / run \u9636\u6BB5 / \u76EE\u6807\u7C7B\u578B\uFF09\u3002",
886
+ diagnostics: []
887
+ }
888
+ ]
889
+ };
890
+ }
891
+ return { sections };
892
+ }
893
+ function collectDiagnostics(result) {
894
+ return result.sections.flatMap((section) => section.diagnostics);
895
+ }
896
+ function renderDiagnostics(result, options = {}) {
897
+ const sections = options.onlyFindings ? result.sections.filter((section) => (section.text ?? "").trim()) : result.sections;
898
+ if (sections.length === 0) return "";
899
+ const groups = /* @__PURE__ */ new Map();
900
+ for (const section of sections) {
901
+ const key = section.target ?? "";
902
+ const group = groups.get(key);
903
+ if (group) group.push(section);
904
+ else groups.set(key, [section]);
905
+ }
906
+ const blocks = [];
907
+ for (const [key, group] of groups) {
908
+ const body = group.map((section) => {
909
+ const text = boundFindings(section.text, options.maxFindingsPerSection);
910
+ return `## ${section.name}
595
911
 
596
- ${body}` : body;
912
+ ${text || "\u6CA1\u6709\u53D1\u73B0\u95EE\u9898"}`;
913
+ }).join("\n\n");
914
+ blocks.push(key ? `### ${key}
915
+
916
+ ${body}` : body);
917
+ }
918
+ return blocks.join("\n\n");
597
919
  }
598
920
  export {
599
921
  DIAGNOSTICS_TOOL_DESCRIPTION,
922
+ collectDiagnostics,
600
923
  findAllTsconfigDirs,
601
924
  findTsconfigDir,
602
- formatDiagnosticsSections,
603
925
  isJsFile,
604
- lintFiles,
605
- lintSectionTitle,
606
926
  omittedFindingsHint,
607
- runAllChecks,
608
- runAllChecksForFiles,
609
- runProjectDiagnostics,
927
+ renderDiagnostics,
928
+ runDiagnostics,
610
929
  runTypeCheck,
611
930
  runTypeChecksForFiles,
612
931
  tscSectionTitle