Repository Public
1// Export : assemblage d'un fichier mbox (variante mboxrd) ou d'une archive ZIP de fichiers .eml, entièrement côté client.23export interface RawMessage {4 /** octets du message RFC 5322 tel que stocké */5 data: Uint8Array6 /** adresse de l'expéditeur pour la ligne « From » d'enveloppe */7 sender: string8 date: Date9 /** nom de fichier souhaité dans l'archive ZIP */10 name?: string11}1213const enc = new TextEncoder()14const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]15const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]1617/** Date au format asctime (UTC), exigé par la ligne de séparation mbox. */18export function asctime(d: Date): string {19 const p = (n: number) => String(n).padStart(2, "0")20 return `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${String(d.getUTCDate()).padStart(2, " ")} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())} ${d.getUTCFullYear()}`21}2223/** mboxrd : toute ligne du corps qui commence par « From » précédé de zéro ou plusieurs « > » reçoit un « > » de plus. */24export function escapeFromLines(data: Uint8Array): Uint8Array {25 const F = 0x46, R = 0x72, O = 0x6f, M = 0x6d, SP = 0x20, GT = 0x3e, LF = 0x0a26 const inserts: number[] = []27 let lineStart = 028 for (let i = 0; i <= data.length; i++) {29 if (i === data.length || data[i] === LF) {30 let j = lineStart31 while (j < i && data[j] === GT) j++32 if (i - j >= 5 && data[j] === F && data[j + 1] === R && data[j + 2] === O && data[j + 3] === M && data[j + 4] === SP) inserts.push(lineStart)33 lineStart = i + 134 }35 }36 if (!inserts.length) return data37 const out = new Uint8Array(data.length + inserts.length)38 let src = 039 let dst = 040 for (const at of inserts) {41 out.set(data.subarray(src, at), dst)42 dst += at - src43 out[dst++] = GT44 src = at45 }46 out.set(data.subarray(src), dst)47 return out48}4950/** Rend les morceaux d'un fichier mbox (à passer tels quels à `new Blob(parts)`). */51export function buildMbox(messages: RawMessage[]): Uint8Array[] {52 const parts: Uint8Array[] = []53 for (const m of messages) {54 const sender = m.sender.replace(/[\s<>]/g, "") || "MAILER-DAEMON"55 parts.push(enc.encode(`From ${sender} ${asctime(m.date)}\n`))56 const body = escapeFromLines(m.data)57 parts.push(body)58 parts.push(enc.encode(body.length && body[body.length - 1] === 0x0a ? "\n" : "\n\n"))59 }60 return parts61}6263// ---------------------------------------------------------------- ZIP (méthode « stored », sans compression)6465let crcTable: Uint32Array | undefined66export function crc32(data: Uint8Array): number {67 if (!crcTable) {68 crcTable = new Uint32Array(256)69 for (let n = 0; n < 256; n++) {70 let c = n71 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 172 crcTable[n] = c >>> 073 }74 }75 let crc = 0xffffffff76 for (let i = 0; i < data.length; i++) crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8)77 return (crc ^ 0xffffffff) >>> 078}7980function dosTime(d: Date): { time: number; date: number } {81 const y = Math.max(1980, d.getFullYear())82 return { time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1), date: ((y - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate() }83}8485/** Noms uniques et sûrs dans l'archive. */86export function uniqueNames(names: string[]): string[] {87 const seen = new Map<string, number>()88 return names.map((raw) => {89 const clean = raw.replace(/[\u0000-\u001f\u007f/\\:*?"<>|]/g, "_").replace(/^\.+/, "_").trim().slice(0, 120) || "message"90 const dot = clean.lastIndexOf(".")91 const [stem, ext] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""]92 const key = clean.toLowerCase()93 const n = seen.get(key) ?? 094 seen.set(key, n + 1)95 return n === 0 ? clean : `${stem} (${n + 1})${ext}`96 })97}9899/** Archive ZIP sans compression (limite classique : 4 Go et 65 535 entrées, largement suffisante pour un dossier). */100export function buildZip(files: { name: string; data: Uint8Array; date: Date }[]): Uint8Array[] {101 if (files.length > 0xffff) throw new Error("too many files for a zip archive")102 const parts: Uint8Array[] = []103 const central: Uint8Array[] = []104 let offset = 0105 const names = uniqueNames(files.map((f) => f.name))106 files.forEach((f, i) => {107 const name = enc.encode(names[i])108 const crc = crc32(f.data)109 const { time, date } = dosTime(f.date)110 const local = new DataView(new ArrayBuffer(30))111 local.setUint32(0, 0x04034b50, true)112 local.setUint16(4, 20, true)113 local.setUint16(6, 0x0800, true) // noms en UTF-8114 local.setUint16(8, 0, true)115 local.setUint16(10, time, true)116 local.setUint16(12, date, true)117 local.setUint32(14, crc, true)118 local.setUint32(18, f.data.length, true)119 local.setUint32(22, f.data.length, true)120 local.setUint16(26, name.length, true)121 local.setUint16(28, 0, true)122 parts.push(new Uint8Array(local.buffer), name, f.data)123 const cd = new DataView(new ArrayBuffer(46))124 cd.setUint32(0, 0x02014b50, true)125 cd.setUint16(4, 20, true)126 cd.setUint16(6, 20, true)127 cd.setUint16(8, 0x0800, true)128 cd.setUint16(10, 0, true)129 cd.setUint16(12, time, true)130 cd.setUint16(14, date, true)131 cd.setUint32(16, crc, true)132 cd.setUint32(20, f.data.length, true)133 cd.setUint32(24, f.data.length, true)134 cd.setUint16(28, name.length, true)135 cd.setUint32(42, offset, true)136 central.push(new Uint8Array(cd.buffer), name)137 offset += 30 + name.length + f.data.length138 })139 if (offset > 0xffffffff) throw new Error("archive too large")140 const cdSize = central.reduce((n, p) => n + p.length, 0)141 const end = new DataView(new ArrayBuffer(22))142 end.setUint32(0, 0x06054b50, true)143 end.setUint16(8, files.length, true)144 end.setUint16(10, files.length, true)145 end.setUint32(12, cdSize, true)146 end.setUint32(16, offset, true)147 return [...parts, ...central, new Uint8Array(end.buffer)]148}149