From 747c8b1c61c4001a0eee52c207a66b95b47e2d39 Mon Sep 17 00:00:00 2001 From: unknowlei <1049573774@qq.com> Date: Fri, 2 Oct 2026 10:32:10 +0800 Subject: [PATCH] Fix missing columns in Markdown tables without outer pipes --- src/utils/markdown-table.test.ts | 35 ++++++++++++++++++++++++++++++++ src/utils/markdown-table.ts | 15 +++++--------- 2 files changed, 40 insertions(+), 10 deletions(-) create mode 100644 src/utils/markdown-table.test.ts diff --git a/src/utils/markdown-table.test.ts b/src/utils/markdown-table.test.ts new file mode 100644 index 000000000..50a9d7d2e --- /dev/null +++ b/src/utils/markdown-table.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from 'bun:test'; +import { formatResponse, parseMarkdownTable, renderBoxTable } from './markdown-table.js'; + +describe('markdown table outer pipes', () => { + const headers = ['Name', 'Revenue', 'Profit']; + const rows = [['Acme', '100', '20']]; + const borders = [ + { name: 'no outer pipes', left: '', right: '' }, + { name: 'a leading pipe only', left: '| ', right: '' }, + { name: 'a trailing pipe only', left: '', right: ' |' }, + { name: 'both outer pipes', left: '| ', right: ' |' }, + ]; + + for (const { name, left, right } of borders) { + test(`keeps all columns with ${name}`, () => { + const table = [headers, ['---', '---', '---'], ...rows] + .map(cells => `${left}${cells.join(' | ')}${right}`) + .join('\n'); + + expect(parseMarkdownTable(table)).toEqual({ headers, rows }); + expect(formatResponse(table)).toBe(renderBoxTable(headers, rows)); + }); + } + + for (const emptyIndex of [0, 1, 2]) { + test(`preserves an empty header in column ${emptyIndex + 1}`, () => { + const emptyHeaders = headers.map((header, index) => index === emptyIndex ? '' : header); + const table = [emptyHeaders, ['---', '---', '---'], ...rows] + .map(cells => `| ${cells.join(' | ')} |`) + .join('\n'); + + expect(parseMarkdownTable(table)).toEqual({ headers: emptyHeaders, rows }); + }); + } +}); diff --git a/src/utils/markdown-table.ts b/src/utils/markdown-table.ts index bc7d1aa14..f7b285fdd 100644 --- a/src/utils/markdown-table.ts +++ b/src/utils/markdown-table.ts @@ -45,16 +45,11 @@ export function parseMarkdownTable(tableText: string): { headers: string[]; rows const headers = headerLine .split('|') - .map(cell => cell.trim()) - .filter((_, i, arr) => i > 0 && i < arr.length - 1 || arr.length === 1); - - // Handle edge case where there's no leading/trailing pipe - if (headers.length === 0) { - const rawHeaders = headerLine.split('|').map(cell => cell.trim()); - if (rawHeaders.length > 0) { - headers.push(...rawHeaders); - } - } + .map(cell => cell.trim()); + + // Remove only the empty cells introduced by outer pipes. + if (headerLine.startsWith('|')) headers.shift(); + if (headerLine.endsWith('|')) headers.pop(); if (headers.length === 0) return null;