mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(core): detect PDFs whose header is not at byte 0 (#65967)
This commit is contained in:
parent
6e2289bc94
commit
ee3326b5d1
2 changed files with 41 additions and 0 deletions
|
|
@ -39,6 +39,8 @@ export function detectMedia(bytes: Uint8Array) {
|
|||
if (brand === "M4A ") return "audio/mp4"
|
||||
return "video/mp4"
|
||||
}
|
||||
const pdf = ascii(bytes, 0, 1024).search(/%PDF-\d\.\d\s*%[\x80-\xff]{4}/)
|
||||
if (pdf > 0 && isText(bytes.subarray(0, pdf)) && !isText(bytes)) return "application/pdf"
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,6 +28,45 @@ describe("Mime.detect", () => {
|
|||
}
|
||||
})
|
||||
|
||||
test("finds a PDF header within the first kilobyte", () => {
|
||||
const pdf = (prefix: string) =>
|
||||
Buffer.concat([
|
||||
Buffer.from(prefix),
|
||||
Buffer.from("%PDF-1.7\n%"),
|
||||
Buffer.from([0xe2, 0xe3, 0xcf, 0xd3]),
|
||||
Buffer.from("\n"),
|
||||
])
|
||||
expect(Mime.detect(pdf(""))).toBe("application/pdf")
|
||||
expect(Mime.detect(pdf("\r\n"))).toBe("application/pdf")
|
||||
expect(Mime.detect(pdf("x".repeat(1000)))).toBe("application/pdf")
|
||||
expect(Mime.detect(pdf("x".repeat(2000)))).toBe("application/octet-stream")
|
||||
expect(Mime.detect(pdf("\uFEFF"))).toBe("application/pdf")
|
||||
})
|
||||
|
||||
test("leaves containers with a PDF member to the binary fallback", () => {
|
||||
const pdf = Buffer.concat([Buffer.from("%PDF-1.7\n%"), Buffer.from([0xe2, 0xe3, 0xcf, 0xd3]), Buffer.from("\n")])
|
||||
const tar = Buffer.alloc(512)
|
||||
tar.write("doc.pdf")
|
||||
tar.write("0000644\0", 100)
|
||||
tar.write("ustar\0", 257)
|
||||
const zip = Buffer.concat([
|
||||
Buffer.from("504b03040a0000000000" + "00".repeat(16) + "07000000", "hex"),
|
||||
Buffer.from("doc.pdf"),
|
||||
])
|
||||
for (const bytes of [tar, zip]) expect(Mime.detect(Buffer.concat([bytes, pdf]))).toBe("application/octet-stream")
|
||||
})
|
||||
|
||||
test("keeps text mentioning a PDF header as text", () => {
|
||||
for (const text of ["Every PDF starts with %PDF-1.7 on its first line.\n", "header:\n%PDF-2.0\n"])
|
||||
expect(Mime.detect(Buffer.from(text))).toBe("text/plain")
|
||||
for (const text of [
|
||||
"Café notes: %PDF-1.4 header\n",
|
||||
"Notes: %PDF-1.4 header, café\n",
|
||||
"header:\n%PDF-1.4\nrésumé\n",
|
||||
])
|
||||
expect(Mime.detectMedia(Buffer.from(text, "latin1"))).toBeUndefined()
|
||||
})
|
||||
|
||||
test("tells ISO-BMFF brands apart", () => {
|
||||
expect(Mime.detect(ftyp("000000206674797061766966000000004d695072617669666d6961666d696631"))).toBe("image/avif")
|
||||
expect(Mime.detect(ftyp("000000186674797061766973000000006d73663161766973"))).toBe("image/avif")
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue