Skip to content

Commit 95a9ead

Browse files
committed
fix(search): let a UTF-8 byte-order mark override a declared charset
1 parent fa4fbbe commit 95a9ead

2 files changed

Lines changed: 12 additions & 5 deletions

File tree

‎apps/sim/lib/sim-search/live/slack.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ describe('Slack file reads', () => {
134134
Buffer.from('Größe: 3', 'latin1')
135135
)
136136
expect((await readSlack(latin1, 'F123', undefined, 'file')).content).toBe('Größe: 3')
137+
const utf8 = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('Größe: 3')])
138+
const marked = fileClient({ mimetype: 'text/plain; charset=ISO-8859-1' }, async () => utf8)
139+
expect((await readSlack(marked, 'F123', undefined, 'file')).content).toBe('Größe: 3')
137140
})
138141
it('keeps the preview when text bytes cannot be read in their charset', async () => {
139142
for (const bytes of [

‎apps/sim/lib/sim-search/live/slack.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -362,18 +362,22 @@ function slackFileFormat(file: Record<string, unknown>): SlackFileFormat | undef
362362
return documentExtension(mimetype)
363363
}
364364

365+
const BYTE_ORDER_MARKS = [
366+
[[0xef, 0xbb, 0xbf], 'utf-8'],
367+
[[0xff, 0xfe], 'utf-16le'],
368+
[[0xfe, 0xff], 'utf-16be'],
369+
] as const
370+
365371
/**
366372
* Decodes downloaded text strictly: a byte-order mark wins, then the declared charset, then UTF-8.
367373
* Bytes invalid in that charset, or text holding NULs (UTF-16 without a mark), are unreadable.
368374
*/
369375
function decodeFileText(bytes: Buffer, mimetype: string): string | undefined {
370376
const charset = /;\s*charset="?([\w.:-]+)"?/i.exec(mimetype)?.[1]
371377
const label =
372-
bytes[0] === 0xff && bytes[1] === 0xfe
373-
? 'utf-16le'
374-
: bytes[0] === 0xfe && bytes[1] === 0xff
375-
? 'utf-16be'
376-
: (charset ?? 'utf-8')
378+
BYTE_ORDER_MARKS.find(([mark]) => mark.every((byte, index) => bytes[index] === byte))?.[1] ??
379+
charset ??
380+
'utf-8'
377381
let text: string
378382
try {
379383
text = new TextDecoder(label, { fatal: true }).decode(bytes)

0 commit comments

Comments
 (0)