/** * Encodes uncompressed binary BLK answers and decodes request bodies for the char service. * The traffic log records the detected body format and its readable representation. */ import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk'; import { markUncompressed, unpackMarked } from './compression-marker.ts'; import { describePbbdForLog, isPbbdStream } from './pbbd-stream.ts'; export function encodeDataAnswer(blk: BlkBlock): Uint8Array { return markUncompressed(encodeBlk(blk)); } export interface DecodedPayload { /** How the body was laid out, for the traffic log. */ readonly form: string; readonly blk?: BlkBlock; /** Readable rendering for the traffic log. */ readonly text: string; } const BINARY_BLK_LABELS = new Set([1, 2, 3, 6]); export function decodeRequestPayload(body: Uint8Array): DecodedPayload { if (body.length === 0) return { form: 'empty', text: '' }; try { if (isPbbdStream(body)) { return { form: 'PBBD stream', text: describePbbdForLog(body) }; } const marked = unpackMarked(body); if (marked) { if (!marked.data) return { form: `marked ${marked.method}, not unpacked`, text: '' }; return describeBlk(`marked ${marked.method}`, marked.data); } if (BINARY_BLK_LABELS.has(body[0]!)) return describeBlk('bare binary BLK', body); } catch (error) { return { form: `undecodable (${(error as Error).message})`, text: '' }; } return { form: 'text', text: Buffer.from(body).toString('utf8') }; } function describeBlk(form: string, bytes: Uint8Array): DecodedPayload { const blk = decodeBlk(bytes); return { form, blk, text: formatBlkText(blk) }; }