// A file as a Response, runtime-neutral (the serve seam's helpers, // docs/contributing/architecture.md#the-serve-seam): what `new Response(Bun.file(path), init)` answered — the bytes, a content type from // the extension unless `init` names one, a 404 when the file is not there. import { existsSync, readFileSync, statSync } from 'node:fs'; const TYPES: Record = { html: 'text/html; charset=utf-8', css: 'text/css; charset=utf-8', js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8', json: 'application/json', map: 'application/json', txt: 'text/plain; charset=utf-8', md: 'text/markdown; charset=utf-8', csv: 'text/csv; charset=utf-8', xml: 'application/xml', png: 'image/png', gif: 'image/gif', jpg: 'image/jpeg', jpeg: 'image/jpeg', svg: 'image/svg+xml', webp: 'image/webp', ico: 'image/x-icon', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', wasm: 'application/wasm', pdf: 'application/pdf', mp3: 'audio/mpeg', mp4: 'video/mp4', wav: 'audio/wav', }; /** The content type a file's extension implies; `application/octet-stream` for the rest. */ export function contentTypeOf(path: string): string { return TYPES[path.slice(path.lastIndexOf('.') + 1).toLowerCase()] ?? 'application/octet-stream'; } export function fileResponse(path: string, init?: ResponseInit): Response { if (!existsSync(path) || !statSync(path).isFile()) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } }); const headers = new Headers(init?.headers); if (!headers.has('content-type')) headers.set('content-type', contentTypeOf(path)); return new Response(readFileSync(path), { ...init, headers }); } /** * Stored bytes as a response, honouring a single `Range: bytes=` as RFC 9110 §14 has it: every satisfiable range is a * 206 with its Content-Range, `bytes=0-` (the whole body) included; a range that does not parse, a first-byte-pos past * its last-byte-pos (`bytes=5-2`) included, is ignored and the whole body is a 200; a well-formed range that starts past * the end (any range of an empty body) is a 416. Lazy sources supply inclusive ranges and stream in bounded reads. * `nosniff` stops a browser second-guessing the content type the vendor gave. */ export function bytesResponse( request: Request, bytes: Uint8Array | { size: number; range(start: number, end: number): Promise }, contentType: string, cacheControl = 'public, max-age=604800, immutable', ): Response { const total = bytes instanceof Uint8Array ? bytes.length : bytes.size; const base = { 'content-type': contentType, 'x-content-type-options': 'nosniff', 'accept-ranges': 'bytes', 'cache-control': cacheControl }; const range = /^bytes=(\d*)-(\d*)$/.exec((request.headers.get('range') ?? '').trim()); let start = 0; let end = total - 1; const valid = range !== null && (range[1] !== '' || range[2] !== '') && !(range[1] !== '' && range[2] !== '' && BigInt(range[1]) > BigInt(range[2])); if (valid) { if (range[1] === '') { start = Math.max(0, total - Number(range[2])); } else { start = Number(range[1]); end = range[2] === '' ? total - 1 : Math.min(Number(range[2]), total - 1); } if (start >= total || (range[1] === '' && Number(range[2]) === 0)) return new Response(null, { status: 416, headers: { ...base, 'content-range': `bytes */${total}` } }); } // every satisfiable range is answered as one, the whole body's `bytes=0-` included: a media player (Safari's) reads a // 206 with its Content-Range as the server taking ranges, and a 200 as one it cannot seek in const partial = valid; let body: BodyInit | null = null; if (request.method !== 'HEAD') { if (bytes instanceof Uint8Array) body = new Blob([bytes.slice(start, end + 1)]); else { let at = start; body = new ReadableStream({ async pull(controller) { if (at > end) { controller.close(); return; } const last = Math.min(at + 8 * 1024 * 1024 - 1, end); const chunk = await bytes.range(at, last); if (!chunk) { controller.error(new Error('stored bytes are gone')); return; } controller.enqueue(chunk); at = last + 1; }, }); } } return new Response(body, { status: partial ? 206 : 200, headers: { ...base, 'content-length': String(end + 1 - start), ...(partial ? { 'content-range': `bytes ${start}-${end}/${total}` } : {}) }, }); }