/** * Normalise every input `scan()` accepts into an async stream of chunks, so a * driver only ever sees one shape and nothing is buffered whole that did not * arrive whole. */ /** * What `scan()` accepts. * * - bytes (`Uint8Array`, `Buffer`, `ArrayBuffer`) * - a `Blob` or `File` * - a `ReadableStream`, read chunk by chunk * - a file path, as a string or `{ path }` * - an open file descriptor, as `{ fd }` * * A bare string is a path, never content: encode text with `TextEncoder` to * scan it. */ export type ScanInput = | Uint8Array | ArrayBuffer | Blob | ReadableStream | string | { path: string } | { fd: number } /** Largest frame a driver sends in one piece. clamd reads 4-byte-length frames. */ export const FRAME_BYTES = 64 * 1024 function isReadableStream(value: unknown): value is ReadableStream { return typeof value === 'object' && value !== null && typeof (value as ReadableStream).getReader === 'function' } async function* splitBytes(bytes: Uint8Array): AsyncGenerator { for (let offset = 0; offset < bytes.byteLength; offset += FRAME_BYTES) yield bytes.subarray(offset, Math.min(offset + FRAME_BYTES, bytes.byteLength)) } async function* readStream(stream: ReadableStream): AsyncGenerator { const reader = stream.getReader() let finished = false try { while (true) { const { done, value } = await reader.read() if (done) { finished = true return } if (!value || value.byteLength === 0) continue // A producer may hand over one huge chunk; keep frames small so the // scanner's socket applies back-pressure at a fine grain. if (value.byteLength > FRAME_BYTES) yield* splitBytes(value) else yield value } } finally { // A driver that stops early (a size limit, a dead socket) cancels the // stream, so whoever shares it (a putStream tee) is not left waiting. if (!finished) await reader.cancel().catch(() => {}) reader.releaseLock() } } /** Turn any {@link ScanInput} into chunks no larger than {@link FRAME_BYTES}. */ export function toChunks(input: ScanInput): AsyncIterable { if (input instanceof Uint8Array) return splitBytes(input) if (input instanceof ArrayBuffer) return splitBytes(new Uint8Array(input)) if (isReadableStream(input)) return readStream(input) if (input instanceof Blob) return readStream(input.stream() as ReadableStream) if (typeof input === 'string') return readStream(Bun.file(input).stream() as ReadableStream) if (typeof input === 'object' && input !== null && 'path' in input) return readStream(Bun.file(input.path).stream() as ReadableStream) if (typeof input === 'object' && input !== null && 'fd' in input) return readStream(Bun.file(input.fd).stream() as ReadableStream) throw new TypeError('scan() accepts bytes, a Blob, a ReadableStream, a path or { fd }') }