Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(mcp-host): write XLSX cells as the numbers, dates and text they are

marcotebe8c23ca7f2da
diff --git a/mcp-host/src/workflow/xlsxCells.ts b/mcp-host/src/workflow/xlsxCells.ts
new file mode 100644
index 000000000..8fefbb8a3
--- /dev/null
+++ b/mcp-host/src/workflow/xlsxCells.ts
@@ -0,0 +1,325 @@
+/**
+ * Spreadsheet cells as models send them.
+ *
+ * Numbers, percents, money and dates arrive as text ("1,234.50", "45%",
+ * "$1,200", "2026-09-22") about as often as JSON numbers. Stored as text, Excel
+ * cannot sum, sort or format them, so such a string is written as the value it
+ * spells — unless reading it could change what it means.
+ */
+
+/** Symbol shown for each currency code; codes that share "$" keep a prefix. */
+export const CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: '£',
+ JPY: '¥',
+ CNY: '¥',
+ INR: '₹',
+ KRW: '₩',
+ BRL: 'R$',
+ MXN: 'MX$',
+ CAD: 'CA$',
+ AUD: 'A$',
+ CHF: 'CHF ',
+ COP: 'COP ',
+ CLP: 'CLP ',
+ ARS: 'ARS ',
+ PEN: 'S/ ',
+}
+
+/** Symbols a price may be written with, longest first so "R$" wins over "$". */
+const WRITTEN_SYMBOLS: Array<[string, string]> = [
+ ['US$', '$'],
+ ['MX$', 'MX$'],
+ ['CA$', 'CA$'],
+ ['R$', 'R$'],
+ ['A$', 'A$'],
+ ['$', '$'],
+ ['€', '€'],
+ ['£', '£'],
+ ['¥', '¥'],
+ ['₹', '₹'],
+ ['₩', '₩'],
+]
+
+export type CellKind =
+ | 'text'
+ | 'number'
+ | 'percent'
+ | 'currency'
+ | 'date'
+ | 'datetime'
+ | 'boolean'
+ | 'empty'
+
+export interface SheetCell {
+ /** What is written to the sheet. */
+ value: string | number | boolean | Date | null
+ kind: CellKind
+ /** The cell as sent, as text; `contains` and `regex` rules test it. */
+ text: string
+ /** The number as written ('45%' is 45, '$1,200' is 1200); numeric rules compare with it. */
+ written?: number
+ /** Symbol a currency text carried. */
+ currency?: string
+ /** A time with seconds, shown with them. */
+ seconds?: boolean
+ /** A time with a UTC offset, moved to UTC. */
+ shifted?: boolean
+ /** Text left alone because it reads as two different numbers. */
+ ambiguous?: boolean
+}
+
+// Groups of three with commas, or none. "1,5" and "1.234,50" stay text: which
+// separator is the decimal one depends on a locale the call does not carry.
+const NUMBER_CORE = /^(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)$/
+
+/** Excel keeps 15 significant digits; longer numbers are IDs, cards or phones. */
+const MAX_SIGNIFICANT_DIGITS = 15
+
+/** Longest "+" number read as signed; international phone numbers are longer. */
+const MAX_SIGNED_DIGITS = 6
+
+/** The currency symbol `s` opens with and the length of what spells it. */
+export function currencyPrefix(s: string): [string, number] | undefined {
+ for (const [written, symbol] of WRITTEN_SYMBOLS) {
+ if (s.startsWith(written)) return [symbol, written.length]
+ }
+ const code = /^([A-Z]{3})\s?(?=[\d.-])/.exec(s)
+ if (code && CURRENCY_SYMBOLS[code[1]]) return [CURRENCY_SYMBOLS[code[1]], code[0].length]
+ return undefined
+}
+
+/** The currency symbol `s` closes with and the length of what spells it. */
+export function currencySuffix(s: string): [string, number] | undefined {
+ for (const [written, symbol] of WRITTEN_SYMBOLS) {
+ if (s.endsWith(written)) return [symbol, written.length]
+ }
+ const code = /(?<=\d)\s?([A-Z]{3})$/.exec(s)
+ if (code && CURRENCY_SYMBOLS[code[1]]) return [CURRENCY_SYMBOLS[code[1]], code[0].length]
+ return undefined
+}
+
+type ParsedNumber = { value: number; written: number; percent: boolean; currency?: string }
+
+function parseNumberText(text: string): ParsedNumber | 'ambiguous' | undefined {
+ let s = text
+ let percent = false
+ if (s.endsWith('%')) {
+ percent = true
+ s = s.slice(0, -1).trimEnd()
+ }
+ // A leading "+" is also how phone numbers and country codes are written, so
+ // it is a sign only on a clear quantity: a percent, money, a decimal point or
+ // grouping, or a number too short to be a phone number.
+ let negative = s.startsWith('-')
+ const plus = !negative && s.startsWith('+')
+ if (negative || plus) s = s.slice(1)
+ let currency: string | undefined
+ const prefix = currencyPrefix(s)
+ if (prefix) {
+ currency = prefix[0]
+ s = s.slice(prefix[1]).trimStart()
+ if (!negative && s.startsWith('-')) {
+ negative = true
+ s = s.slice(1)
+ }
+ } else {
+ const suffix = currencySuffix(s)
+ if (suffix) {
+ currency = suffix[0]
+ s = s.slice(0, s.length - suffix[1]).trimEnd()
+ }
+ }
+ if ((currency && percent) || !NUMBER_CORE.test(s)) return undefined
+ if (plus && !percent && !currency && !/[.,]/.test(s) && s.length > MAX_SIGNED_DIGITS) {
+ return undefined
+ }
+ // Leading zeros mark a code ("00123"), which a number would lose.
+ if (/^0\d/.test(s)) return undefined
+ if (s.replace(/\D/g, '').replace(/^0+/, '').length > MAX_SIGNIFICANT_DIGITS) return undefined
+ // "1.200" is 1.2 in English and 1200 in Spanish or German.
+ if (/^[1-9]\d{0,2}\.\d{3}$/.test(s)) return 'ambiguous'
+ const plain = `${negative ? '-' : ''}${s.replace(/,/g, '')}`
+ const written = Number(plain) || 0
+ // Shifting the exponent in the text avoids 1.1 / 100 = 0.011000000000000001.
+ const value = percent ? Number(`${plain}e-2`) || 0 : written
+ return { value, written, percent, currency }
+}
+
+const ISO_DATE =
+ /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}(?::?\d{2})?)?)?$/
+
+type ParsedDate = { date: Date; time: boolean; seconds: boolean; shifted: boolean }
+
+function parseDateText(text: string): ParsedDate | undefined {
+ const m = ISO_DATE.exec(text)
+ if (!m) return undefined
+ const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])]
+ const [hour, minute, second] = [Number(m[4] ?? 0), Number(m[5] ?? 0), Number(m[6] ?? 0)]
+ if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59) return undefined
+ // Excel counts a 29 February 1900 that never existed, so the serial of any
+ // earlier date shows one day late; those dates stay text.
+ if (year < 1900 || (year === 1900 && month < 3)) return undefined
+ const ms = m[7] ? Math.round(Number(`0.${m[7]}`) * 1000) : 0
+ let time = Date.UTC(year, month - 1, day, hour, minute, second, ms)
+ const check = new Date(time)
+ if (check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) return undefined
+ let offsetMinutes = 0
+ if (m[8] && m[8] !== 'Z') {
+ const digits = m[8].replace(':', '')
+ offsetMinutes = Number(digits.slice(1, 3)) * 60 + Number(digits.slice(3, 5) || 0)
+ if (digits[0] === '-') offsetMinutes = -offsetMinutes
+ time -= offsetMinutes * 60_000
+ }
+ return {
+ date: new Date(time),
+ time: m[4] !== undefined,
+ seconds: m[6] !== undefined && (second !== 0 || ms !== 0),
+ shifted: offsetMinutes !== 0,
+ }
+}
+
+/**
+ * The cell to write for `raw`. With `convert` false, text is kept as sent,
+ * for columns declared as text or holding identifiers.
+ */
+export function readCell(raw: unknown, convert = true): SheetCell {
+ if (raw === null || raw === undefined) return { value: null, kind: 'empty', text: '' }
+ if (typeof raw === 'boolean') return { value: raw, kind: 'boolean', text: String(raw) }
+ if (typeof raw === 'number') {
+ return { value: raw, kind: 'number', text: String(raw), written: raw }
+ }
+ const text = String(raw)
+ if (!convert) return { value: text, kind: 'text', text }
+ const trimmed = text.trim()
+ const date = parseDateText(trimmed)
+ if (date) {
+ return {
+ value: date.date,
+ kind: date.time ? 'datetime' : 'date',
+ text,
+ seconds: date.seconds,
+ shifted: date.shifted,
+ }
+ }
+ // U+2212 is the typographic minus sign.
+ const parsed = parseNumberText(trimmed.replace(/^\u2212/, '-'))
+ if (parsed === 'ambiguous') return { value: text, kind: 'text', text, ambiguous: true }
+ if (!parsed) return { value: text, kind: 'text', text }
+ return {
+ value: parsed.value,
+ kind: parsed.percent ? 'percent' : parsed.currency ? 'currency' : 'number',
+ text,
+ written: parsed.written,
+ currency: parsed.currency,
+ }
+}
+
+const LOCALE_NUMBERS = [
+ // 1.234,50 and 1.234.567: dot grouping.
+ /^\d{1,3}(?:\.\d{3})+(?:,\d+)?$/,
+ // 12,5: comma decimals.
+ /^\d+,\d+$/,
+ // 1 234,50 and 1'234.50: space or apostrophe grouping.
+ /^\d{1,3}(?:[ '\u00A0\u202F]\d{3})+(?:[.,]\d+)?$/,
+ // 12,34,567: Indian grouping.
+ /^\d{1,2}(?:,\d{2})+,\d{3}(?:\.\d+)?$/,
+ // 1e6: an exponent.
+ /^\d+(?:\.\d+)?[eE][+-]?\d+$/,
+]
+const LOCALE_DATE = /^(?:\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}|\d{4}\/\d{1,2}\/\d{1,2})$/
+
+/**
+ * Whether text kept as text spells a number or a date in a form this reader
+ * does not convert ("1.234,50", "12,5%", "22/09/2026", "1e6"), so the caller
+ * can be told it stayed text.
+ */
+export function looksLikeUnreadNumber(text: string): boolean {
+ let s = text.trim()
+ if (s.length > 64) return false
+ if (LOCALE_DATE.test(s)) return true
+ s = s.replace(/^[-+\u2212(]\s*/, '').replace(/\)$/, '')
+ const prefix = currencyPrefix(s)
+ if (prefix) s = s.slice(prefix[1]).trimStart()
+ if (s.endsWith('%')) s = s.slice(0, -1).trimEnd()
+ const suffix = currencySuffix(s)
+ if (suffix) s = s.slice(0, s.length - suffix[1]).trimEnd()
+ return LOCALE_NUMBERS.some(pattern => pattern.test(s))
+}
+
+/** Whether `raw` is text written as a percent or an amount of money. */
+export function isQuantityText(raw: unknown): boolean {
+ if (typeof raw !== 'string') return false
+ const s = raw.trim().replace(/^[-+\u2212]\s*/, '')
+ return s.endsWith('%') || currencyPrefix(s) !== undefined || currencySuffix(s) !== undefined
+}
+
+/** Whether `text` is a run of digits a number would change: a leading zero, or over 15 of them. */
+export function codeDigits(text: string): boolean {
+ const s = text.trim()
+ return /^\d+$/.test(s) && (/^0\d/.test(s) || s.length > MAX_SIGNIFICANT_DIGITS)
+}
+
+/** The number a rule value stands for, read the way cells are. */
+export function ruleNumber(value: unknown): number | undefined {
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
+ if (typeof value !== 'string') return undefined
+ const cell = readCell(value)
+ return cell.written
+}
+
+/** The instant a rule value names, when it is an ISO 8601 date. */
+export function ruleDate(value: unknown): Date | undefined {
+ return typeof value === 'string' ? parseDateText(value.trim())?.date : undefined
+}
+
+/**
+ * Why `value` cannot be a cell, or undefined when it can. An object would reach
+ * ExcelJS as a formula, hyperlink or rich text — a formula-injection guard that
+ * only looks at strings never sees it.
+ */
+export function cellProblem(value: unknown): string | undefined {
+ if (value === null || value === undefined) return undefined
+ if (typeof value === 'string' || typeof value === 'boolean') return undefined
+ if (typeof value === 'number') {
+ return Number.isFinite(value) ? undefined : 'is not a finite number'
+ }
+ if (value instanceof Date) {
+ return "is a Date object; send the date as ISO 8601 text such as '2026-09-22'"
+ }
+ if (Array.isArray(value)) return 'is an array; a cell holds a single value'
+ if (typeof value === 'object') {
+ const keys = Object.keys(value)
+ .slice(0, 4)
+ .map(k => k.slice(0, 24))
+ .join(', ')
+ return (
+ `is an object${keys ? ` (keys: ${keys})` : ''}; formulas, links and rich text ` +
+ 'are not supported, so send the value itself'
+ )
+ }
+ return `is a ${typeof value}`
+}
+
+const FORMULA_LEAD = /^[=+\-@\t\r]/
+
+/** Text Excel would turn into a formula if the cell were edited and confirmed. */
+export function startsLikeFormula(text: string): boolean {
+ return FORMULA_LEAD.test(text)
+}
+
+const WIDE =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\u3000-\u303F\uFF01-\uFF60\uFFE0-\uFFE6]/u
+const ZERO_WIDTH = /[\p{Mn}\p{Me}\u200B-\u200D\uFE0E\uFE0F]/u
+
+/** Width of the widest line of `text` in Excel character units: CJK and emoji take two. */
+export function visualWidth(text: string): number {
+ let widest = 0
+ for (const line of text.split('\n')) {
+ let width = 0
+ for (const ch of line) width += ZERO_WIDTH.test(ch) ? 0 : WIDE.test(ch) ? 2 : 1
+ if (width > widest) widest = width
+ }
+ return widest
+}
diff --git a/mcp-host/src/workflow/xlsxFormats.ts b/mcp-host/src/workflow/xlsxFormats.ts
new file mode 100644
index 000000000..0da99411e
--- /dev/null
+++ b/mcp-host/src/workflow/xlsxFormats.ts
@@ -0,0 +1,302 @@
+/**
+ * Number formats for XLSX columns: the keywords a caller may ask for, and the
+ * format a column gets from its header and values when nobody asked.
+ */
+import { CURRENCY_SYMBOLS } from './xlsxCells'
+
+export const NUMBER_FORMATS = {
+ currencyUsd: '"$"#,##0.00_);[Red]("$"#,##0.00)',
+ currencyUsdInt: '"$"#,##0_);[Red]("$"#,##0)',
+ percent: '0.0%',
+ percentInt: '0%',
+ integer: '#,##0',
+ decimal: '#,##0.00',
+ plain: '0',
+ datetime: 'yyyy-mm-dd hh:mm',
+ date: 'yyyy-mm-dd',
+ text: '@',
+}
+
+/**
+ * How a column is formatted. Decimals left undefined are chosen from the
+ * values; `points` percents hold 45 for 45% and are divided by 100.
+ */
+export type FormatSpec =
+ | { type: 'currency'; symbol?: string; decimals?: 0 | 2 }
+ | { type: 'percent'; points: boolean; decimals?: 0 | 1 }
+ | { type: 'number'; numFmt: string }
+ | { type: 'date'; numFmt: string }
+ | { type: 'text' }
+ | { type: 'custom'; numFmt: string }
+
+export function currencyFormat(symbol: string, decimals: number): string {
+ const body = decimals > 0 ? '#,##0.00' : '#,##0'
+ const literal = `"${symbol.replace(/"/g, '')}"`
+ return `${literal}${body}_);[Red](${literal}${body})`
+}
+
+const KEYWORDS: Record<string, FormatSpec> = {
+ currencyusd: { type: 'currency', symbol: '$', decimals: 2 },
+ currencyusdint: { type: 'currency', symbol: '$', decimals: 0 },
+ currency: { type: 'currency' },
+ money: { type: 'currency' },
+ percent: { type: 'percent', points: false, decimals: 1 },
+ percentage: { type: 'percent', points: false, decimals: 1 },
+ pct: { type: 'percent', points: false, decimals: 1 },
+ '%': { type: 'percent', points: false, decimals: 1 },
+ percentint: { type: 'percent', points: false, decimals: 0 },
+ percentpoints: { type: 'percent', points: true },
+ integer: { type: 'number', numFmt: NUMBER_FORMATS.integer },
+ int: { type: 'number', numFmt: NUMBER_FORMATS.integer },
+ decimal: { type: 'number', numFmt: NUMBER_FORMATS.decimal },
+ number: { type: 'number', numFmt: NUMBER_FORMATS.decimal },
+ plain: { type: 'number', numFmt: NUMBER_FORMATS.plain },
+ year: { type: 'number', numFmt: NUMBER_FORMATS.plain },
+ id: { type: 'number', numFmt: NUMBER_FORMATS.plain },
+ date: { type: 'date', numFmt: NUMBER_FORMATS.date },
+ datetime: { type: 'date', numFmt: NUMBER_FORMATS.datetime },
+ timestamp: { type: 'date', numFmt: NUMBER_FORMATS.datetime },
+ text: { type: 'text' },
+ string: { type: 'text' },
+ '@': { type: 'text' },
+}
+
+/**
+ * Whether quotes and brackets close and there are at most four sections
+ * (positive;negative;zero;text): Excel asks to repair a file with more.
+ */
+function wellFormedSections(code: string): boolean {
+ let sections = 1
+ for (let i = 0; i < code.length; i++) {
+ const ch = code[i]
+ if (ch === '\\') i++
+ else if (ch === '"' || ch === '[') {
+ const end = code.indexOf(ch === '"' ? '"' : ']', i + 1)
+ if (end < 0) return false
+ i = end
+ } else if (ch === ']') return false
+ else if (ch === ';') sections++
+ }
+ return sections <= 4
+}
+
+/** A format code, as opposed to a word: digit placeholders or date parts only. */
+function looksLikeFormatCode(code: string): boolean {
+ if (/^general$/i.test(code)) return true
+ if (!wellFormedSections(code)) return false
+ const bare = code
+ .replace(/"[^"]*"/g, '')
+ .replace(/\[[^\]]*\]/g, '')
+ .replace(/\\./g, '')
+ return /^[0#?@.,%+\-/ :()ymdhsAMPEe_*;$€£¥]+$/.test(bare) && /[0#?@ymdhs]/i.test(bare)
+}
+
+/** The format a `columnFormats` value asks for, or undefined when it names none. */
+export function formatSpec(value: unknown): FormatSpec | undefined {
+ if (typeof value !== 'string' || !value.trim()) return undefined
+ const key = value
+ .trim()
+ .toLowerCase()
+ .replace(/[\s_-]+/g, '')
+ if (KEYWORDS[key]) return KEYWORDS[key]
+ const code = /^(?:currency|money)[:(]?([a-z]{3})\)?$/.exec(key)?.[1] ?? key
+ if (/^[a-z]{3}$/.test(code)) {
+ const upper = code.toUpperCase()
+ if (CURRENCY_SYMBOLS[upper]) return { type: 'currency', symbol: CURRENCY_SYMBOLS[upper] }
+ if (code !== key) return { type: 'currency', symbol: `${upper} ` }
+ }
+ const trimmed = value.trim()
+ return looksLikeFormatCode(trimmed) ? { type: 'custom', numFmt: trimmed } : undefined
+}
+
+/** Header words, lowercased and without accents: "Tasa de conversión" → tasa, de, conversion. */
+export function headerTokens(header: unknown): string[] {
+ return String(header ?? '')
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
+ .normalize('NFD')
+ .replace(/\p{M}/gu, '')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter(Boolean)
+}
+
+const words = (list: string): Set<string> => new Set(list.split(' '))
+
+/** English money words show a dollar sign. */
+const MONEY_WORDS_DOLLAR = words(
+ 'amount amounts revenue revenues price prices cost costs fee fees charge charges payment ' +
+ 'payments balance balances mrr arr salary salaries spend budget income profit profits expense expenses'
+)
+/** Spanish and Portuguese money words name no currency, so none is shown. */
+const MONEY_WORDS = words(
+ 'monto montos importe importes ingreso ingresos precio precios costo costos coste costes pago ' +
+ 'pagos saldo saldos tarifa tarifas gasto gastos presupuesto salario sueldo ganancia ganancias ' +
+ 'preco precos custo custos receita receitas pagamento pagamentos faturamento montante orcamento'
+)
+const PERCENT_WORDS = words(
+ 'pct percent percentage porcentaje porcentagem percentual rate tasa taxa share participacion'
+)
+/** Rates that are not shares of a whole. */
+const NOT_PERCENT_WORDS = words('exchange fx cambio heart hourly frame bit baud')
+const DATE_WORDS = words('date dates fecha fechas timestamp datetime')
+/** Events that date a row alone or with "at"/"on" ("Created at"); "Accounts created" is a count. */
+const DATE_EVENT_WORDS = words('created updated started completed modified')
+const DATE_EVENT_LINKS = words('at on el time')
+const YEAR_WORDS = words('year years yr fy ano anos anio')
+/** Identifiers read as numbers only lose digits or gain separators. */
+const ID_WORDS = words(
+ 'id ids uuid code codes codigo codigos sku ean upc isbn zip zipcode postal postcode cp cep ' +
+ 'phone phones telephone telefono telefone tel mobile celular movil nif rfc dni cuit cuil ' +
+ 'iban folio ref reference tracking ticket'
+)
+/** Things that are numbered; with a word for "number" the header names an identifier. */
+const NUMBERED_WORDS = words(
+ 'invoice factura fatura account cuenta conta employee empleado order pedido customer ' +
+ 'cliente document documento policy poliza serial contract contrato member socio case caso ' +
+ 'receipt recibo transaction transaccion'
+)
+/** "No.", "Nº", "Número": singular only, so "Number of employees" stays a count. */
+const NUMBER_WORDS = words('number no num nro numero n')
+
+const HEADER_CODE = new RegExp(
+ `(?:^|[^A-Za-z])(${Object.keys(CURRENCY_SYMBOLS).join('|')})(?![A-Za-z])`,
+ 'gi'
+)
+/** Codes that are also English words ("pen", "cop", "ars") count only in capitals. */
+const WORD_CODES = new Set(['PEN', 'COP', 'ARS'])
+const HEADER_SYMBOLS: Array<[string, string]> = [
+ ['US$', '$'],
+ ['MX$', 'MX$'],
+ ['CA$', 'CA$'],
+ ['R$', 'R$'],
+ ['A$', 'A$'],
+ ['€', '€'],
+ ['£', '£'],
+ ['¥', '¥'],
+ ['₹', '₹'],
+ ['₩', '₩'],
+ ['$', '$'],
+]
+
+/** The currency a header names by code or symbol, as the symbol to show. */
+export function headerCurrency(header: unknown): string | undefined {
+ const text = String(header ?? '')
+ for (const [, code] of text.matchAll(HEADER_CODE)) {
+ const upper = code.toUpperCase()
+ if (!WORD_CODES.has(upper) || code === upper) return CURRENCY_SYMBOLS[upper]
+ }
+ return HEADER_SYMBOLS.find(([written]) => text.includes(written))?.[1]
+}
+
+/**
+ * Whether a header names an identifier: an ID, code, postcode or phone number,
+ * or a numbered thing such as "Invoice No.", "Invoice #" or "Número de factura".
+ */
+export function isIdentifierHeader(header: unknown): boolean {
+ const tokens = headerTokens(header)
+ // "Ticket price" and "Code coverage %" name amounts, not identifiers.
+ const amount = [MONEY_WORDS_DOLLAR, MONEY_WORDS, PERCENT_WORDS].some(set =>
+ tokens.some(t => set.has(t))
+ )
+ if (amount || String(header ?? '').includes('%')) return false
+ if (tokens.some(t => ID_WORDS.has(t))) return true
+ return (
+ tokens.some(t => NUMBERED_WORDS.has(t)) &&
+ (tokens.some(t => NUMBER_WORDS.has(t)) || String(header ?? '').includes('#'))
+ )
+}
+
+function maxAbs(values: number[]): number {
+ let max = 0
+ for (const v of values) if (Math.abs(v) > max) max = Math.abs(v)
+ return max
+}
+
+// Excel serials for 1950-01-01 and 2100-12-31: a number outside this range
+// under a "date" header is a count, not a day.
+const SERIAL_MIN = 18264
+const SERIAL_MAX = 73415
+
+/** The format a column's header and numbers suggest, when no format was asked for. */
+export function detectFormat(header: unknown, numbers: number[]): FormatSpec | undefined {
+ if (numbers.length === 0) return undefined
+ const tokens = headerTokens(header)
+ const has = (set: Set<string>) => tokens.some(t => set.has(t))
+ const ints = numbers.every(n => Number.isInteger(n))
+
+ if (isIdentifierHeader(header)) {
+ return ints ? { type: 'number', numFmt: NUMBER_FORMATS.plain } : undefined
+ }
+ const symbol = headerCurrency(header)
+ if (symbol || has(MONEY_WORDS_DOLLAR)) {
+ return { type: 'currency', symbol: symbol ?? '$' }
+ }
+ if (has(MONEY_WORDS)) {
+ return { type: 'number', numFmt: ints ? NUMBER_FORMATS.integer : NUMBER_FORMATS.decimal }
+ }
+ const percentSign = String(header ?? '').includes('%')
+ if (percentSign || (has(PERCENT_WORDS) && !has(NOT_PERCENT_WORDS))) {
+ // Fractions stop at 1 (100%); a column reaching past 1.5 holds points, 45 for
+ // 45%. Under a "%" header, values past 1 are points too: "Churn %" of 1.1.
+ const max = maxAbs(numbers)
+ return { type: 'percent', points: max > 1.5 || (percentSign && max > 1) }
+ }
+ const dated =
+ has(DATE_WORDS) || (has(DATE_EVENT_WORDS) && (tokens.length === 1 || has(DATE_EVENT_LINKS)))
+ if (dated && numbers.every(n => n >= SERIAL_MIN && n <= SERIAL_MAX)) {
+ return { type: 'date', numFmt: ints ? NUMBER_FORMATS.date : NUMBER_FORMATS.datetime }
+ }
+ if (has(YEAR_WORDS) || (ints && numbers.every(n => n >= 1900 && n <= 2100))) {
+ return { type: 'number', numFmt: NUMBER_FORMATS.plain }
+ }
+ return { type: 'number', numFmt: ints ? NUMBER_FORMATS.integer : decimalFormat(numbers) }
+}
+
+/** Places `n` needs to show without rounding, up to six. */
+function placesOf(n: number): number {
+ for (let places = 0; places < 6; places++) {
+ if (Math.abs(n - Number(n.toFixed(places))) <= 1e-9 * Math.max(1, Math.abs(n))) return places
+ }
+ return 6
+}
+
+/** Two places, or as many as a value needs: a p-value of 0.0012 must not show 0.00. */
+function decimalFormat(numbers: number[]): string {
+ let places = 2
+ for (const n of numbers) places = Math.max(places, placesOf(n))
+ return places === 2 ? NUMBER_FORMATS.decimal : `#,##0.${'0'.repeat(places)}`
+}
+
+function wholePercents(fractions: number[]): boolean {
+ return fractions.every(v => Math.abs(v * 100 - Math.round(v * 100)) < 1e-9)
+}
+
+/** The numFmt a percent column gets for these stored fractions. */
+export function percentFormat(decimals: 0 | 1 | undefined, fractions: number[]): string {
+ const d = decimals ?? (wholePercents(fractions) ? 0 : 1)
+ return d === 0 ? NUMBER_FORMATS.percentInt : NUMBER_FORMATS.percent
+}
+
+/** Approximate width of a number or date as `numFmt` displays it, in characters. */
+export function displayedWidth(value: number | Date, numFmt: string | undefined): number {
+ if (value instanceof Date) {
+ if (!numFmt || !/h/i.test(numFmt)) return 10
+ return /s/i.test(numFmt.replace(/"[^"]*"/g, '')) ? 19 : 16
+ }
+ if (!numFmt || numFmt === '@' || /^general$/i.test(numFmt)) {
+ return Math.min(String(value).length, 11)
+ }
+ const section = numFmt.split(';')[0]
+ const literals = (section.match(/"[^"]*"/g) ?? []).join('').replace(/"/g, '').length
+ const bare = section.replace(/"[^"]*"/g, '')
+ const decimals = /\.(0+)/.exec(bare)?.[1].length ?? 0
+ const percent = bare.includes('%')
+ const shown = Math.abs(percent ? value * 100 : value).toLocaleString('en-US', {
+ useGrouping: bare.includes(','),
+ minimumFractionDigits: decimals,
+ maximumFractionDigits: decimals,
+ })
+ const padding = bare.includes('_') ? 1 : 0
+ const sign = value < 0 ? (numFmt.includes('(') ? 2 : 1) : 0
+ return shown.length + literals + (percent ? 1 : 0) + padding + sign
+}
diff --git a/mcp-host/src/workflow/xlsxRules.ts b/mcp-host/src/workflow/xlsxRules.ts
new file mode 100644
index 000000000..c7bd82d1d
--- /dev/null
+++ b/mcp-host/src/workflow/xlsxRules.ts
@@ -0,0 +1,190 @@
+/**
+ * Conditional formatting for XLSX columns: each rule is checked once, and every
+ * cell it styles is tested against the value as the caller wrote it.
+ */
+import * as vm from 'node:vm'
+import safeRegex from 'safe-regex'
+import { type SheetCell, ruleDate, ruleNumber } from './xlsxCells'
+import { argumentColor } from './xlsxSheet'
+
+export interface XlsxConditionalRule {
+ equals?: unknown
+ notEquals?: unknown
+ greaterThan?: unknown
+ lessThan?: unknown
+ /** Inclusive `[min, max]`. */
+ between?: unknown
+ contains?: unknown
+ regex?: unknown
+ fillColor?: unknown
+ fontColor?: unknown
+ bold?: unknown
+}
+
+export interface PreparedRule {
+ matches(cell: SheetCell): boolean
+ fill?: string
+ font?: string
+ bold?: boolean
+}
+
+// Pattern and input are both model-supplied, and a backtracking engine takes
+// exponential time on patterns such as ^(a|a)*$ that no static check catches,
+// so the matching runs in a vm context under a deadline.
+const MAX_REGEX_PATTERN_LENGTH = 256
+const MAX_REGEX_INPUT_LENGTH = 4096
+/** Time the regex rules of one workbook may take together. */
+const REGEX_BUDGET_MS = 500
+
+const MATCH_ALL = new vm.Script(
+ 'const re = new RegExp(pattern); const out = []; for (const t of texts) out.push(re.test(t)); out'
+)
+
+/** Time left for the regex rules of one workbook. */
+export class RegexBudget {
+ private remaining = REGEX_BUDGET_MS
+
+ /** Which of `texts` match `pattern`, or undefined when the time ran out. */
+ run(pattern: string, texts: string[]): boolean[] | undefined {
+ if (this.remaining <= 0) return undefined
+ const started = Date.now()
+ try {
+ const out = MATCH_ALL.runInContext(vm.createContext({ pattern, texts }), {
+ timeout: Math.max(1, Math.round(this.remaining)),
+ }) as boolean[]
+ return Array.from(out)
+ } catch {
+ return undefined
+ } finally {
+ this.remaining -= Date.now() - started
+ }
+ }
+}
+
+function sameValue(cell: SheetCell, expected: unknown): boolean {
+ if (cell.kind === 'empty') return expected === null || expected === ''
+ if (cell.kind === 'boolean' || typeof expected === 'boolean') {
+ return cell.text.toLowerCase() === String(expected).trim().toLowerCase()
+ }
+ if (cell.value instanceof Date) {
+ return ruleDate(expected)?.getTime() === cell.value.getTime()
+ }
+ if (cell.written !== undefined) {
+ const n = ruleNumber(expected)
+ if (n !== undefined) return n === cell.written
+ }
+ return (
+ cell.text.trim().toLowerCase() ===
+ String(expected ?? '')
+ .trim()
+ .toLowerCase()
+ )
+}
+
+function compileRegex(pattern: unknown, field: string, warnings: string[]): RegExp | undefined {
+ const reject = (why: string) => {
+ warnings.push(`${field} ${why}, so the rule was skipped.`)
+ return undefined
+ }
+ if (typeof pattern !== 'string') return reject('must be text')
+ if (pattern.length > MAX_REGEX_PATTERN_LENGTH) {
+ return reject(`is longer than ${MAX_REGEX_PATTERN_LENGTH} characters`)
+ }
+ let regex: RegExp
+ try {
+ regex = new RegExp(pattern)
+ } catch {
+ return reject('is not a valid regular expression')
+ }
+ // safe-regex turns away nested unbounded quantifiers (star height > 1) before
+ // they spend the time budget.
+ if (!safeRegex(pattern)) {
+ return reject(
+ 'has nested repetition that can hang the match; use contains or a simpler pattern'
+ )
+ }
+ return regex
+}
+
+/**
+ * The usable rules of one `conditionalFormatting` entry. A rule that cannot
+ * work is skipped with a warning naming it instead of failing the workbook.
+ * `texts` are the column's cells as sent, which regex rules are run on here.
+ */
+export function prepareRules(
+ rules: unknown,
+ label: string,
+ warnings: string[],
+ texts: string[],
+ budget: RegexBudget
+): PreparedRule[] {
+ if (!Array.isArray(rules)) {
+ warnings.push(`${label}.rules must be an array of rules; nothing was formatted.`)
+ return []
+ }
+ const prepared: PreparedRule[] = []
+ rules.forEach((raw, i) => {
+ const field = `${label}.rules[${i}]`
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ warnings.push(
+ `${field} must be an object such as {"equals": "Late", "fillColor": "#fee2e2"}.`
+ )
+ return
+ }
+ const rule = raw as XlsxConditionalRule
+ const bound = (key: 'greaterThan' | 'lessThan') => {
+ if (rule[key] === undefined) return undefined
+ const n = ruleNumber(rule[key])
+ if (n === undefined)
+ warnings.push(`${field}.${key} must be a number, so the rule was skipped.`)
+ return n ?? null
+ }
+ const greaterThan = bound('greaterThan')
+ const lessThan = bound('lessThan')
+ if (greaterThan === null || lessThan === null) return
+ let range: [number, number] | undefined
+ if (rule.between !== undefined) {
+ const ends = Array.isArray(rule.between) ? rule.between.map(ruleNumber) : []
+ if (ends.length !== 2 || ends.some(e => e === undefined)) {
+ warnings.push(`${field}.between must be [min, max], so the rule was skipped.`)
+ return
+ }
+ range = [Math.min(ends[0]!, ends[1]!), Math.max(ends[0]!, ends[1]!)]
+ }
+ let regexHits: Map<string, boolean> | undefined
+ if (rule.regex !== undefined) {
+ const regex = compileRegex(rule.regex, `${field}.regex`, warnings)
+ if (!regex) return
+ const inputs = [...new Set(texts.map(t => t.slice(0, MAX_REGEX_INPUT_LENGTH)))]
+ const hits = budget.run(regex.source, inputs)
+ if (!hits) {
+ warnings.push(
+ `${field}.regex took too long to test (over ${REGEX_BUDGET_MS} ms for all regex ` +
+ 'rules), so the rule was skipped; use contains, or a pattern without repeated ' +
+ 'alternatives such as (a|a)*.'
+ )
+ return
+ }
+ regexHits = new Map(inputs.map((t, j) => [t, hits[j]]))
+ }
+ const contains = rule.contains === undefined ? undefined : String(rule.contains).toLowerCase()
+
+ prepared.push({
+ matches(cell) {
+ if (rule.equals !== undefined && !sameValue(cell, rule.equals)) return false
+ if (rule.notEquals !== undefined && sameValue(cell, rule.notEquals)) return false
+ const n = cell.written
+ if (greaterThan !== undefined && !(n !== undefined && n > greaterThan)) return false
+ if (lessThan !== undefined && !(n !== undefined && n < lessThan)) return false
+ if (range && !(n !== undefined && n >= range[0] && n <= range[1])) return false
+ if (contains !== undefined && !cell.text.toLowerCase().includes(contains)) return false
+ if (regexHits && !regexHits.get(cell.text.slice(0, MAX_REGEX_INPUT_LENGTH))) return false
+ return true
+ },
+ fill: argumentColor(rule.fillColor, `${field}.fillColor`, warnings),
+ font: argumentColor(rule.fontColor, `${field}.fontColor`, warnings),
+ bold: typeof rule.bold === 'boolean' ? rule.bold : undefined,
+ })
+ })
+ return prepared
+}
diff --git a/mcp-host/src/workflow/xlsxSheet.ts b/mcp-host/src/workflow/xlsxSheet.ts
new file mode 100644
index 000000000..eb4aa2cc5
--- /dev/null
+++ b/mcp-host/src/workflow/xlsxSheet.ts
@@ -0,0 +1,235 @@
+/**
+ * The shape of an XLSX sheet request: its rows, its name, the columns other
+ * arguments point at, and the colors it names.
+ */
+import { headerText, normalizeTableRows } from './tableRows'
+import { cellProblem } from './xlsxCells'
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+/**
+ * Widest row. A loop, because `Math.max(...rows)` passes every row as an
+ * argument and overflows the stack at about 120k rows.
+ */
+export function tableWidth(rows: unknown[][]): number {
+ let width = 0
+ for (const row of rows) if (row.length > width) width = row.length
+ return width
+}
+
+/** Throws, naming the cell, when a row carries a value that is not a cell. */
+function checkCells(rows: unknown, headers: unknown, label: string): void {
+ const fail = (where: string, value: unknown) => {
+ const problem = cellProblem(value)
+ if (problem) {
+ throw new Error(
+ `${label}.${where} ${problem}. A cell must be text, a number, true/false or null.`
+ )
+ }
+ }
+ if (Array.isArray(headers)) headers.forEach((h, c) => fail(`headers[${c}]`, h))
+ if (!Array.isArray(rows)) return
+ rows.forEach((row, r) => {
+ if (Array.isArray(row)) row.forEach((v, c) => fail(`rows[${r}][${c}]`, v))
+ else if (isRecord(row)) for (const [k, v] of Object.entries(row)) fail(`rows[${r}].${k}`, v)
+ })
+}
+
+export interface SheetTable {
+ header: unknown[]
+ rows: unknown[][]
+}
+
+/**
+ * Header and data rows of a sheet. The header is `headers` when given, else the
+ * first row; rows sent as `{Header: value}` records are read by header name,
+ * and when every row is a record the header is the union of their keys.
+ */
+export function sheetTable(
+ sheet: { rows?: unknown; headers?: unknown },
+ label: string,
+ warnings: string[]
+): SheetTable {
+ checkCells(sheet.rows, sheet.headers, label)
+ if (Array.isArray(sheet.headers)) {
+ const header = sheet.headers
+ return { header, rows: normalizeTableRows(sheet.rows, header, label, warnings) }
+ }
+ if (!Array.isArray(sheet.rows)) {
+ return { header: [], rows: normalizeTableRows(sheet.rows, [], label, warnings) }
+ }
+ const rows = sheet.rows as unknown[]
+ const first = rows.findIndex(r => Array.isArray(r) || isRecord(r))
+ if (first >= 0 && Array.isArray(rows[first])) {
+ const header = rows[first] as unknown[]
+ const rest = rows.filter((_, i) => i !== first)
+ return { header, rows: normalizeTableRows(rest, header, label, warnings) }
+ }
+ const keys = new Set<string>()
+ for (const row of rows) if (isRecord(row)) for (const k of Object.keys(row)) keys.add(k)
+ const header = [...keys]
+ return { header, rows: normalizeTableRows(rows, header, label, warnings) }
+}
+
+const MAX_SHEET_NAME = 31
+const FORBIDDEN_SHEET_CHARS = /[\\/?*:[\]]/g
+
+/** The longest prefix of `text` within `max` UTF-16 units that does not split a character. */
+export function fitLength(text: string, max: number): string {
+ if (text.length <= max) return text
+ let out = ''
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(
+ text
+ )) {
+ if (out.length + segment.length > max) break
+ out += segment
+ }
+ return out
+}
+
+function stripQuotes(text: string): string {
+ return text
+ .trim()
+ .replace(/^'+|'+$/g, '')
+ .trim()
+}
+
+/**
+ * Sheet names Excel accepts, unique within one workbook. ExcelJS throws on an
+ * empty name, "History", the characters \ / ? * : [ ], a leading or trailing
+ * apostrophe and a case-insensitive duplicate — failing the whole workbook —
+ * and cuts names at 31 units, which can split an emoji or make two long names
+ * collide.
+ */
+export class SheetNames {
+ // Excel reserves "History" for its change log.
+ private readonly used = new Set(['history'])
+
+ name(requested: unknown, index: number, warnings: string[]): string {
+ const asked = requested === null || requested === undefined ? '' : String(requested)
+ const base =
+ stripQuotes(
+ fitLength(stripQuotes(asked.replace(FORBIDDEN_SHEET_CHARS, '-')), MAX_SHEET_NAME)
+ ) || `Sheet${index + 1}`
+ let name = base
+ for (let n = 2; this.used.has(name.toLowerCase()); n++) {
+ const suffix = ` (${n})`
+ name = `${fitLength(base, MAX_SHEET_NAME - suffix.length).trimEnd()}${suffix}`
+ }
+ this.used.add(name.toLowerCase())
+ if (name !== asked) {
+ warnings.push(
+ `sheets[${index}].name '${asked}' was saved as '${name}': Excel sheet names need 1 to 31 ` +
+ 'characters, none of \\ / ? * : [ ], no apostrophe at either end, must differ from ' +
+ "each other ignoring case, and can't be History."
+ )
+ }
+ return name
+ }
+}
+
+function lettersToIndex(letters: string): number {
+ let n = 0
+ for (const ch of letters.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64)
+ return n - 1
+}
+
+/**
+ * The 0-based column `ref` names: its header text (exact, then ignoring case
+ * and surrounding space), its Excel letter, or its 0-based index. Undefined
+ * when it names no column of the sheet.
+ */
+export function resolveColumn(ref: unknown, header: unknown[], width: number): number | undefined {
+ const inRange = (i: number) => (Number.isInteger(i) && i >= 0 && i < width ? i : undefined)
+ if (typeof ref === 'number') return inRange(ref)
+ if (typeof ref !== 'string') return undefined
+ const exact = header.findIndex(h => headerText(h) === ref)
+ if (exact >= 0) return exact
+ const wanted = ref.trim().toLowerCase()
+ const loose = header.findIndex(h => headerText(h).trim().toLowerCase() === wanted)
+ if (loose >= 0) return loose
+ if (/^[A-Za-z]{1,3}$/.test(wanted)) return inRange(lettersToIndex(wanted))
+ if (/^\d+$/.test(wanted)) return inRange(Number(wanted))
+ return undefined
+}
+
+const NAMED_COLORS: Record<string, string> = {
+ black: '000000',
+ white: 'FFFFFF',
+ red: 'FF0000',
+ green: '008000',
+ blue: '0000FF',
+ yellow: 'FFFF00',
+ orange: 'FFA500',
+ purple: '800080',
+ pink: 'FFC0CB',
+ brown: 'A52A2A',
+ gray: '808080',
+ grey: '808080',
+ navy: '000080',
+ teal: '008080',
+ maroon: '800000',
+ olive: '808000',
+ lime: '00FF00',
+ cyan: '00FFFF',
+ magenta: 'FF00FF',
+ silver: 'C0C0C0',
+ gold: 'FFD700',
+ indigo: '4B0082',
+ lightgray: 'D3D3D3',
+ lightgrey: 'D3D3D3',
+ darkgray: 'A9A9A9',
+ darkgrey: 'A9A9A9',
+ lightgreen: '90EE90',
+ darkgreen: '006400',
+ lightblue: 'ADD8E6',
+ darkblue: '00008B',
+ darkred: '8B0000',
+}
+
+/**
+ * ARGB for a CSS hex color ("#1e3a8a", "#fff", "#1e3a8a80"), a bare 8-digit
+ * Excel ARGB ("FF1E3A8A"), rgb(), or a basic CSS name. Alpha is dropped:
+ * Excel fills and fonts are opaque.
+ */
+export function parseColor(input: unknown): string | undefined {
+ const text = String(input ?? '').trim()
+ const css = text.startsWith('#')
+ const hex = css ? text.slice(1) : text
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) {
+ return `FF${[...hex.slice(0, 3)].map(c => c + c).join('')}`.toUpperCase()
+ }
+ if (/^[0-9a-f]{6}$/i.test(hex)) return `FF${hex}`.toUpperCase()
+ if (/^[0-9a-f]{8}$/i.test(hex)) return `FF${css ? hex.slice(0, 6) : hex.slice(2)}`.toUpperCase()
+ const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*[,)]/i.exec(text)
+ if (rgb && rgb.slice(1, 4).every(v => Number(v) <= 255)) {
+ return `FF${rgb
+ .slice(1, 4)
+ .map(v => Number(v).toString(16).padStart(2, '0'))
+ .join('')}`.toUpperCase()
+ }
+ const named = NAMED_COLORS[text.toLowerCase().replace(/[\s_-]+/g, '')]
+ return named ? `FF${named}` : undefined
+}
+
+/**
+ * parseColor for a caller's argument: an unreadable color is reported and
+ * replaced by `fallback`, or ignored when there is none.
+ */
+export function argumentColor(
+ input: unknown,
+ field: string,
+ warnings: string[],
+ fallback?: string
+): string | undefined {
+ if (input === undefined || input === null || input === '') return fallback
+ const argb = parseColor(input)
+ if (argb) return argb
+ warnings.push(
+ `${field} '${String(input)}' is not a color, so ${fallback ? 'the default was used' : 'it was ignored'}; ` +
+ "use a hex color such as '#1e3a8a'."
+ )
+ return fallback
+}
diff --git a/mcp-host/src/workflow/xlsxWorkbook.ts b/mcp-host/src/workflow/xlsxWorkbook.ts
new file mode 100644
index 000000000..a4c1ac524
--- /dev/null
+++ b/mcp-host/src/workflow/xlsxWorkbook.ts
@@ -0,0 +1,890 @@
+/**
+ * The workbook clerum__generate_xlsx writes: sheets, typed and formatted cells,
+ * conditional styles and images. Everything it drops or repairs is reported in
+ * `warnings`, so the agent does not describe content the file lacks.
+ */
+import ExcelJS from 'exceljs'
+import {
+ type EmbeddableImage,
+ type ImageSize,
+ fitImageSize,
+ loadEmbeddableImage,
+} from './embeddedImages'
+import { headerText } from './tableRows'
+import {
+ type SheetCell,
+ cellProblem,
+ codeDigits,
+ isQuantityText,
+ looksLikeUnreadNumber,
+ readCell,
+ startsLikeFormula,
+ visualWidth,
+} from './xlsxCells'
+import {
+ type FormatSpec,
+ NUMBER_FORMATS,
+ currencyFormat,
+ detectFormat,
+ displayedWidth,
+ formatSpec,
+ headerCurrency,
+ isIdentifierHeader,
+ percentFormat,
+} from './xlsxFormats'
+import { RegexBudget, prepareRules } from './xlsxRules'
+import {
+ SheetNames,
+ argumentColor,
+ fitLength,
+ resolveColumn,
+ sheetTable,
+ tableWidth,
+} from './xlsxSheet'
+
+interface XlsxPalette {
+ // ARGB hex (no leading '#'), 8 chars: AA RR GG BB
+ primary: string
+ primaryDark: string
+ text: string
+ zebra: string
+}
+
+const argb = (hex: string) => `FF${hex.replace('#', '').toUpperCase()}`
+
+const XLSX_PALETTES: Record<string, XlsxPalette> = {
+ default: {
+ primary: argb('#0f172a'),
+ primaryDark: argb('#020617'),
+ text: argb('#0f172a'),
+ zebra: argb('#f8fafc'),
+ },
+ corporate: {
+ primary: argb('#1e3a8a'),
+ primaryDark: argb('#1e293b'),
+ text: argb('#1e293b'),
+ zebra: argb('#f1f5f9'),
+ },
+ warm: {
+ primary: argb('#b45309'),
+ primaryDark: argb('#78350f'),
+ text: argb('#2f2823'),
+ zebra: argb('#fefdfb'),
+ },
+ alert: {
+ primary: argb('#9f1239'),
+ primaryDark: argb('#4c0519'),
+ text: argb('#1f2937'),
+ zebra: argb('#fef2f2'),
+ },
+}
+
+const WHITE = argb('#ffffff')
+/** Default row height, 15 points, in pixels. */
+const ROW_PX = 20
+const LOGO_BOX: ImageSize = { width: 160, height: 60 }
+const MIN_TEXT_WIDTH = 10
+const MAX_TEXT_WIDTH = 50
+/** Width Excel gives a column nobody sized, in characters. */
+const DEFAULT_COLUMN_WIDTH = 8.43
+/** A 14pt bold title character takes about 1.4 characters of the default font. */
+const TITLE_CHAR_WIDTH = 1.4
+const TITLE_ROW_HEIGHT = 28
+const TITLE_LINE_HEIGHT = 19
+const MAX_TITLE_COLUMN_WIDTH = 100
+/** Longest text a cell holds; Excel asks to repair a file with more. */
+const MAX_CELL_TEXT = 32_767
+
+interface XlsxSheetSpec {
+ name?: unknown
+ rows?: unknown
+ headers?: unknown
+ titleRow?: unknown
+ columnFormats?: unknown
+ conditionalFormatting?: unknown
+ freezeHeader?: unknown
+ autoFilter?: unknown
+ images?: unknown
+}
+
+export type XlsxBuild = { ok: true; buffer: Buffer; summary: string } | { ok: false; error: string }
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? '' : 's'}`
+
+/** loadEmbeddableImage, with a refused path reported against the argument that sent it. */
+function loadImage(
+ ref: unknown,
+ outputDir: string,
+ warnings: string[],
+ field: string
+): EmbeddableImage | undefined {
+ try {
+ return loadEmbeddableImage(ref, outputDir, warnings, field)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ throw new Error(
+ `${field}: ${message}. Pass the file name in the output folder, as ` +
+ "clerum__generate_chart returns it (e.g. 'sales.png')."
+ )
+ }
+}
+
+function positive(value: unknown): number | undefined {
+ return typeof value === 'number' && value > 0 ? value : undefined
+}
+
+function columnLetter(n: number): string {
+ let s = ''
+ while (n > 0) {
+ const r = (n - 1) % 26
+ s = String.fromCharCode(65 + r) + s
+ n = Math.floor((n - 1) / 26)
+ }
+ return s
+}
+
+/** The last column (XFD) and row a sheet has. */
+const MAX_COLUMN = 16_384
+const MAX_ROW = 1_048_576
+
+function columnNumber(letters: string): number {
+ let col = 0
+ for (const ch of letters.toUpperCase()) col = col * 26 + (ch.charCodeAt(0) - 64)
+ return col
+}
+
+/** Whether a cell such as "F2" lies inside the sheet. */
+function onSheet(letters: string, row: string): boolean {
+ const r = Number(row)
+ return r >= 1 && r <= MAX_ROW && columnNumber(letters) <= MAX_COLUMN
+}
+
+/** "F2" → { col: 5, row: 1 }, the zero-based anchor ExcelJS takes. */
+function cellAddressToCoord(address: string, field: string): { col: number; row: number } {
+ const m = /^\$?([A-Za-z]{1,3})\$?(\d+)$/.exec(address.trim())
+ if (!m || !onSheet(m[1], m[2])) {
+ throw new Error(
+ `Invalid cell anchor "${address}" in ${field}: use a cell such as "F2", within XFD1048576.`
+ )
+ }
+ return { col: columnNumber(m[1]) - 1, row: Number(m[2]) - 1 }
+}
+
+function cellRange(range: string, field: string): string {
+ const m = /^\$?([A-Za-z]{1,3})\$?(\d+):\$?([A-Za-z]{1,3})\$?(\d+)$/.exec(range.trim())
+ if (!m || !onSheet(m[1], m[2]) || !onSheet(m[3], m[4])) {
+ throw new Error(
+ `Invalid cell range "${range}" in ${field}: use a range such as "F2:M20", within XFD1048576.`
+ )
+ }
+ return `${m[1]}${m[2]}:${m[3]}${m[4]}`.toUpperCase()
+}
+
+/** Columns and the format each was asked for; keys that name nothing are reported. */
+function requestedFormats(
+ columnFormats: unknown,
+ header: unknown[],
+ width: number,
+ label: string,
+ warnings: string[]
+): Map<number, FormatSpec> {
+ const formats = new Map<number, FormatSpec>()
+ if (columnFormats === undefined || columnFormats === null) return formats
+ if (!isRecord(columnFormats)) {
+ warnings.push(`${label}.columnFormats must be an object such as {"Revenue": "currencyUsd"}.`)
+ return formats
+ }
+ const setBy = new Map<number, string>()
+ for (const [key, value] of Object.entries(columnFormats)) {
+ const col = resolveColumn(key, header, width)
+ if (col === undefined) {
+ warnings.push(
+ `${label}.columnFormats key '${key}' matches no column; use a header text, ` +
+ "a column letter such as 'B', or a 0-based index."
+ )
+ continue
+ }
+ const spec = formatSpec(value)
+ if (!spec) {
+ warnings.push(
+ `${label}.columnFormats['${key}'] '${String(value)}' is not a format, so the column was ` +
+ 'formatted automatically; use currencyUsd, currency:EUR, percent, percentPoints, ' +
+ "integer, decimal, plain, date, datetime, text, or an Excel code such as '#,##0.0'."
+ )
+ continue
+ }
+ if (setBy.has(col)) {
+ warnings.push(
+ `${label}.columnFormats keys '${setBy.get(col)}' and '${key}' name the same column; '${key}' was used.`
+ )
+ }
+ setBy.set(col, key)
+ formats.set(col, spec)
+ }
+ return formats
+}
+
+interface ColumnPlan {
+ spec?: FormatSpec
+ explicit: boolean
+ /** Format for the column's cells that fit its spec. */
+ numFmt?: string
+ /** Plain numbers are stored divided by it: 100 for percentage points. */
+ divisor: number
+ /** Some amount in the column has decimals, so currency shows cents. */
+ fraction: boolean
+}
+
+function maxAbs(values: number[]): number {
+ let max = 0
+ for (const v of values) if (Math.abs(v) > max) max = Math.abs(v)
+ return max
+}
+
+function planColumn(
+ cells: SheetCell[],
+ header: unknown,
+ requested: FormatSpec | undefined,
+ name: string,
+ warnings: string[]
+): ColumnPlan {
+ const numbers: number[] = []
+ const currencies = new Set<string>()
+ let fraction = false
+ for (const cell of cells) {
+ if (cell.kind === 'number') numbers.push(cell.value as number)
+ if ((cell.kind === 'number' || cell.kind === 'currency') && !Number.isInteger(cell.value)) {
+ fraction = true
+ }
+ if (cell.currency) currencies.add(cell.currency)
+ }
+ const spec = requested ?? detectFormat(header, numbers)
+ const plan: ColumnPlan = { spec, explicit: requested !== undefined, divisor: 1, fraction }
+ if (!spec) return plan
+ if (spec.type === 'currency') {
+ const symbol =
+ spec.symbol ?? headerCurrency(header) ?? (currencies.size === 1 ? [...currencies][0] : '$')
+ plan.numFmt = currencyFormat(symbol, spec.decimals ?? (fraction ? 2 : 0))
+ } else if (spec.type === 'percent') {
+ plan.divisor = spec.points ? 100 : 1
+ // Cells written as percents ('12.5%') count too, or 12.5% would show as 13%.
+ const shares = cells.flatMap(cell => (cell.kind === 'percent' ? [cell.value as number] : []))
+ plan.numFmt = percentFormat(spec.decimals, [...numbers.map(n => n / plan.divisor), ...shares])
+ const max = maxAbs(numbers)
+ const key = headerText(header)
+ if (spec.points && !requested) {
+ warnings.push(
+ `${name}: values up to ${max} were read as percentage points (45 = 45%)` +
+ (max <= 1.5 ? `; if they are fractions use columnFormats {'${key}': 'percent'}.` : '.')
+ )
+ } else if (!requested && numbers.length > 0) {
+ warnings.push(
+ `${name}: values up to ${max} were read as fractions (0.8 = 80%); if they are ` +
+ `percentage points use columnFormats {'${key}': 'percentPoints'}.`
+ )
+ } else if (!spec.points && requested && max > 1.5) {
+ warnings.push(
+ `${name} is formatted as a percent, which expects fractions (0.45 = 45%), but holds ` +
+ `values up to ${max}; use 'percentPoints' for values such as 45.`
+ )
+ }
+ } else if (spec.type === 'text') {
+ plan.numFmt = NUMBER_FORMATS.text
+ } else {
+ plan.numFmt = spec.numFmt
+ }
+ return plan
+}
+
+/**
+ * Whether every text value in column `c` is a plain integer. Identifier columns
+ * are converted only then: "02134" must stay text, and converting its
+ * neighbours would leave a column of numbers and text that sorts apart.
+ */
+function plainIntegers(rows: unknown[][], c: number): boolean {
+ return rows.every(
+ row => typeof row[c] !== 'string' || /^(?:0|[1-9]\d{0,14})$/.test(row[c].trim())
+ )
+}
+
+/**
+ * A value in column `c` that a number would change (a leading zero, more than
+ * 15 digits), when every value there is a whole number: such a column is kept
+ * as text throughout, so its values sort and match as one type.
+ */
+function codeColumn(rows: unknown[][], c: number): string | undefined {
+ let code: string | undefined
+ for (const row of rows) {
+ const v = row[c]
+ if (v === null || v === undefined || v === '') continue
+ if (typeof v === 'number') {
+ if (!Number.isSafeInteger(v) || v < 0) return undefined
+ } else if (typeof v !== 'string' || !/^\s*\d+\s*$/.test(v)) {
+ return undefined
+ } else if (code === undefined && codeDigits(v)) {
+ code = v.trim()
+ }
+ }
+ return code
+}
+
+/** Text cut to the cell limit, recording `address` when it was cut. */
+function capText<T>(value: T, address: string, cut: string[]): T {
+ if (typeof value !== 'string' || value.length <= MAX_CELL_TEXT) return value
+ cut.push(address)
+ return fitLength(value, MAX_CELL_TEXT) as T
+}
+
+/**
+ * Whether a requested format applies to `cell`. A percent or an amount in
+ * another currency keeps its own format: '45%' under 'integer' would show 0,
+ * and '$1,200' under 'percent' 120000%.
+ */
+function fits(spec: FormatSpec, cell: SheetCell): boolean {
+ const { kind } = cell
+ switch (spec.type) {
+ case 'text':
+ return true
+ case 'custom':
+ if (kind === 'percent') return spec.numFmt.includes('%')
+ if (kind === 'currency') return !!cell.currency && spec.numFmt.includes(cell.currency.trim())
+ return kind === 'number' || kind === 'date' || kind === 'datetime'
+ case 'date':
+ return kind === 'number' || kind === 'date' || kind === 'datetime'
+ case 'percent':
+ return kind === 'number' || kind === 'percent'
+ case 'currency':
+ return (
+ kind === 'number' ||
+ (kind === 'currency' && (!cell.currency || !spec.symbol || cell.currency === spec.symbol))
+ )
+ default:
+ return kind === 'number'
+ }
+}
+
+/** The value written for `cell` and the format it is shown with. */
+function cellOutput(
+ cell: SheetCell,
+ plan: ColumnPlan
+): { value: SheetCell['value']; numFmt?: string } {
+ const { spec } = plan
+ const value =
+ cell.kind === 'number' && plan.divisor !== 1
+ ? Number(((cell.value as number) / plan.divisor).toPrecision(15))
+ : cell.value
+ switch (cell.kind) {
+ case 'text': {
+ // Under the Text format, text that starts like a formula stays text even
+ // when the cell is edited, so nothing has to be added to it.
+ const asText = spec?.type === 'text' || startsLikeFormula(cell.text)
+ return { value, numFmt: asText ? NUMBER_FORMATS.text : undefined }
+ }
+ case 'boolean':
+ case 'empty':
+ return { value }
+ }
+ if (plan.explicit && spec && fits(spec, cell)) return { value, numFmt: plan.numFmt }
+ switch (cell.kind) {
+ case 'number':
+ return { value, numFmt: plan.numFmt }
+ case 'percent':
+ return {
+ value,
+ numFmt:
+ spec?.type === 'percent' ? plan.numFmt : percentFormat(undefined, [value as number]),
+ }
+ case 'currency':
+ return { value, numFmt: currencyFormat(cell.currency ?? '$', plan.fraction ? 2 : 0) }
+ case 'date':
+ return { value, numFmt: NUMBER_FORMATS.date }
+ default:
+ return { value, numFmt: cell.seconds ? 'yyyy-mm-dd hh:mm:ss' : NUMBER_FORMATS.datetime }
+ }
+}
+
+function cellWidth(value: unknown, numFmt: string | undefined): number {
+ if (value === null || value === undefined) return 0
+ if (typeof value === 'number' || value instanceof Date) return displayedWidth(value, numFmt)
+ if (typeof value === 'boolean') return 5
+ return visualWidth(String(value))
+}
+
+/**
+ * Keeps the whole title visible once the columns are sized. A merged cell
+ * clips its text, and columns are sized from the data alone, so a title wider
+ * than the table wraps onto taller rows; on a sheet without columns, column A
+ * is widened for it.
+ */
+function fitTitle(ws: ExcelJS.Worksheet, row: ExcelJS.Row, text: string, span: number): void {
+ const lines = text.split('\n').map(line => visualWidth(line) * TITLE_CHAR_WIDTH + 2)
+ const column = ws.getColumn(1)
+ if (span === 1 && column.width === undefined) {
+ column.width = Math.min(Math.max(...lines, DEFAULT_COLUMN_WIDTH), MAX_TITLE_COLUMN_WIDTH)
+ }
+ let available = 0
+ for (let c = 1; c <= span; c++) available += ws.getColumn(c).width ?? DEFAULT_COLUMN_WIDTH
+ const count = lines.reduce((sum, needed) => sum + Math.max(1, Math.ceil(needed / available)), 0)
+ if (count <= 1) return
+ for (let c = 1; c <= span; c++) {
+ row.getCell(c).alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }
+ }
+ row.height = TITLE_ROW_HEIGHT + (count - 1) * TITLE_LINE_HEIGHT
+}
+
+function addImages(
+ workbook: ExcelJS.Workbook,
+ ws: ExcelJS.Worksheet,
+ refs: unknown,
+ label: string,
+ startRow: number,
+ outputDir: string,
+ box: ImageSize,
+ warnings: string[]
+): number {
+ if (refs === undefined || refs === null) return 0
+ if (!Array.isArray(refs)) {
+ warnings.push(`${label}.images must be an array such as [{"path": "sales.png"}].`)
+ return 0
+ }
+ let row = startRow
+ let placed = 0
+ refs.forEach((ref, j) => {
+ const field = `${label}.images[${j}]`
+ const image = loadImage(ref, outputDir, warnings, field)
+ if (!image) return
+ const opts = isRecord(ref) ? ref : {}
+ const size = fitImageSize(image, box, {
+ width: positive(opts.width),
+ height: positive(opts.height),
+ })
+ const id = workbook.addImage({
+ buffer: image.data as unknown as ExcelJS.Buffer,
+ extension: image.format,
+ })
+ if (typeof opts.range === 'string' && opts.range.trim()) {
+ ws.addImage(id, cellRange(opts.range, `${field}.range`))
+ } else if (typeof opts.anchor === 'string' && opts.anchor.trim()) {
+ ws.addImage(id, {
+ tl: cellAddressToCoord(opts.anchor, `${field}.anchor`),
+ ext: size,
+ editAs: 'oneCell',
+ })
+ } else {
+ ws.addImage(id, { tl: { col: 0, row }, ext: size, editAs: 'oneCell' })
+ row += Math.ceil(size.height / ROW_PX) + 1
+ }
+ placed++
+ })
+ return placed
+}
+
+interface SheetContext {
+ workbook: ExcelJS.Workbook
+ palette: XlsxPalette
+ outputDir: string
+ imageBox: ImageSize
+ warnings: string[]
+ /** Time the regex rules of every sheet share. */
+ regexBudget: RegexBudget
+}
+
+/** Writes one sheet; returns what it holds, for the summary. */
+function writeSheet(
+ ws: ExcelJS.Worksheet,
+ sheet: XlsxSheetSpec,
+ label: string,
+ ctx: SheetContext,
+ logo?: EmbeddableImage
+): { rows: number; columns: number; images: number; title: boolean } {
+ const { warnings, palette } = ctx
+ const table = sheetTable(sheet, label, warnings)
+ const { header } = table
+ const width = Math.max(header.length, tableWidth(table.rows))
+
+ let rowNumber = 0
+ const titleRow = isRecord(sheet.titleRow) ? sheet.titleRow : undefined
+ let title: { row: ExcelJS.Row; text: string; span: number } | undefined
+ if (titleRow) {
+ const problem = cellProblem(titleRow.text)
+ if (problem) throw new Error(`${label}.titleRow.text ${problem}.`)
+ const titleCell = readCell(titleRow.text, false)
+ const titleText = capText(titleCell.value, 'A1', [])
+ if (titleText !== titleCell.value) {
+ warnings.push(`${label}.titleRow.text was cut to 32,767 characters, Excel's cell limit.`)
+ }
+ const row = ws.addRow([titleText])
+ rowNumber = 1
+ const span = Math.max(width, 1)
+ title = { row, text: titleCell.text, span }
+ if (span > 1) ws.mergeCells(1, 1, 1, span)
+ const font: Partial<ExcelJS.Font> = {
+ bold: true,
+ size: 14,
+ color: {
+ argb: argumentColor(titleRow.fontColor, `${label}.titleRow.fontColor`, warnings, WHITE),
+ },
+ }
+ const fill: ExcelJS.Fill = {
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: {
+ argb: argumentColor(
+ titleRow.fillColor,
+ `${label}.titleRow.fillColor`,
+ warnings,
+ palette.primary
+ ),
+ },
+ }
+ // Fill and font go on the merged cells only, not the row: a row style is
+ // written for all 16,384 columns and paints past the data area.
+ for (let c = 1; c <= span; c++) {
+ const cell = row.getCell(c)
+ cell.font = font
+ cell.fill = fill
+ cell.alignment = { vertical: 'middle', horizontal: 'center' }
+ }
+ if (startsLikeFormula(titleCell.text)) row.getCell(1).numFmt = NUMBER_FORMATS.text
+ row.height = TITLE_ROW_HEIGHT
+ }
+
+ const autoFilter = sheet.autoFilter !== false
+ const widths = new Array<number>(width).fill(0)
+ const headerRowNumber = rowNumber + 1
+ const dataRows = table.rows.length
+
+ if (width > 0) {
+ const requested = requestedFormats(sheet.columnFormats, header, width, label, warnings)
+ const columns: SheetCell[][] = Array.from({ length: width }, () => [])
+ const columnName = (c: number) =>
+ `${label} column ${headerText(header[c]).trim() ? `'${headerText(header[c])}'` : columnLetter(c + 1)}`
+ for (let c = 0; c < width; c++) {
+ const format = requested.get(c)
+ const code = format ? undefined : codeColumn(table.rows, c)
+ if (code !== undefined) {
+ warnings.push(
+ `${columnName(c)}: kept as text because '${code}' ` +
+ `${code.startsWith('0') ? 'has a leading zero' : 'has more than 15 digits'}, ` +
+ 'which a number would lose.'
+ )
+ for (const row of table.rows) {
+ const v = row[c]
+ columns[c].push(readCell(typeof v === 'number' ? String(v) : v, false))
+ }
+ continue
+ }
+ const convert = format
+ ? format.type !== 'text'
+ : !isIdentifierHeader(header[c]) || plainIntegers(table.rows, c)
+ // A percent or an amount of money is never an identifier.
+ for (const row of table.rows) {
+ columns[c].push(readCell(row[c], convert || (!format && isQuantityText(row[c]))))
+ }
+ }
+ const plans = columns.map((cells, c) =>
+ planColumn(cells, header[c], requested.get(c), columnName(c), warnings)
+ )
+ columns.forEach((cells, c) => {
+ const ambiguous = cells.find(cell => cell.ambiguous)
+ if (ambiguous) {
+ warnings.push(
+ `${columnName(c)}: '${ambiguous.text}' was kept as text because it reads as two ` +
+ 'different numbers depending on the locale; send numbers as JSON numbers.'
+ )
+ }
+ const unread = requested.has(c)
+ ? []
+ : cells.filter(
+ cell => cell.kind === 'text' && !cell.ambiguous && looksLikeUnreadNumber(cell.text)
+ )
+ if (unread.length > 0) {
+ const sample = unread[0].text.trim()
+ warnings.push(
+ `${columnName(c)}: ` +
+ (unread.length === 1
+ ? `'${sample}' was kept as text`
+ : `${unread.length} values such as '${sample}' were kept as text`) +
+ '; send JSON numbers, or ISO 8601 dates such as 2026-09-22.'
+ )
+ }
+ if (cells.some(cell => cell.shifted)) {
+ warnings.push(`${columnName(c)}: times with a UTC offset were converted to UTC.`)
+ }
+ const spec = requested.get(c)
+ if (spec && spec.type !== 'text') {
+ const misfits = cells.filter(
+ cell =>
+ cell.kind !== 'empty' && cell.kind !== 'boolean' && !cell.ambiguous && !fits(spec, cell)
+ )
+ if (misfits.length > 0) {
+ const hint =
+ spec.type === 'date'
+ ? "ISO 8601 dates such as '2026-09-22'"
+ : spec.type === 'custom'
+ ? "JSON numbers or ISO 8601 dates such as '2026-09-22'"
+ : 'JSON numbers such as 1234.5'
+ const chars = [...misfits[0].text]
+ const sample = chars.length > 40 ? `${chars.slice(0, 40).join('')}…` : misfits[0].text
+ const which =
+ misfits.length === 1
+ ? `'${sample}' does not fit the format columnFormats asked for, so it was`
+ : `${misfits.length} values such as '${sample}' do not fit the format ` +
+ 'columnFormats asked for, so they were'
+ warnings.push(`${columnName(c)}: ${which} written as sent; send ${hint}.`)
+ }
+ }
+ })
+
+ const cut: string[] = []
+ const headerRow = ws.addRow(
+ header.map((h, c) =>
+ h === undefined ? null : capText(h, `${columnLetter(c + 1)}${headerRowNumber}`, cut)
+ )
+ )
+ rowNumber++
+ const headerFont: Partial<ExcelJS.Font> = { bold: true, color: { argb: WHITE }, size: 11 }
+ const headerFill: ExcelJS.Fill = {
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: { argb: palette.primary },
+ }
+ // Styles are set per cell for the same reason as the title row.
+ for (let c = 0; c < width; c++) {
+ const cell = headerRow.getCell(c + 1)
+ cell.font = headerFont
+ cell.fill = headerFill
+ cell.border = { bottom: { style: 'thin', color: { argb: palette.primaryDark } } }
+ cell.alignment = { vertical: 'middle', horizontal: 'left', indent: 1 }
+ if (typeof header[c] === 'string' && startsLikeFormula(header[c] as string)) {
+ cell.numFmt = NUMBER_FORMATS.text
+ }
+ // The filter button takes about two characters of the header cell.
+ widths[c] = cellWidth(header[c], undefined) + (autoFilter && dataRows > 0 ? 2 : 0)
+ }
+ headerRow.height = 22
+
+ const dataFont: Partial<ExcelJS.Font> = { color: { argb: palette.text }, size: 10 }
+ const zebraFill: ExcelJS.Fill = {
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: { argb: palette.zebra },
+ }
+ for (let r = 0; r < dataRows; r++) {
+ const outputs = columns.map((cells, c) => {
+ const out = cellOutput(cells[r], plans[c])
+ const address = `${columnLetter(c + 1)}${headerRowNumber + 1 + r}`
+ return { ...out, value: capText(out.value, address, cut) }
+ })
+ const row = ws.addRow(outputs.map(o => o.value))
+ rowNumber++
+ for (let c = 0; c < width; c++) {
+ const cell = row.getCell(c + 1)
+ cell.font = dataFont
+ if (r % 2 === 1) cell.fill = zebraFill
+ const { value, numFmt } = outputs[c]
+ if (numFmt) cell.numFmt = numFmt
+ if (typeof value === 'number' || value instanceof Date) {
+ cell.alignment = { horizontal: 'right' }
+ }
+ const w = cellWidth(value, numFmt)
+ if (w > widths[c]) widths[c] = w
+ }
+ }
+
+ if (cut.length > 0) {
+ const shown = cut.slice(0, 5).join(', ')
+ const more = cut.length > 5 ? ` and ${cut.length - 5} more` : ''
+ warnings.push(
+ `${label}: ${cut.length === 1 ? `cell ${shown} was` : `cells ${shown}${more} were`} ` +
+ "cut to 32,767 characters, Excel's cell limit."
+ )
+ }
+
+ if (Array.isArray(sheet.conditionalFormatting)) {
+ sheet.conditionalFormatting.forEach((cf, j) => {
+ const cfLabel = `${label}.conditionalFormatting[${j}]`
+ if (!isRecord(cf)) {
+ warnings.push(`${cfLabel} must be an object with column and rules.`)
+ return
+ }
+ const col = resolveColumn(cf.column, header, width)
+ if (col === undefined) {
+ warnings.push(
+ `${cfLabel}.column '${String(cf.column)}' matches no column; use a header text, ` +
+ "a column letter such as 'B', or a 0-based index."
+ )
+ return
+ }
+ const texts = columns[col].map(cell => cell.text)
+ const rules = prepareRules(cf.rules, cfLabel, warnings, texts, ctx.regexBudget)
+ for (let r = 0; r < dataRows; r++) {
+ const rule = rules.find(candidate => candidate.matches(columns[col][r]))
+ if (!rule) continue
+ const cell = ws.getRow(headerRowNumber + 1 + r).getCell(col + 1)
+ if (rule.fill)
+ cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: rule.fill } }
+ if (rule.font || rule.bold !== undefined) {
+ cell.font = {
+ ...(cell.font as object),
+ ...(rule.font ? { color: { argb: rule.font } } : {}),
+ ...(rule.bold !== undefined ? { bold: rule.bold } : {}),
+ }
+ }
+ }
+ })
+ } else if (sheet.conditionalFormatting !== undefined) {
+ warnings.push(`${label}.conditionalFormatting must be an array of {column, rules}.`)
+ }
+
+ if (sheet.freezeHeader ?? dataRows > 0) {
+ ws.views = [{ state: 'frozen', xSplit: 0, ySplit: headerRowNumber }]
+ }
+ if (autoFilter && dataRows > 0) {
+ ws.autoFilter = `A${headerRowNumber}:${columnLetter(width)}${headerRowNumber}`
+ }
+ widths.forEach((w, c) => {
+ ws.getColumn(c + 1).width = Math.min(Math.max(w, MIN_TEXT_WIDTH), MAX_TEXT_WIDTH) + 2
+ })
+ }
+
+ if (title) fitTitle(ws, title.row, title.text, title.span)
+
+ let imageRow = rowNumber > 0 ? rowNumber + 1 : 0
+ let images = 0
+ if (logo) {
+ const size = fitImageSize(logo, LOGO_BOX)
+ const id = ctx.workbook.addImage({
+ buffer: logo.data as unknown as ExcelJS.Buffer,
+ extension: logo.format,
+ })
+ // Beside the data, one column apart, so it covers neither the title nor the
+ // header; with no columns, below the title, which then fills column A.
+ const logoRow = width > 0 ? 0 : rowNumber
+ ws.addImage(id, {
+ tl: { col: width > 0 ? width + 1 : 0, row: logoRow },
+ ext: size,
+ editAs: 'oneCell',
+ })
+ if (width === 0) {
+ imageRow = Math.max(imageRow, logoRow + Math.ceil(size.height / ROW_PX) + 1)
+ }
+ images++
+ }
+ images += addImages(
+ ctx.workbook,
+ ws,
+ sheet.images,
+ label,
+ imageRow,
+ ctx.outputDir,
+ ctx.imageBox,
+ warnings
+ )
+ return { rows: dataRows, columns: width, images, title: titleRow !== undefined }
+}
+
+/** Whether top-level `images`, which belong in a sheet, go on the first sheet. */
+function topLevelImagesPlaced(args: Record<string, unknown>): boolean {
+ return (
+ Array.isArray(args.images) &&
+ args.images.length > 0 &&
+ Array.isArray(args.sheets) &&
+ isRecord(args.sheets[0])
+ )
+}
+
+/**
+ * Builds the workbook `args` describe. Throws, with a message naming the
+ * argument, on input that must not be written (an object as a cell, a
+ * malformed anchor); returns `ok: false` when there is nothing to write.
+ */
+export async function buildXlsxWorkbook(
+ args: Record<string, unknown>,
+ outputDir: string,
+ imageBox: ImageSize,
+ warnings: string[]
+): Promise<XlsxBuild> {
+ const requested = args.sheets
+ if (!Array.isArray(requested) || requested.length === 0) {
+ return {
+ ok: false,
+ error:
+ 'sheets must be a non-empty array of sheets, e.g. ' +
+ '[{"name": "Sales", "rows": [["Month", "Revenue"], ["Jan", 1200]]}].',
+ }
+ }
+ let sheets: unknown[] = requested
+ // The other generators take images at the top level, so models send them there too.
+ if (topLevelImagesPlaced(args)) {
+ const first = sheets[0] as Record<string, unknown>
+ const own = Array.isArray(first.images) ? first.images : []
+ sheets = [{ ...first, images: [...own, ...(args.images as unknown[])] }, ...sheets.slice(1)]
+ warnings.push(
+ 'images belongs inside each sheet (sheets[i].images); the top-level images were placed on the first sheet.'
+ )
+ }
+ const palette = XLSX_PALETTES[String(args.palette ?? 'default')] ?? XLSX_PALETTES.default
+ const branding = isRecord(args.branding) ? args.branding : {}
+ const company = typeof branding.companyName === 'string' ? branding.companyName : ''
+
+ const workbook = new ExcelJS.Workbook()
+ workbook.creator = company
+ workbook.company = company
+ workbook.created = new Date()
+ const ctx: SheetContext = {
+ workbook,
+ palette,
+ outputDir,
+ imageBox,
+ warnings,
+ regexBudget: new RegexBudget(),
+ }
+
+ let logo = branding.logoPath
+ ? loadImage(branding.logoPath, outputDir, warnings, 'branding.logoPath')
+ : undefined
+ const names = new SheetNames()
+ const parts: string[] = []
+ let written = false
+ sheets.forEach((sheet, i) => {
+ const label = `sheets[${i}]`
+ if (!isRecord(sheet)) {
+ warnings.push(`${label} must be an object with a name and rows; it was left out.`)
+ return
+ }
+ const ws = workbook.addWorksheet(names.name(sheet.name, i, warnings))
+ const result = writeSheet(ws, sheet, label, ctx, logo)
+ logo = undefined
+ const holds: string[] = []
+ if (result.columns > 0) {
+ holds.push(`${count(result.rows, 'data row')}, ${count(result.columns, 'column')}`)
+ }
+ if (result.images > 0) holds.push(count(result.images, 'image'))
+ if (holds.length > 0 || result.title) written = true
+ else warnings.push(`${label} has no rows or images, so sheet '${ws.name}' is empty.`)
+ parts.push(
+ `sheet '${ws.name}' (${holds.join(', ') || (result.title ? 'title only' : 'empty')})`
+ )
+ })
+
+ if (!written) {
+ return {
+ ok: false,
+ error:
+ 'No sheet had rows or images to write, so no file was created. Send sheets[].rows as ' +
+ 'arrays of cells with the header row first, e.g. [["Month", "Revenue"], ["Jan", 1200]].' +
+ (warnings.length > 0 ? ` Details: ${warnings.join(' ')}` : ''),
+ }
+ }
+ const raw = (await workbook.xlsx.writeBuffer()) as unknown as ArrayBufferView
+ return {
+ ok: true,
+ buffer: Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength),
+ summary: parts.join('; '),
+ }
+}