/** * Generic browser-side download helper for plain-text files. * * Mirrors `downloadCsv` in `./csv.ts` but takes an explicit MIME type so the * same code path can serve X12 (text/x12), JSON (application/json), or any * other text payload without growing a one-off helper per format. * * The implementation is identical to `downloadCsv` minus the BOM prepending * (we want byte-faithful X12 — prepending a BOM corrupts the ISA segment). * * Safe to call from SSR/Node — guards against a missing `document`. */ export function downloadTextFile( filename: string, mimeType: string, text: string, ): void { if (typeof document === "undefined" || typeof URL === "undefined") return; const blob = new Blob([text], { type: `${mimeType};charset=utf-8` }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; // Some browsers require the link to be in the DOM before .click() works. a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a); // Defer revoke so the browser has the URL handle when the download kicks off. queueMicrotask(() => URL.revokeObjectURL(url)); }