From 6cbfb406605c96363083067a4a5db49838e2dac2 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:08:37 -0800 Subject: [PATCH 1/2] Export flattenDiagnosticMessage from the API Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 2 +- .../typescript/src/api/diagnosticFormatter.ts | 3 ++- packages/typescript/src/api/sync/api.ts | 2 +- .../test/diagnosticFormatter.test.ts | 20 +++++++++++++++++++ 4 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 7256e47c0da36..0f4bb4d701aef 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -192,7 +192,7 @@ import type { UnionType, } from "./types.ts"; -export { formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; +export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind }; export type { diff --git a/packages/typescript/src/api/diagnosticFormatter.ts b/packages/typescript/src/api/diagnosticFormatter.ts index ed5129bb215d0..2f8b93722d964 100644 --- a/packages/typescript/src/api/diagnosticFormatter.ts +++ b/packages/typescript/src/api/diagnosticFormatter.ts @@ -59,7 +59,8 @@ function diagnosticPrefix(diagnostic: Diagnostic): string { return diagnostic.source || "TS"; } -function flattenDiagnosticMessage(diagnostic: Diagnostic, newLine: string, indentLevel = 0): string { +/** Flattens a diagnostic and its message chain, indenting each nested message by two spaces. */ +export function flattenDiagnosticMessage(diagnostic: Diagnostic, newLine: string, indentLevel = 0): string { let result = ""; if (indentLevel) { result += newLine + " ".repeat(indentLevel); diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5534ffd53e1df..f0707ec146b99 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -210,7 +210,7 @@ import type { UnionType, } from "./types.ts"; -export { formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; +export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind }; export type { diff --git a/packages/typescript/test/diagnosticFormatter.test.ts b/packages/typescript/test/diagnosticFormatter.test.ts index e20b5acbb371c..5ced7c11688ec 100644 --- a/packages/typescript/test/diagnosticFormatter.test.ts +++ b/packages/typescript/test/diagnosticFormatter.test.ts @@ -1,9 +1,12 @@ import { API, + type Diagnostic, + flattenDiagnosticMessage, formatDiagnostics, type FormatDiagnosticsHost, formatDiagnosticsWithColorAndContext, } from "@typescript/typescript/async"; +import { flattenDiagnosticMessage as flattenDiagnosticMessageSync } from "@typescript/typescript/sync"; import assert from "node:assert"; import { describe, @@ -15,6 +18,23 @@ import { } from "./testUtils.ts"; describe("diagnosticFormatter", { concurrency: areTestsFiltered() }, () => { + test("flattens diagnostic message chains with configurable newlines and indentation", () => { + const diagnostic: Diagnostic = { + pos: -1, + end: -1, + code: 1, + category: 1, + text: "Root", + }; + const child = { ...diagnostic, text: "Child", messageChain: [{ ...diagnostic, text: "Grandchild" }] }; + const chained = { ...diagnostic, messageChain: [child, { ...diagnostic, text: "Sibling" }] }; + for (const flatten of [flattenDiagnosticMessage, flattenDiagnosticMessageSync]) { + assert.equal(flatten(diagnostic, "\n"), "Root"); + assert.equal(flatten(chained, "\r\n"), "Root\r\n Child\r\n Grandchild\r\n Sibling"); + assert.equal(flatten(chained, "\n", 1), "\n Root\n Child\n Grandchild\n Sibling"); + } + }); + test("formats diagnostics with a configured program host", async () => { const source = `const x: number = "oops";\n`; const api = spawnAPI({ From 9f71fbe7ad38b66e1de3234b1ff7a1e445fb9fba Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:35:47 -0800 Subject: [PATCH 2/2] Add public diagnostic sorting and deduplication Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 1 + .../typescript/src/api/diagnosticUtils.ts | 50 +++++++++++++ packages/typescript/src/api/sync/api.ts | 1 + .../test/diagnosticFormatter.test.ts | 71 ++++++++++++++++++- 4 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 packages/typescript/src/api/diagnosticUtils.ts diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 0f4bb4d701aef..8f0fbe0c9fffd 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -193,6 +193,7 @@ import type { } from "./types.ts"; export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; +export { sortAndDeduplicateDiagnostics } from "../diagnosticUtils.ts"; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind }; export type { diff --git a/packages/typescript/src/api/diagnosticUtils.ts b/packages/typescript/src/api/diagnosticUtils.ts new file mode 100644 index 0000000000000..c73b96436d908 --- /dev/null +++ b/packages/typescript/src/api/diagnosticUtils.ts @@ -0,0 +1,50 @@ +import type { Diagnostic } from "./proto.ts"; + +/** + * Returns a sorted copy, removing diagnostics with identical file names, ranges, + * codes, categories, sources, text, message chains, and related information. + * File names and localized text are compared case-sensitively. More elaborated + * message chains and related information sort first; distinct details are retained. + */ +export function sortAndDeduplicateDiagnostics(diagnostics: readonly T[]): T[] { + const sorted = diagnostics.slice().sort(compareDiagnostics); + return sorted.filter((diagnostic, index) => index === 0 || compareDiagnostics(sorted[index - 1], diagnostic) !== 0); +} + +function compareValues(a: string | number, b: string | number): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function compareDiagnostics(a: Diagnostic, b: Diagnostic): number { + if (a === b) return 0; + return compareValues(a.fileName ?? "", b.fileName ?? "") || + a.pos - b.pos || + a.end - b.end || + a.code - b.code || + a.category - b.category || + compareValues(a.source ?? "", b.source ?? "") || + compareValues(a.text, b.text) || + compareMessageChainSize(a.messageChain ?? [], b.messageChain ?? []) || + compareDiagnosticLists(a.messageChain ?? [], b.messageChain ?? []) || + compareDiagnosticLists(a.relatedInformation ?? [], b.relatedInformation ?? []); +} + +function compareMessageChainSize(a: readonly Diagnostic[], b: readonly Diagnostic[]): number { + const result = b.length - a.length; + if (result) return result; + for (let i = 0; i < a.length; i++) { + const result = compareMessageChainSize(a[i].messageChain ?? [], b[i].messageChain ?? []); + if (result) return result; + } + return 0; +} + +function compareDiagnosticLists(a: readonly Diagnostic[], b: readonly Diagnostic[]): number { + const result = b.length - a.length; + if (result) return result; + for (let i = 0; i < a.length; i++) { + const result = compareDiagnostics(a[i], b[i]); + if (result) return result; + } + return 0; +} diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index f0707ec146b99..b634a29d2c9d5 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -211,6 +211,7 @@ import type { } from "./types.ts"; export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts"; +export { sortAndDeduplicateDiagnostics } from "../diagnosticUtils.ts"; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind }; export type { diff --git a/packages/typescript/test/diagnosticFormatter.test.ts b/packages/typescript/test/diagnosticFormatter.test.ts index 5ced7c11688ec..e5e884ba1e754 100644 --- a/packages/typescript/test/diagnosticFormatter.test.ts +++ b/packages/typescript/test/diagnosticFormatter.test.ts @@ -5,18 +5,87 @@ import { formatDiagnostics, type FormatDiagnosticsHost, formatDiagnosticsWithColorAndContext, + sortAndDeduplicateDiagnostics, } from "@typescript/typescript/async"; -import { flattenDiagnosticMessage as flattenDiagnosticMessageSync } from "@typescript/typescript/sync"; +import { + flattenDiagnosticMessage as flattenDiagnosticMessageSync, + sortAndDeduplicateDiagnostics as sortAndDeduplicateDiagnosticsSync, +} from "@typescript/typescript/sync"; import assert from "node:assert"; import { describe, test, } from "node:test"; +import { toRootedFilePath } from "../src/api/path.ts"; import { areTestsFiltered, createVirtualFileSystem, } from "./testUtils.ts"; +describe("sortAndDeduplicateDiagnostics", () => { + const diagnostic: Diagnostic = { pos: -1, end: -1, code: 1, category: 1, text: "Error" }; + + test("sorts by file, location, code, category, source, and text without mutating input", () => { + const firstFile = { ...diagnostic, fileName: toRootedFilePath("/A.ts", undefined), pos: 0, end: 1 }; + const expected = [ + diagnostic, + firstFile, + { ...firstFile, text: "Other error" }, + { ...firstFile, source: "plugin" }, + { ...firstFile, category: 2 }, + { ...firstFile, code: 2 }, + { ...firstFile, end: 2 }, + { ...firstFile, pos: 1, end: 2 }, + { ...firstFile, fileName: toRootedFilePath("/a.ts", undefined) }, + ].map((item, index) => ({ ...item, index })); + const input = Object.freeze([...expected].reverse()); + for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) { + const result = sort(input); + assert.deepEqual(result.map(item => item.index), expected.map(item => item.index)); + assert.ok(result.every((item, index) => item === expected[index])); + assert.deepEqual(input, [...expected].reverse()); + assert.deepEqual(sort([]), []); + assert.deepEqual(sort([diagnostic, structuredClone(diagnostic)]), [diagnostic]); + } + }); + + test("orders message chains by shape before content without dropping distinct chains", () => { + const child = { ...diagnostic, text: "Child" }; + const shallow = { ...diagnostic, messageChain: [child] }; + const deep = { ...diagnostic, messageChain: [{ ...child, text: "Z", messageChain: [child] }] }; + const wide = { ...diagnostic, messageChain: [child, child] }; + for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) { + assert.deepEqual(sort([diagnostic, shallow, deep]), [deep, shallow, diagnostic]); + assert.deepEqual(sort([deep, wide]), [wide, deep]); + const earlierText = { ...shallow, messageChain: [{ ...child, text: "A" }] }; + assert.deepEqual(sort([shallow, earlierText]), [earlierText, shallow]); + const deeperSecondChild = { + ...wide, + messageChain: [child, { ...child, messageChain: [child] }], + }; + assert.deepEqual(sort([wide, deeperSecondChild]), [deeperSecondChild, wide]); + assert.deepEqual(sort([deep, structuredClone(deep)]), [deep]); + assert.deepEqual(sort([diagnostic, { ...diagnostic, messageChain: [] }]), [diagnostic]); + const differentCode = { ...shallow, messageChain: [{ ...child, code: 2 }] }; + assert.equal(sort([shallow, differentCode]).length, 2); + } + }); + + test("orders related information without dropping distinct details and stably deduplicates", () => { + const related = { ...diagnostic, text: "Related" }; + const detailed = { ...diagnostic, relatedInformation: [related] }; + const moreDetailed = { ...diagnostic, relatedInformation: [related, related] }; + const earlierRelated = { ...detailed, relatedInformation: [{ ...related, text: "Earlier" }] }; + for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) { + assert.deepEqual(sort([diagnostic, detailed, moreDetailed]), [moreDetailed, detailed, diagnostic]); + assert.deepEqual(sort([detailed, earlierRelated]), [earlierRelated, detailed]); + const duplicate = structuredClone(detailed); + assert.equal(sort([detailed, duplicate])[0], detailed); + assert.equal(sort([duplicate, detailed])[0], duplicate); + } + }); +}); + describe("diagnosticFormatter", { concurrency: areTestsFiltered() }, () => { test("flattens diagnostic message chains with configurable newlines and indentation", () => { const diagnostic: Diagnostic = {