Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(mcp-host): read chart data as written and label it legibly
marcotebbe0d37573aed
diff --git a/mcp-host/src/workflow/__tests__/chartData.test.ts b/mcp-host/src/workflow/__tests__/chartData.test.tsnew file mode 100644index 000000000..17f120be9--- /dev/null+++ b/mcp-host/src/workflow/__tests__/chartData.test.ts@@ -0,0 +1,474 @@+/**+ * What chart data gets repaired (with a warning) and what gets rejected (with a+ * message naming the field).+ */+import { describe, expect, it } from 'vitest'+import { ChartDataError, coerceNumber, normalizeChartData } from '../chartData'++const bar = { chartType: 'bar' as const }++function expectRejected(fn: () => unknown): string {+ try {+ fn()+ } catch (err) {+ expect(err).toBeInstanceOf(ChartDataError)+ return (err as Error).message+ }+ throw new Error('expected the input to be rejected')+}++describe('coerceNumber', () => {+ it('reads the numeric forms models write', () => {+ expect(coerceNumber(42)).toBe(42)+ expect(coerceNumber('120')).toBe(120)+ expect(coerceNumber('1,234.5')).toBe(1234.5)+ expect(coerceNumber('$1,200')).toBe(1200)+ expect(coerceNumber('45%')).toBe(45)+ expect(coerceNumber('-17.5')).toBe(-17.5)+ expect(coerceNumber('1.2K')).toBe(1200)+ expect(coerceNumber('3M')).toBe(3_000_000)+ })++ it('reads accounting parentheses, a plus sign and the scale words as written', () => {+ expect(coerceNumber('(1,200)')).toBe(-1200)+ expect(coerceNumber('($45.5)')).toBe(-45.5)+ expect(coerceNumber('+12')).toBe(12)+ expect(coerceNumber('\u221212.5')).toBe(-12.5)+ expect(coerceNumber('2.5bn')).toBe(2_500_000_000)+ expect(coerceNumber('4mn')).toBe(4_000_000)+ expect(coerceNumber('987,65')).toBe(987.65)+ expect(coerceNumber('1.234,50')).toBe(1234.5)+ expect(coerceNumber("1'234.50")).toBe(1234.5)+ })++ it('reads no number out of units, a lowercase m or a locale-dependent grouping', () => {+ expect(coerceNumber('100 MB')).toBeUndefined()+ expect(coerceNumber('12 kg')).toBeUndefined()+ expect(coerceNumber('5m')).toBeUndefined()+ expect(coerceNumber('1.200')).toBeUndefined()+ expect(coerceNumber('~5')).toBeUndefined()+ })++ it('refuses text with no number rather than defaulting to zero', () => {+ expect(coerceNumber('none')).toBeUndefined()+ expect(coerceNumber('')).toBeUndefined()+ expect(coerceNumber(null)).toBeUndefined()+ expect(coerceNumber(NaN)).toBeUndefined()+ expect(coerceNumber(Infinity)).toBeUndefined()+ })+})++describe('normalizeChartData — repairs', () => {+ it('reads values written as strings and says it did', () => {+ const r = normalizeChartData(+ { labels: ['a', 'b'], datasets: [{ label: 'x', data: ['120', '190'] }] },+ bar+ )+ expect(r.datasets[0].data).toEqual([120, 190])+ expect(r.warnings.join(' ')).toContain('written as text')+ })++ it('reads comma decimals when the series writes them unambiguously, and lists what it read', () => {+ const r = normalizeChartData(+ { labels: ['A', 'B', 'C'], datasets: [{ data: ['1.234,50', '987,65', '1.200'] }] },+ bar+ )+ expect(r.datasets[0].data).toEqual([1234.5, 987.65, 1200])+ const note = r.warnings.join(' ')+ expect(note).toContain("'987,65' as 987.65")+ expect(note).toContain("'1.200' as 1200")+ })++ it('reads dot decimals when the series writes them unambiguously', () => {+ const r = normalizeChartData(+ { labels: ['A', 'B'], datasets: [{ data: ['1,234.50', '1.200'] }] },+ bar+ )+ expect(r.datasets[0].data).toEqual([1234.5, 1.2])+ })++ it('reads accounting parentheses as negative', () => {+ const r = normalizeChartData(+ { labels: ['A', 'B'], datasets: [{ data: ['(1,200)', '500'] }] },+ bar+ )+ expect(r.datasets[0].data).toEqual([-1200, 500])+ })++ it('uses a numeric x as the category on a line chart and says so', () => {+ const r = normalizeChartData(+ {+ datasets: [+ {+ data: [+ { x: 10, y: 2 },+ { x: 20, y: 3 },+ ],+ },+ ],+ },+ { chartType: 'line' }+ )+ expect(r.labels).toEqual(['10', '20'])+ expect(r.datasets[0].data).toEqual([2, 3])+ const note = r.warnings.join(' ')+ expect(note).toContain('{x, y}')+ expect(note).not.toContain('{label, value}')+ expect(note).not.toContain('numbered')+ })++ it('reads [x, y] pairs on a scatter and [label, value] pairs on a category chart', () => {+ const scatter = normalizeChartData(+ {+ datasets: [+ {+ data: [+ [1, 2],+ [2, 3],+ ],+ },+ ],+ },+ { chartType: 'scatter' }+ )+ expect(scatter.datasets[0].data).toEqual([+ { x: 1, y: 2 },+ { x: 2, y: 3 },+ ])+ const bars = normalizeChartData(+ {+ datasets: [+ {+ data: [+ ['Jan', 5],+ ['Feb', 7],+ ],+ },+ ],+ },+ bar+ )+ expect(bars.labels).toEqual(['Jan', 'Feb'])+ expect(bars.datasets[0].data).toEqual([5, 7])+ })++ it('does not note missing labels for a gauge, which draws none', () => {+ const r = normalizeChartData({ datasets: [{ data: [72] }] }, { chartType: 'gauge' })+ expect(r.warnings.join(' ')).not.toContain('labels')+ })++ it('reads {label, value} records and adopts their labels', () => {+ const r = normalizeChartData(+ {+ datasets: [+ {+ label: 'Spend',+ data: [+ { label: 'Compute', value: 268 },+ { label: 'Storage', value: 120 },+ ],+ },+ ],+ },+ bar+ )+ expect(r.datasets[0].data).toEqual([268, 120])+ expect(r.labels).toEqual(['Compute', 'Storage'])+ })++ it('accepts the {name, count} synonyms', () => {+ const r = normalizeChartData(+ {+ datasets: [+ {+ data: [+ { name: 'A', count: 3 },+ { name: 'B', count: 5 },+ ],+ },+ ],+ },+ bar+ )+ expect(r.datasets[0].data).toEqual([3, 5])+ expect(r.labels).toEqual(['A', 'B'])+ })++ it('numbers the positions when labels are missing on a category chart', () => {+ const r = normalizeChartData({ datasets: [{ data: [1, 2, 3] }] }, bar)+ expect(r.labels).toEqual(['1', '2', '3'])+ expect(r.warnings.join(' ')).toContain('labels')+ })++ it('reconciles a label count that disagrees with the values', () => {+ const r = normalizeChartData(+ { labels: ['Jan', 'Feb'], datasets: [{ data: [1, 2, 3, 4, 5] }] },+ { chartType: 'line' }+ )+ expect(r.labels).toHaveLength(5)+ expect(r.warnings.join(' ')).toContain('the missing labels were numbered 3..5')+ expect(r.warnings.join(' ')).toContain('one label per value')+ })++ it('says labels past the last value were left out', () => {+ const r = normalizeChartData({ labels: ['a', 'b', 'c'], datasets: [{ data: [1] }] }, bar)+ expect(r.labels).toEqual(['a'])+ expect(r.warnings.join(' ')).toContain('the labels past 1 were left out')+ })++ it('keeps nulls as gaps rather than plotting them as zero', () => {+ const r = normalizeChartData(+ { labels: ['a', 'b', 'c'], datasets: [{ data: [1, null, 3] }] },+ { chartType: 'line' }+ )+ expect(r.datasets[0].data).toEqual([1, null, 3])+ })++ it('warns when every value is zero, because the plot will look empty', () => {+ const r = normalizeChartData({ labels: ['a', 'b'], datasets: [{ data: [0, 0] }] }, bar)+ expect(r.warnings.join(' ')).toContain('empty plot')+ })++ it('turns plain numbers into coordinates for a scatter and says so', () => {+ const r = normalizeChartData({ datasets: [{ data: [5, 9, 3] }] }, { chartType: 'scatter' })+ expect(r.datasets[0].data).toEqual([+ { x: 0, y: 5 },+ { x: 1, y: 9 },+ { x: 2, y: 3 },+ ])+ expect(r.warnings.join(' ')).toContain('index')+ })++ it('gives a bubble point a default radius when none was sent', () => {+ const r = normalizeChartData(+ { datasets: [{ data: [{ x: 1, y: 2 }] }] },+ { chartType: 'bubble' }+ )+ expect(r.datasets[0].data[0]).toMatchObject({ x: 1, y: 2 })+ expect((r.datasets[0].data[0] as { r: number }).r).toBeGreaterThan(0)+ })++ it('notes that a single-series type drops the extra datasets', () => {+ const r = normalizeChartData(+ { labels: ['a'], datasets: [{ data: [1] }, { data: [2] }] },+ { chartType: 'funnel' }+ )+ expect(r.warnings.join(' ')).toContain('single series')+ })++ it('carries explicit colors through untouched', () => {+ const r = normalizeChartData(+ { labels: ['a'], datasets: [{ data: [1], backgroundColor: '#ff0000', fill: true }] },+ bar+ )+ expect(r.datasets[0].backgroundColor).toBe('#ff0000')+ expect(r.datasets[0].fill).toBe(true)+ })++ it('says a pie cannot show values below zero, and a bar chart says nothing', () => {+ const data = { labels: ['Loss', 'North', 'South'], datasets: [{ data: [-10, 20, -3] }] }+ const pie = normalizeChartData(data, { chartType: 'pie' })+ expect(pie.datasets[0].data).toEqual([-10, 20, -3])+ expect(pie.warnings.join(' ')).toContain(+ '`data.datasets[0]` has 2 value(s) below zero, which a pie cannot show'+ )+ expect(normalizeChartData(data, bar).warnings.join(' ')).not.toContain('below zero')+ })+})++describe('normalizeChartData — rejections', () => {+ it('rejects a missing data argument', () => {+ expect(expectRejected(() => normalizeChartData(undefined, bar))).toContain('`data` is required')+ })++ it('rejects datasets that are absent or empty', () => {+ expect(expectRejected(() => normalizeChartData({}, bar))).toContain('datasets')+ expect(expectRejected(() => normalizeChartData({ datasets: [] }, bar))).toContain('empty')+ })++ it('rejects an empty series instead of drawing a blank plot', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: [], datasets: [{ data: [] }] }, bar)+ )+ expect(msg).toContain('data.datasets[0].data')+ expect(msg).toContain('empty')+ })++ it('rejects objects with no numeric value and names the fix', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ datasets: [{ data: [{ label: 'a', amountish: 3 }] }] }, bar)+ )+ expect(msg).toContain('data.datasets[0].data[0]')+ expect(msg).toContain('value')+ })++ it('rejects text that holds no number', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: ['a'], datasets: [{ data: ['none'] }] }, bar)+ )+ expect(msg).toContain('holds no number')+ })++ it('rejects a value with a unit and names the unit', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: ['a', 'b'], datasets: [{ data: ['100 MB', 5] }] }, bar)+ )+ expect(msg).toContain('data.datasets[0].data[0]')+ expect(msg).toContain("'MB'")+ })++ it('rejects a lowercase m instead of reading it as million', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: ['a'], datasets: [{ data: ['5m'] }] }, bar)+ )+ expect(msg).toContain("'5m'")+ expect(msg).toContain('5M')+ })++ it('rejects a grouping that reads two ways when nothing else settles it', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: ['a'], datasets: [{ data: ['1.200'] }] }, bar)+ )+ expect(msg).toContain('1.2 or 1200')+ expect(msg).toContain('JSON numbers')+ })++ it('rejects a series that mixes dot and comma decimals', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ labels: ['a', 'b'], datasets: [{ data: ['1,234.50', '987,65'] }] }, bar)+ )+ expect(msg).toContain('JSON numbers')+ })++ it('rejects NaN and Infinity', () => {+ expect(+ expectRejected(() => normalizeChartData({ datasets: [{ data: [NaN] }] }, bar))+ ).toContain('finite')+ expect(+ expectRejected(() => normalizeChartData({ datasets: [{ data: [Infinity] }] }, bar))+ ).toContain('finite')+ })++ it('rejects a series that is entirely null', () => {+ expect(+ expectRejected(() => normalizeChartData({ datasets: [{ data: [null, null] }] }, bar))+ ).toContain('no usable value')+ })++ it('requires labels for a slice chart, which is unreadable without them', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ datasets: [{ data: [1, 2, 3] }] }, { chartType: 'pie' })+ )+ expect(msg).toContain('labels')+ })++ it('rejects a scatter point missing a coordinate', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ datasets: [{ data: [{ x: 1 }] }] }, { chartType: 'scatter' })+ )+ expect(msg).toContain('`x` and `y`')+ })++ it('names the point shape when a scatter point is neither a pair nor an object', () => {+ const msg = expectRejected(() =>+ normalizeChartData({ datasets: [{ data: [true] }] }, { chartType: 'scatter' })+ )+ expect(msg).toContain('{x, y}')+ })++ it('rejects a data field that is not an array', () => {+ expect(expectRejected(() => normalizeChartData({ datasets: [{ data: 42 }] }, bar))).toContain(+ 'must be an array'+ )+ })+})++describe('normalizeChartData — field paths', () => {+ it('names the fields where the caller keeps the chart', () => {+ const opts = { chartType: 'pie', path: 'data.charts[2]' }+ expect(expectRejected(() => normalizeChartData({ datasets: [{ data: [1] }] }, opts))).toContain(+ '`data.charts[2].labels`'+ )+ expect(expectRejected(() => normalizeChartData({ datasets: [] }, opts))).toContain(+ '`data.charts[2].datasets`'+ )+ const { warnings } = normalizeChartData(+ { labels: ['a', 'b', 'c'], datasets: [{ data: ['1', 2] }] },+ { chartType: 'bar', path: 'data.charts[0]' }+ )+ expect(warnings.join(' ')).toContain('data.charts[0].datasets[0]')+ expect(warnings.join(' ')).toContain('`data.charts[0].labels` had 3 entries')+ })++ it('keeps naming `data` for callers that pass no path', () => {+ expect(expectRejected(() => normalizeChartData({ datasets: [] }, bar))).toContain(+ '`data.datasets`'+ )+ })+})++describe('values that name their label', () => {+ it('are placed at their label, not in the order sent', () => {+ const r = normalizeChartData(+ {+ labels: ['Jan', 'Feb'],+ datasets: [+ {+ label: 'Rev',+ data: [+ { label: 'Feb', value: 200 },+ { label: 'Jan', value: 100 },+ ],+ },+ ],+ },+ bar+ )+ expect(r.labels).toEqual(['Jan', 'Feb'])+ expect(r.datasets[0].data).toEqual([100, 200])+ expect(r.warnings.join(' ')).toContain('placed at that label')+ })++ it('line series up by label, leaving a gap where a series has no value', () => {+ const r = normalizeChartData(+ {+ datasets: [+ {+ label: 'North',+ data: [+ ['Jan', 1],+ ['Feb', 2],+ ['Mar', 3],+ ],+ },+ {+ label: 'South',+ data: [+ { label: 'Mar', value: 30 },+ { label: 'Jan', value: 10 },+ ],+ },+ ],+ },+ { chartType: 'line' }+ )+ expect(r.labels).toEqual(['Jan', 'Feb', 'Mar'])+ expect(r.datasets[1].data).toEqual([10, null, 30])+ })+})++describe('single-series charts', () => {+ it('count only the series they draw when numbering missing labels', () => {+ const r = normalizeChartData(+ {+ labels: ['Start', 'Sales', 'Costs'],+ datasets: [+ { label: 'Delta', data: [100, 50, -30] },+ { label: 'Other', data: [1, 2, 3, 4, 5] },+ ],+ },+ { chartType: 'waterfall' }+ )+ expect(r.labels).toEqual(['Start', 'Sales', 'Costs'])+ })+})diff --git a/mcp-host/src/workflow/chartData.ts b/mcp-host/src/workflow/chartData.tsnew file mode 100644index 000000000..fff6396ab--- /dev/null+++ b/mcp-host/src/workflow/chartData.ts@@ -0,0 +1,709 @@+/**+ * Input normalization for chart data, shared by the tools that draw charts.+ *+ * Models describe the same chart in many shapes: numbers as strings, `{label,+ * value}` records instead of a numeric array, a missing `labels` key, a series+ * whose length disagrees with its labels.+ *+ * Everything unambiguous is repaired and reported as a warning; everything that+ * would yield a chart with nothing in it is rejected with a message naming the+ * field and the fix. Warnings travel back in the tool result so the agent can+ * correct itself on the next call.+ */+import { currencyPrefix, currencySuffix } from './xlsxCells'++/** Types whose points are {x,y} pairs rather than a value per label. */+const XY_TYPES = new Set(['scatter', 'bubble'])++/** Types that draw one colored slice per data point. */+const SLICE_TYPES = new Set(['pie', 'doughnut', 'polarArea'])++/** Types that draw each value as a share of the whole. */+const SHARE_TYPES = new Set(['pie', 'doughnut'])++/** Types that draw no category labels. */+const UNLABELLED_TYPES = new Set(['gauge'])++/** Types that carry exactly one series; extra datasets are dropped downstream. */+const SINGLE_SERIES_TYPES = new Set(['gauge', 'waterfall', 'funnel'])++export interface NormalizedPoint {+ x: number+ y: number+ r?: number+}++export interface NormalizedDataset {+ label?: string+ data: Array<number | null> | NormalizedPoint[]+ backgroundColor?: string | string[]+ borderColor?: string | string[]+ fill?: boolean+}++export interface NormalizedChartData {+ labels?: string[]+ datasets: NormalizedDataset[]+ warnings: string[]+}++export class ChartDataError extends Error {}++function fail(message: string): never {+ throw new ChartDataError(message)+}++/** The value of a numeral under each decimal convention that can spell it. */+interface Readings {+ /** "1,234.5": comma groups, dot decimals. */+ dot?: number+ /** "1.234,5": dot groups, comma decimals. */+ comma?: number+}++const SPACED_GROUPS = /^\d{1,3}(?:[ '_\u00a0\u202f]\d{3})+(?:[.,]\d+)?$/+const DOT_DECIMAL = /^(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)$/+const COMMA_DECIMAL = /^(?:(?:\d{1,3}(?:\.\d{3})+|\d+)(?:,\d+)?|,\d+)$/+const EXPONENT = /^\d+(?:\.\d+)?[eE][+-]?\d+$/++function readNumeral(text: string): Readings | undefined {+ if (EXPONENT.test(text)) return { dot: Number(text), comma: Number(text) }+ // Space, apostrophe and underscore only ever group digits.+ const body = SPACED_GROUPS.test(text) ? text.replace(/[ '_\u00a0\u202f]/g, '') : text+ const out: Readings = {}+ if (DOT_DECIMAL.test(body)) out.dot = Number(body.replace(/,/g, ''))+ if (COMMA_DECIMAL.test(body)) out.comma = Number(body.replace(/\./g, '').replace(',', '.'))+ return out.dot === undefined && out.comma === undefined ? undefined : out+}++/** Scale words, only directly after the number. A lowercase "m" is refused. */+const SCALES: Record<string, number> = {+ k: 3,+ K: 3,+ M: 6,+ mn: 6,+ Mn: 6,+ MN: 6,+ B: 9,+ bn: 9,+ Bn: 9,+ BN: 9,+}++type ParsedText =+ | { readings: Readings; negative: boolean; exponent: number }+ | { problem: string }+ | undefined++/**+ * Split text such as "-$1.2M", "(1,200)" or "45%" into its numeral, sign and+ * scale. Undefined when it holds no digit; a problem when it holds a number+ * that cannot be read without guessing.+ */+function parseText(value: string): ParsedText {+ let s = value.trim().replace(/\u2212/g, '-')+ if (!/\d/.test(s)) return undefined+ const quoted = `'${value.trim().slice(0, 40)}'`+ let negative = false+ const parens = /^\((.*)\)$/.exec(s)+ if (parens) {+ negative = true+ s = parens[1].trim()+ }+ const sign = () => {+ if (/^[-+]/.test(s)) {+ if (s[0] === '-') negative = !negative+ s = s.slice(1).trimStart()+ }+ }+ sign()+ const prefix = currencyPrefix(s)+ if (prefix) {+ s = s.slice(prefix[1]).trimStart()+ sign()+ }+ if (s.endsWith('%')) s = s.slice(0, -1).trimEnd()+ const suffix = currencySuffix(s)+ if (suffix) s = s.slice(0, s.length - suffix[1]).trimEnd()+ let exponent = 0+ const scaled = /^(.*\d)\s?([A-Za-z]+)$/.exec(s)+ if (scaled) {+ const word = scaled[2]+ if (word === 'm') {+ return {+ problem:+ `is ${quoted}: a lowercase m may mean million, minutes or metres. ` ++ `Send a JSON number, or write 'M' for million (e.g. '${scaled[1]}M').`,+ }+ }+ if (SCALES[word] === undefined) {+ return {+ problem:+ `is ${quoted}, which carries the unit '${word}'. Send the number alone ` ++ '(as JSON) and put the unit in the axis title or the series label.',+ }+ }+ exponent = SCALES[word]+ s = scaled[1]+ }+ const readings = readNumeral(s)+ if (!readings) {+ return { problem: `is ${quoted}, which is not a number a chart can read. Send JSON numbers.` }+ }+ return { readings, negative, exponent }+}++/** The decimal convention a set of values settles on, if any. */+type Convention = 'dot' | 'comma' | 'mixed' | undefined++function conventionOf(texts: string[]): Convention {+ let dot = false+ let comma = false+ for (const text of texts) {+ const parsed = parseText(text)+ if (!parsed || 'problem' in parsed) continue+ const { readings } = parsed+ if (readings.comma === undefined) dot = true+ else if (readings.dot === undefined) comma = true+ }+ return dot && comma ? 'mixed' : dot ? 'dot' : comma ? 'comma' : undefined+}++/**+ * Reads the numbers of one chart. Text such as "1.200" reads as 1.2 with dot+ * decimals and 1200 with comma decimals, so the convention is taken from the+ * values that can only be read one way; "1,200" alone follows the dot+ * convention, as the XLSX reader does.+ */+class NumberReader {+ private readonly convention: Convention++ constructor(texts: string[]) {+ this.convention = conventionOf(texts)+ }++ /** The number `value` holds; throws naming `where` when it cannot be read safely. */+ read(value: unknown, where: string): number | undefined {+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined+ if (typeof value !== 'string') return undefined+ const parsed = parseText(value)+ if (!parsed) return undefined+ if ('problem' in parsed) fail(`${where} ${parsed.problem}`)+ const quoted = `'${value.trim().slice(0, 40)}'`+ const { dot, comma } = parsed.readings+ const oneReading = dot === undefined || comma === undefined || dot === comma+ const neutral = dot !== undefined && dot === comma+ if (!neutral && this.convention === 'mixed') {+ fail(+ `${where} is ${quoted}, and this chart writes decimals both as "1,234.5" and as ` ++ '"1.234,5". Send JSON numbers.'+ )+ }+ let n: number+ if (oneReading) n = (dot ?? comma)!+ else if (this.convention) n = this.convention === 'comma' ? comma! : dot!+ else if (value.includes(',')) n = dot!+ else {+ fail(+ `${where} is ${quoted}, which reads as ${dot} or ${comma} depending on the ` ++ 'locale. Send JSON numbers.'+ )+ }+ const scaled = parsed.exponent ? Number((n * 10 ** parsed.exponent).toPrecision(15)) : n+ return parsed.negative ? -scaled : scaled+ }+}++/** Every string a chart's data holds, at the depths values are read from. */+function dataTexts(datasets: unknown[]): string[] {+ const texts: string[] = []+ const add = (v: unknown) => {+ if (typeof v === 'string') texts.push(v)+ }+ for (const ds of datasets) {+ const data = (ds as { data?: unknown } | null)?.data+ if (!Array.isArray(data)) continue+ for (const entry of data) {+ add(entry)+ if (Array.isArray(entry)) entry.forEach(add)+ else if (entry && typeof entry === 'object') Object.values(entry).forEach(add)+ }+ }+ return texts+}++/**+ * The number a single value holds: a JSON number, or text such as "1,234.5",+ * "$1.2M", "(1,200)", "45%" or "987,65". Undefined for text with no number, a+ * unit ("100 MB"), a lowercase "m", or a grouping that reads two ways ("1.200"),+ * so the caller can refuse it rather than plot a guess.+ */+export function coerceNumber(value: unknown): number | undefined {+ try {+ return new NumberReader([]).read(value, 'value')+ } catch {+ return undefined+ }+}++const LABEL_KEYS = ['label', 'name', 'category', 'key']+const VALUE_KEYS = ['value', 'y', 'count', 'total', 'amount']++interface RecordPoint {+ label?: string+ value: number+ /** The label came from a numeric `x`. */+ fromX: boolean+}++/** Read a `{label, value}`-style record, whatever synonym the model used. */+function readRecordPoint(+ obj: Record<string, unknown>,+ reader: NumberReader,+ where: string+): RecordPoint | undefined {+ let value: number | undefined+ for (const key of VALUE_KEYS) {+ if (key in obj) {+ value = reader.read(obj[key], `${where}.${key}`)+ if (value !== undefined) break+ }+ }+ if (value === undefined) return undefined++ for (const key of LABEL_KEYS) {+ const raw = obj[key]+ if (typeof raw === 'string' && raw !== '') return { label: raw, value, fromX: false }+ }+ const x = obj.x+ if (typeof x === 'string' && x !== '') return { label: x, value, fromX: false }+ if (typeof x === 'number' && Number.isFinite(x)) return { label: String(x), value, fromX: true }+ return { value, fromX: false }+}++function readXYPoint(+ obj: Record<string, unknown>,+ wantsRadius: boolean,+ reader: NumberReader,+ where: string+): NormalizedPoint | undefined {+ const x = reader.read(obj.x, `${where}.x`)+ const y = reader.read(obj.y, `${where}.y`)+ if (x === undefined || y === undefined) return undefined+ if (!wantsRadius) return { x, y }+ const r = reader.read(obj.r ?? obj.radius ?? obj.size, `${where}.r`)+ return { x, y, r: r !== undefined && r > 0 ? r : 6 }+}++interface SeriesResult {+ data: Array<number | null>+ labels?: string[]+ warnings: string[]+}++/** How text values were read, for the note that reports them. */+function readingsNote(where: string, read: Array<[string, number]>): string {+ const shown = read+ .filter(([text, n]) => text.trim() !== String(n))+ .slice(0, 3)+ .map(([text, n]) => `'${text.trim().slice(0, 40)}' as ${n}`)+ return (+ `${where}: read ${read.length} value(s) written as text` ++ (shown.length > 0 ? ` (${shown.join(', ')})` : '') ++ '. Send JSON numbers.'+ )+}++/** Normalize one dataset's `data` into numbers, harvesting labels if embedded. */+function normalizeSeries(raw: unknown, where: string, reader: NumberReader): SeriesResult {+ if (!Array.isArray(raw)) {+ fail(`${where}.data must be an array; received ${describe(raw)}.`)+ }+ if (raw.length === 0) {+ fail(`${where}.data is empty — a chart needs at least one value.`)+ }++ const data: Array<number | null> = []+ const harvested: string[] = []+ const warnings: string[] = []+ const readText: Array<[string, number]> = []+ let fromRecords = 0+ let fromX = 0+ let fromPairs = 0++ raw.forEach((entry, i) => {+ const at = `${where}.data[${i}]`+ if (entry === null || entry === undefined) {+ data.push(null)+ return+ }+ if (typeof entry === 'number') {+ if (!Number.isFinite(entry)) {+ fail(`${at} is ${String(entry)} — every value must be a finite number.`)+ }+ data.push(entry)+ return+ }+ if (typeof entry === 'string') {+ const n = reader.read(entry, at)+ if (n === undefined) {+ fail(+ `${at} is ${JSON.stringify(entry)}, which holds no number. ` ++ 'Send numbers, and put the text in `labels`.'+ )+ }+ readText.push([entry, n])+ data.push(n)+ return+ }+ if (Array.isArray(entry)) {+ // [label, value] or [x, y]: the first member names the position.+ const value = entry.length === 2 ? reader.read(entry[1], `${at}[1]`) : undefined+ const label = entry[0]+ if (value === undefined || (typeof label !== 'string' && typeof label !== 'number')) {+ fail(+ `${at} is an array; send a number per label, or a [label, value] pair ` ++ `(received ${JSON.stringify(entry).slice(0, 80)}).`+ )+ }+ fromPairs+++ harvested.push(String(label))+ data.push(value)+ return+ }+ if (typeof entry === 'object') {+ const point = readRecordPoint(entry as Record<string, unknown>, reader, at)+ if (!point) {+ fail(+ `${at} is an object with no numeric value ` ++ `(${JSON.stringify(entry).slice(0, 80)}). Use a plain number, or an object ` ++ 'carrying `value`. For scatter/bubble use `{x, y}` / `{x, y, r}`.'+ )+ }+ if (point.fromX) fromX+++ else fromRecords+++ if (point.label !== undefined) harvested.push(point.label)+ data.push(point.value)+ return+ }+ fail(`${at} is ${describe(entry)}, which is not a value a chart can plot.`)+ })++ const labelled = harvested.length === data.length+ if (readText.length > 0) warnings.push(readingsNote(where, readText))+ if (fromRecords > 0) {+ warnings.push(+ `${where}: read ${fromRecords} value(s) out of {label, value} objects` ++ (labelled ? ' and used their labels' : '') ++ '. A plain number array is the expected shape.'+ )+ }+ if (fromX > 0) {+ warnings.push(+ `${where}: read ${fromX} point(s) out of {x, y} objects` ++ (labelled ? ' and used each x as its category label' : '') ++ '. On this chart type send labels and a plain number array; {x, y} is for scatter.'+ )+ }+ if (fromPairs > 0) {+ warnings.push(+ `${where}: read ${fromPairs} [label, value] pair(s)` ++ (labelled ? ' and used their first members as labels' : '') ++ '. A plain number array with labels is the expected shape.'+ )+ }++ if (data.every(v => v === null)) {+ fail(`${where}.data holds no usable value — every entry was null.`)+ }++ return {+ data,+ labels: labelled ? harvested : undefined,+ warnings,+ }+}++function describe(v: unknown): string {+ if (v === null) return 'null'+ if (Array.isArray(v)) return 'an array'+ return `a ${typeof v}`+}++/** Normalize a scatter/bubble dataset, which needs coordinate pairs. */+function normalizeXYSeries(+ raw: unknown,+ where: string,+ wantsRadius: boolean,+ reader: NumberReader+): {+ data: NormalizedPoint[]+ warnings: string[]+} {+ if (!Array.isArray(raw)) fail(`${where}.data must be an array; received ${describe(raw)}.`)+ if (raw.length === 0) fail(`${where}.data is empty — a chart needs at least one point.`)++ const warnings: string[] = []+ const numeric: number[] = []+ const points: NormalizedPoint[] = []+ const shape = wantsRadius ? '`{x, y, r}` objects or [x, y, r]' : '`{x, y}` objects or [x, y]'++ for (const [i, entry] of raw.entries()) {+ const at = `${where}.data[${i}]`+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {+ const p = readXYPoint(entry as Record<string, unknown>, wantsRadius, reader, at)+ if (!p) {+ fail(+ `${at} needs numeric \`x\` and \`y\`` ++ (wantsRadius ? ' (and \`r\` for the bubble size)' : '') ++ `; received ${JSON.stringify(entry).slice(0, 80)}.`+ )+ }+ points.push(p)+ continue+ }+ if (Array.isArray(entry) && entry.length >= 2) {+ const x = reader.read(entry[0], `${at}[0]`)+ const y = reader.read(entry[1], `${at}[1]`)+ if (x === undefined || y === undefined) {+ fail(`${at} is a pair with non-numeric members; send ${shape}.`)+ }+ const r = wantsRadius ? reader.read(entry[2], `${at}[2]`) : undefined+ points.push(wantsRadius ? { x, y, r: r && r > 0 ? r : 6 } : { x, y })+ continue+ }+ const n = reader.read(entry, at)+ if (n === undefined) {+ fail(`${at} is ${describe(entry)}; scatter and bubble need {x, y} points: ${shape}.`)+ }+ numeric.push(n)+ }++ // A plain number array is unambiguous: index becomes x, value becomes y.+ if (numeric.length > 0) {+ if (points.length > 0) {+ fail(`${where}.data mixes coordinate objects with plain numbers; use one shape.`)+ }+ warnings.push(+ `${where}: received plain numbers, so each index was used as x and each value as y. ` ++ 'Send `{x, y}` points to control both axes.'+ )+ return {+ data: numeric.map((y, i) => (wantsRadius ? { x: i, y, r: 6 } : { x: i, y })),+ warnings,+ }+ }++ return { data: points, warnings }+}++export interface NormalizeOptions {+ /** The user-facing chart type, before it is mapped onto a Chart.js type. */+ chartType: string+ /**+ * Where the chart's `labels` and `datasets` sit in the caller's arguments,+ * so messages name the field the model has to fix. Defaults to `data`.+ */+ path?: string+}++/**+ * Validate and repair the `data` argument. Throws `ChartDataError` with an+ * actionable message when the input cannot produce a meaningful chart.+ */+export function normalizeChartData(raw: unknown, opts: NormalizeOptions): NormalizedChartData {+ const { chartType } = opts+ const root = opts.path ?? 'data'++ if (raw === null || raw === undefined) {+ fail(`\`${root}\` is required: { labels: string[], datasets: [{ label, data }] }.`)+ }+ if (typeof raw !== 'object' || Array.isArray(raw)) {+ fail(`\`${root}\` must be an object with a \`datasets\` array; received ${describe(raw)}.`)+ }++ const obj = raw as { labels?: unknown; datasets?: unknown }+ const warnings: string[] = []++ if (!Array.isArray(obj.datasets)) {+ fail(+ `\`${root}.datasets\` must be an array of series, e.g. ` ++ '[{ "label": "Revenue", "data": [120, 190] }].'+ )+ }+ if (obj.datasets.length === 0) fail(`\`${root}.datasets\` is empty — nothing to plot.`)++ let labels: string[] | undefined+ if (Array.isArray(obj.labels)) {+ labels = obj.labels.map(l => (typeof l === 'string' ? l : String(l ?? '')))+ } else if (obj.labels !== undefined && obj.labels !== null) {+ fail(`\`${root}.labels\` must be an array of strings; received ${describe(obj.labels)}.`)+ }++ const isXY = XY_TYPES.has(chartType)+ const reader = new NumberReader(dataTexts(obj.datasets))+ const datasets: NormalizedDataset[] = []+ /** Per dataset, the label each value carried, when every value carried one. */+ const labelled: Array<string[] | undefined> = []++ obj.datasets.forEach((dsRaw, index) => {+ if (dsRaw === null || typeof dsRaw !== 'object' || Array.isArray(dsRaw)) {+ fail(`${root}.datasets[${index}] must be an object with a \`data\` array.`)+ }+ const ds = dsRaw as Record<string, unknown>+ const where = `${root}.datasets[${index}]`++ if (isXY) {+ const { data, warnings: w } = normalizeXYSeries(+ ds.data,+ where,+ chartType === 'bubble',+ reader+ )+ warnings.push(...w)+ datasets.push({ ...(carryStyle(ds) as NormalizedDataset), data })+ return+ }++ const series = normalizeSeries(ds.data, where, reader)+ warnings.push(...series.warnings)+ labelled.push(series.labels)+ datasets.push({ ...(carryStyle(ds) as NormalizedDataset), data: series.data })+ })++ if (labelled.some(Boolean)) labels = placeByLabel(labels, datasets, labelled, root, warnings)++ if (SINGLE_SERIES_TYPES.has(chartType) && datasets.length > 1) {+ warnings.push(+ `"${chartType}" draws a single series; ${datasets.length - 1} extra dataset(s) were dropped.`+ )+ }++ if (!isXY) {+ // A single-series chart draws only the first dataset, so only it sets the length.+ const counted = SINGLE_SERIES_TYPES.has(chartType) ? datasets.slice(0, 1) : datasets+ const longest = Math.max(...counted.map(d => d.data.length))++ if (!labels) {+ // A slice chart with no labels is an unreadable ring of colors; a category+ // chart at least keeps its shape, so only the former is rejected.+ if (SLICE_TYPES.has(chartType)) {+ fail(+ `"${chartType}" needs \`${root}.labels\` — one label per slice — or the chart ` ++ 'cannot say what each slice is.'+ )+ }+ labels = Array.from({ length: longest }, (_, i) => String(i + 1))+ if (!UNLABELLED_TYPES.has(chartType)) {+ warnings.push(`\`${root}.labels\` was missing, so positions were numbered 1..n.`)+ }+ } else if (labels.length !== longest) {+ const before = labels.length+ if (before < longest) {+ for (let i = before; i < longest; i++) labels.push(String(i + 1))+ } else {+ labels = labels.slice(0, longest)+ }+ warnings.push(+ `\`${root}.labels\` had ${before} entries for ${longest} value(s); ` ++ (before < longest+ ? `the missing labels were numbered ${before + 1}..${longest}`+ : `the labels past ${longest} were left out`) ++ '. Send one label per value.'+ )+ }++ const plotted = datasets+ .flatMap(d => d.data as Array<number | null | NormalizedPoint>)+ .filter((v): v is number => typeof v === 'number')+ if (plotted.length > 0 && plotted.every(v => v === 0)) {+ warnings.push('every value is 0, so the chart will render as an empty plot.')+ }+ if (SHARE_TYPES.has(chartType)) {+ datasets.forEach((d, i) => {+ const below = (d.data as Array<number | null>).filter(v => v !== null && v < 0).length+ if (below === 0) return+ warnings.push(+ `\`${root}.datasets[${i}]\` has ${below} value(s) below zero, which a ${chartType} ` ++ 'cannot show: it draws each value as a share of the whole. Use a bar chart for them.'+ )+ })+ }+ }++ return { labels, datasets, warnings }+}++/**+ * Values that carry their own label ({label, value} records, [label, value]+ * pairs) placed at that label, not at their position: the categories are the+ * given labels, then any new ones in the order met. A series with no value for+ * a category leaves a gap there. Returns the categories.+ */+function placeByLabel(+ given: string[] | undefined,+ datasets: NormalizedDataset[],+ labelled: Array<string[] | undefined>,+ root: string,+ warnings: string[]+): string[] {+ const categories = given ? [...given] : []+ const index = new Map<string, number>()+ categories.forEach((label, i) => {+ if (!index.has(label)) index.set(label, i)+ })+ let moved = false+ let repeated = 0+ labelled.forEach((own, d) => {+ if (!own) return+ const values = datasets[d].data as Array<number | null>+ const placed: Array<number | null> = new Array(categories.length).fill(null)+ const seen = new Set<string>()+ own.forEach((label, i) => {+ if (seen.has(label)) {+ repeated+++ return+ }+ seen.add(label)+ let at = index.get(label)+ if (at === undefined) {+ at = categories.length+ categories.push(label)+ index.set(label, at)+ }+ if (at !== i) moved = true+ placed[at] = values[i]+ })+ datasets[d] = { ...datasets[d], data: placed }+ })+ // Series without labels of their own keep their positions, padded to every category.+ for (const ds of datasets) {+ const data = ds.data as Array<number | null>+ while (data.length < categories.length) data.push(null)+ }+ if (moved) {+ warnings.push(+ `${root}: values that name their label were placed at that label, not in the order sent.`+ )+ }+ if (repeated > 0) {+ warnings.push(+ `${root}: ${repeated} value(s) repeated a label already used in the same series and were left out.`+ )+ }+ return categories+}++/** Carry through the presentation fields a caller may have set explicitly. */+function carryStyle(ds: Record<string, unknown>): Partial<NormalizedDataset> {+ const out: Partial<NormalizedDataset> = {}+ if (typeof ds.label === 'string') out.label = ds.label+ if (typeof ds.backgroundColor === 'string' || Array.isArray(ds.backgroundColor)) {+ out.backgroundColor = ds.backgroundColor as string | string[]+ }+ if (typeof ds.borderColor === 'string' || Array.isArray(ds.borderColor)) {+ out.borderColor = ds.borderColor as string | string[]+ }+ if (typeof ds.fill === 'boolean') out.fill = ds.fill+ return out+}diff --git a/mcp-host/src/workflow/chartPlugins.ts b/mcp-host/src/workflow/chartPlugins.tsnew file mode 100644index 000000000..7ea9aa1c6--- /dev/null+++ b/mcp-host/src/workflow/chartPlugins.ts@@ -0,0 +1,571 @@+/**+ * Chart.js plugins that put the numbers on the chart itself.+ *+ * A chart whose values can only be read off an axis degrades badly: shrunk into+ * a report page, or rendered where a tick label is missing, it stops carrying+ * information. These plugins print the value at each mark, the share on each+ * slice, and the reading inside a gauge, so the picture stays legible on its+ * own. They are written against the Chart.js element geometry rather than a+ * plugin package, so nothing is added to the dependency tree.+ */+import type { Chart, ChartType, Plugin } from 'chart.js'+import { CHART_FONT_STACK } from './fonts'++export type ValueFormat = 'auto' | 'plain' | 'compact' | 'currency' | 'percent'++export interface ValueLabelOptions {+ format: ValueFormat+ /** Prefix for `currency`, e.g. "$" or "€". */+ currencySymbol?: string+ decimals?: number+ textColor: string+ backgroundColor: string+ /** 'y' when bars grow horizontally, which moves labels past the bar end. */+ indexAxis?: 'x' | 'y'+ /** Multiplier tying label type to the canvas size, as the axes use. */+ fontScale?: number+}++/** Below this, money is grouped in full rather than abbreviated. */+const CURRENCY_ABBREVIATE_FROM = 100_000++const COMPACT_STEPS: Array<[number, string]> = [+ [1_000_000_000, 'B'],+ [1_000_000, 'M'],+ [1_000, 'K'],+]++/** Render one number the way a reader expects to see it on a chart. */+export function formatValue(value: number, o: ValueLabelOptions): string {+ if (!Number.isFinite(value)) return ''+ const decimals = o.decimals+ const fixed = (n: number, d: number): string =>+ n+ .toFixed(d)+ .replace(/\.0+$/, '')+ .replace(/(\.\d*?)0+$/, '$1')++ switch (o.format) {+ case 'percent':+ return `${fixed(value, decimals ?? 1)}%`+ case 'currency': {+ const sym = o.currencySymbol ?? '$'+ const abs = Math.abs(value)+ const sign = value < 0 ? '-' : ''+ // Money reads better grouped until it gets long: $1,200 beats $1.2K,+ // while $120K beats $120,000 on a crowded axis.+ if (abs >= CURRENCY_ABBREVIATE_FROM) {+ for (const [step, suffix] of COMPACT_STEPS) {+ if (abs >= step) return `${sign}${sym}${fixed(abs / step, decimals ?? 1)}${suffix}`+ }+ }+ // Cents are kept, both places: $4.99 must not read as $5, nor $4.90 as $4.9.+ const places = decimals ?? (Number.isInteger(abs) ? 0 : Math.max(2, guessDecimals(abs)))+ const shown =+ decimals === undefined && places > 0+ ? abs.toFixed(places).replace(/(\.\d\d\d*?)0+$/, '$1')+ : fixed(abs, places)+ return `${sign}${sym}${group(shown)}`+ }+ case 'compact': {+ const abs = Math.abs(value)+ for (const [step, suffix] of COMPACT_STEPS) {+ if (abs >= step)+ return `${value < 0 ? '-' : ''}${fixed(abs / step, decimals ?? 1)}${suffix}`+ }+ return fixed(value, decimals ?? guessDecimals(value))+ }+ case 'plain':+ return group(fixed(value, decimals ?? guessDecimals(value)))+ case 'auto':+ default:+ return Math.abs(value) >= 10_000+ ? formatValue(value, { ...o, format: 'compact' })+ : group(fixed(value, decimals ?? guessDecimals(value)))+ }+}++/**+ * Enough decimal places for the value to survive rounding: a fixed count prints+ * 0.0012 as "0", so values below 1 get places by their order of magnitude.+ */+function guessDecimals(value: number): number {+ if (Number.isInteger(value)) return 0+ const abs = Math.abs(value)+ if (abs >= 10) return 1+ if (abs >= 1) return 2+ if (abs === 0) return 0+ // Two significant figures: 0.0012 -> 4 places, 0.5 -> 2.+ return Math.min(8, 1 - Math.floor(Math.log10(abs)))+}++function group(text: string): string {+ const [int, frac] = text.split('.')+ const sign = int.startsWith('-') ? '-' : ''+ const digits = sign ? int.slice(1) : int+ const grouped = digits.replace(/\B(?=(\d{3})+(?!\d))/g, ',')+ return `${sign}${grouped}${frac ? `.${frac}` : ''}`+}++/** Elements smaller than this are left unlabelled — the text would not fit. */+const MIN_ARC_SHARE = 0.04++/** Roughly how many value labels fit across a plot before they collide. */+const READABLE_LABEL_COUNT = 14++/**+ * Label every `stride`-th point. Returns 0 when the series is so dense that+ * even thinned labels would be noise rather than information.+ */+function labelStride(points: number): number {+ if (points <= READABLE_LABEL_COUNT) return 1+ const stride = Math.ceil(points / READABLE_LABEL_COUNT)+ return stride <= 3 ? stride : 0+}++interface Point {+ x: number+ y: number+}++interface Box {+ left: number+ top: number+ right: number+ bottom: number+}++function intersects(a: Box, b: Box): boolean {+ return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom+}++/**+ * The column of a radial scale's tick labels, which runs straight up from the+ * centre of a polar area chart. Undefined on charts without one.+ */+function radialTickColumn(chart: Chart): Box | undefined {+ const r = (chart.scales as Record<string, unknown> | undefined)?.r as+ | {+ xCenter?: number+ yCenter?: number+ drawingArea?: number+ ticks?: Array<{ label?: unknown }>+ options?: { ticks?: { display?: boolean } }+ }+ | undefined+ if (!r || r.options?.ticks?.display === false) return undefined+ const { xCenter, yCenter, drawingArea } = r+ if (xCenter === undefined || yCenter === undefined || drawingArea === undefined) return undefined+ const widest = Math.max(+ 0,+ ...(r.ticks ?? []).map(t => chart.ctx.measureText(String(t.label ?? '')).width)+ )+ const half = widest / 2 + 6+ return {+ left: xCenter - half,+ right: xCenter + half,+ top: yCenter - drawingArea - 12,+ bottom: yCenter,+ }+}++/** The legend and title boxes, which value labels must not print over. */+/** The rectangle of every drawn bar, with the element it belongs to. */+function barBoxes(chart: Chart, horizontal: boolean): Array<Box & { element: unknown }> {+ const out: Array<Box & { element: unknown }> = []+ chart.data.datasets.forEach((_, di) => {+ const meta = chart.getDatasetMeta(di)+ if (meta.hidden) return+ for (const element of meta.data) {+ const el = element as {+ x?: number+ y?: number+ base?: number+ width?: number+ height?: number+ }+ const thickness = horizontal ? el.height : el.width+ if (el.x === undefined || el.y === undefined || el.base === undefined) continue+ if (typeof thickness !== 'number' || !(thickness > 0)) continue+ out.push(+ horizontal+ ? {+ element,+ left: Math.min(el.x, el.base),+ right: Math.max(el.x, el.base),+ top: el.y - thickness / 2,+ bottom: el.y + thickness / 2,+ }+ : {+ element,+ left: el.x - thickness / 2,+ right: el.x + thickness / 2,+ top: Math.min(el.y, el.base),+ bottom: Math.max(el.y, el.base),+ }+ )+ }+ })+ return out+}++function reservedBoxes(chart: Chart): Box[] {+ const blocks = [+ (chart as { legend?: Partial<Box> }).legend,+ (chart as { titleBlock?: Partial<Box> }).titleBlock,+ ]+ return blocks.filter(+ (b): b is Box =>+ b !== undefined &&+ [b.left, b.top, b.right, b.bottom].every(v => typeof v === 'number') &&+ b.right! > b.left! &&+ b.bottom! > b.top!+ )+}++function isArcChart(type: ChartType | string): boolean {+ return type === 'pie' || type === 'doughnut' || type === 'polarArea'+}++/** Perceived lightness of a #rgb/#rrggbb fill, 0 (black) to 1 (white). */+function luminance(color: string): number | undefined {+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())+ if (!hex) return undefined+ let body = hex[1]+ if (body.length === 3)+ body = body+ .split('')+ .map(c => c + c)+ .join('')+ const r = parseInt(body.slice(0, 2), 16) / 255+ const g = parseInt(body.slice(2, 4), 16) / 255+ const b = parseInt(body.slice(4, 6), 16) / 255+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+}++/** The fill this element was drawn with, when it resolves to a single color. */+function elementFill(element: unknown, index: number): string | undefined {+ const opts = (element as { options?: { backgroundColor?: unknown } }).options+ const bg = opts?.backgroundColor+ if (typeof bg === 'string') return bg+ if (Array.isArray(bg)) {+ const c = bg[index % bg.length]+ return typeof c === 'string' ? c : undefined+ }+ return undefined+}++/**+ * Draw each value beside its mark. Slice charts additionally get their share of+ * the total, which is the number a reader of a pie actually wants.+ */+export function valueLabelsPlugin(options: ValueLabelOptions): Plugin {+ return {+ id: 'clerumValueLabels',+ // After everything else, so scale ticks drawn above the data do not cover them.+ afterDraw(chart: Chart) {+ try {+ drawValueLabels(chart, options)+ } catch {+ // A label is an enhancement; never let it cost the whole render.+ }+ },+ }+}++function drawValueLabels(chart: Chart, o: ValueLabelOptions): void {+ const { ctx } = chart+ const arcs = isArcChart((chart.config as { type?: ChartType }).type ?? 'bar')++ // Each ring of a pie or doughnut is a whole of its own.+ const totals = chart.data.datasets.map(ds =>+ arcs+ ? (ds.data ?? []).reduce<number>(+ (sum, v) => sum + (typeof v === 'number' ? Math.abs(v) : 0),+ 0+ )+ : 0+ )++ const points = chart.data.datasets.reduce((n, d) => n + (d.data?.length ?? 0), 0)+ const stride = labelStride(points)+ if (stride === 0) return++ const size = Math.round(12 * (o.fontScale ?? 1))+ // Labels of different series can land on the same spot; the first one drawn+ // keeps it. In a bar chart a label may cover its own bar, never another.+ const taken = reservedBoxes(chart)+ const bars = arcs ? [] : barBoxes(chart, o.indexAxis === 'y')+ ctx.save()+ const ticks = arcs ? radialTickColumn(chart) : undefined+ ctx.font = `600 ${size}px ${CHART_FONT_STACK}`+ ctx.textAlign = 'center'+ ctx.textBaseline = 'middle'++ chart.data.datasets.forEach((dataset, di) => {+ const meta = chart.getDatasetMeta(di)+ if (meta.hidden) return++ const total = totals[di]+ meta.data.forEach((element, ei) => {+ // Keep the first and last of a thinned series so the range stays readable.+ if (stride > 1 && ei % stride !== 0 && ei !== meta.data.length - 1) return+ const raw = dataset.data[ei]+ const value = typeof raw === 'number' ? raw : readY(raw)+ if (value === null) return++ let text = formatValue(value, o)+ if (arcs && total > 0) {+ text = `${text} (${((Math.abs(value) / total) * 100).toFixed(0)}%)`+ }+ if (!text) return++ if (arcs && total > 0 && Math.abs(value) / total < MIN_ARC_SHARE) return+ const half = ctx.measureText(text).width / 2 + 2+ const spot = labelSpot(chart, element, arcs, o.indexAxis === 'y', half)+ if (!spot) return+ const box = {+ left: spot.x - half,+ right: spot.x + half,+ top: spot.y - size / 2 - 1,+ bottom: spot.y + size / 2 + 1,+ }+ // A label on the tick column moves to the side of it its slice is on.+ if (ticks && intersects(box, ticks)) {+ const shift =+ spot.x < (ticks.left + ticks.right) / 2 ? ticks.left - box.right : ticks.right - box.left+ box.left += shift+ box.right += shift+ spot.x += shift+ }+ if (taken.some(other => intersects(box, other))) return+ if (bars.some(bar => bar.element !== element && intersects(box, bar))) return+ taken.push(box)++ // A label that lands on top of a filled slice has to invert; one that+ // sits in open plot area keeps the theme color over a halo of the ground.+ let ink = o.textColor+ let halo = o.backgroundColor+ if (arcs) {+ const light = luminance(elementFill(element, ei) ?? '')+ if (light !== undefined) {+ ink = light < 0.5 ? '#ffffff' : '#0f172a'+ halo = light < 0.5 ? '#00000055' : '#ffffff99'+ }+ }++ ctx.lineWidth = 3+ ctx.strokeStyle = halo+ ctx.strokeText(text, spot.x, spot.y)+ ctx.fillStyle = ink+ ctx.fillText(text, spot.x, spot.y)+ })+ })++ ctx.restore()+}++function readY(raw: unknown): number | null {+ // A floating bar is stored as [from, to]; the number worth printing is the+ // step it spans, which is what a waterfall is read for.+ if (Array.isArray(raw) && raw.length === 2) {+ const from = Number(raw[0])+ const to = Number(raw[1])+ return Number.isFinite(from) && Number.isFinite(to) ? to - from : null+ }+ if (raw && typeof raw === 'object' && 'y' in raw) {+ const y = (raw as { y: unknown }).y+ return typeof y === 'number' ? y : null+ }+ return null+}++/** Where the number goes for this element, in canvas coordinates. */+function labelSpot(+ chart: Chart,+ element: unknown,+ arcs: boolean,+ horizontal: boolean,+ halfWidth: number+): Point | undefined {+ const el = element as {+ x?: number+ y?: number+ base?: number+ getCenterPoint?: () => Point+ }++ if (arcs) {+ const centre = el.getCenterPoint?.()+ return centre ? { x: centre.x, y: centre.y } : undefined+ }++ if (el.x === undefined || el.y === undefined) return undefined+ const area = chart.chartArea++ // A horizontal bar grows along x, so its number sits just past the bar end.+ if (horizontal) {+ const outward = el.base !== undefined && el.x < el.base ? -(halfWidth + 6) : halfWidth + 6+ return { x: clampTo(el.x + outward, halfWidth, chart.width - halfWidth), y: el.y }+ }++ // Vertical bars and line points read best just above the mark; a negative bar+ // grows downward, so its label goes below.+ const offset = el.base !== undefined && el.y > el.base ? 14 : -12+ return {+ // Clamped against the canvas rather than the plot: a label on the first or+ // last mark sits over the axis gutter, but must not leave the image.+ x: clampTo(el.x, halfWidth, chart.width - halfWidth),+ y: clampTo(el.y + offset, area.top + 9, area.bottom - 9),+ }+}++function clampTo(v: number, lo: number, hi: number): number {+ return Math.min(Math.max(v, lo), hi)+}++/** Color distance below which two slice colors read as the same. */+const MIN_COLOR_DISTANCE = 48++function rgb(color: string): [number, number, number] | undefined {+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())?.[1]+ if (!hex) return undefined+ return [0, 2, 4].map(i => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number]+}++function mix(color: string, toward: string, share: number): string | undefined {+ const a = rgb(color)+ const b = rgb(toward)+ if (!a || !b) return undefined+ return `#${a+ .map((c, i) => Math.round(c + (b[i] - c) * share))+ .map(c => c.toString(16).padStart(2, '0'))+ .join('')}`+}++function distance(a: string, b: string): number {+ const x = rgb(a)+ const y = rgb(b)+ if (!x || !y) return a === b ? 0 : Infinity+ return Math.hypot(x[0] - y[0], x[1] - y[1], x[2] - y[2])+}++/**+ * One fill per slice: the caller's colors first, then the palette, then the+ * palette shaded toward and away from the background, skipping shades too close+ * to a color already used. Only when those run out do colors repeat, and then+ * never on the last slice, which sits beside the first.+ */+export function sliceColors(+ count: number,+ requested: string[] | undefined,+ palette: string[],+ background: string+): { colors: string[]; padded: boolean; repeated: boolean } {+ const own = (requested ?? []).filter(c => typeof c === 'string').slice(0, count)+ const light = (rgb(background) ?? [255, 255, 255]).reduce((sum, c) => sum + c, 0) > 382+ const shades = [+ ...palette.map(c => mix(c, background, 0.45)),+ ...palette.map(c => mix(c, light ? '#000000' : '#ffffff', 0.4)),+ ...palette.map(c => mix(c, background, 0.7)),+ ].filter((c): c is string => c !== undefined)+ const pool = [...own]+ for (const candidate of [...palette, ...shades]) {+ if (pool.length >= count) break+ if (pool.every(used => distance(used, candidate) >= MIN_COLOR_DISTANCE)) pool.push(candidate)+ }+ const distinct = pool.length+ const colors = Array.from({ length: count }, (_, i) => pool[i % distinct])+ if (count > distinct && count > 1 && colors[count - 1] === colors[0]) {+ colors[count - 1] = pool[Math.min(1, distinct - 1)]+ }+ return {+ colors,+ padded: requested !== undefined && own.length < count,+ repeated: count > distinct,+ }+}++export interface GaugeCenterOptions {+ value: number+ max: number+ textColor: string+ mutedColor: string+ format: ValueLabelOptions+}++/**+ * Print the reading inside the dial. Without it a gauge shows a coloured arc+ * and no number, which is the one thing a gauge exists to communicate.+ */+export function gaugeCenterPlugin(o: GaugeCenterOptions): Plugin {+ return {+ id: 'clerumGaugeCenter',+ afterDatasetsDraw(chart: Chart) {+ try {+ const { ctx, chartArea } = chart+ const cx = (chartArea.left + chartArea.right) / 2+ // The dial is a half circle, so its visual centre sits low in the box.+ const cy = chartArea.bottom - (chartArea.bottom - chartArea.top) * 0.12+ const size = Math.max(18, Math.min(52, (chartArea.right - chartArea.left) / 9))++ ctx.save()+ ctx.textAlign = 'center'+ ctx.textBaseline = 'alphabetic'+ ctx.fillStyle = o.textColor+ ctx.font = `700 ${size}px ${CHART_FONT_STACK}`+ ctx.fillText(formatValue(o.value, o.format), cx, cy)+ ctx.fillStyle = o.mutedColor+ ctx.font = `500 ${Math.round(size * 0.42)}px ${CHART_FONT_STACK}`+ // Neutral rather than an English word: the caller's title and labels+ // may be in any language, and this sits inside the same picture.+ ctx.fillText(`/ ${formatValue(o.max, o.format)}`, cx, cy + size * 0.62)+ ctx.restore()+ } catch {+ // Enhancement only.+ }+ },+ }+}++/**+ * Paint the theme background behind the plot. Kept here so every chart shares+ * one implementation rather than rebuilding the plugin per render.+ */+export function backgroundPlugin(color: string): Plugin {+ return {+ id: 'clerumBackground',+ beforeDraw(chart: Chart) {+ const { ctx } = chart+ ctx.save()+ ctx.globalCompositeOperation = 'destination-over'+ ctx.fillStyle = color+ ctx.fillRect(0, 0, chart.width, chart.height)+ ctx.restore()+ },+ }+}++/**+ * State the chart is empty instead of writing out a blank rectangle, so a+ * dataset that reduced to nothing is visible as such in the report.+ */+export function emptyStatePlugin(message: string, textColor: string): Plugin {+ return {+ id: 'clerumEmptyState',+ afterDraw(chart: Chart) {+ const { ctx, chartArea } = chart+ ctx.save()+ ctx.fillStyle = textColor+ ctx.font = `500 14px ${CHART_FONT_STACK}`+ ctx.textAlign = 'center'+ ctx.textBaseline = 'middle'+ ctx.fillText(+ message,+ (chartArea.left + chartArea.right) / 2,+ (chartArea.top + chartArea.bottom) / 2+ )+ ctx.restore()+ },+ }+}