/** Minimal protobuf wire-format writer/reader (widevine messages) — Uint8Array only (browser-safe). */ export function varint(n) { const out = []; let v = BigInt(n); while (v > 0x7fn) { out.push(Number((v & 0x7fn) | 0x80n)); v >>= 7n; } out.push(Number(v)); return new Uint8Array(out); } export function tag(field, wire) { return varint((field << 3) | wire); } export function pbVarint(field, value) { return concat(tag(field, 0), varint(value)); } export function pbBytes(field, buf) { return concat(tag(field, 2), varint(buf.length), buf); } export function pbString(field, str) { return pbBytes(field, new TextEncoder().encode(str)); } /** Concatenate pre-encoded fields. */ export function pbMsg(...parts) { return concat(...parts); } export function concat(...arrays) { const len = arrays.reduce((n, a) => n + a.length, 0); const out = new Uint8Array(len); let o = 0; for (const a of arrays) { out.set(a, o); o += a.length; } return out; } export function tryParse(buf) { const out = []; let i = 0; while (i < buf.length) { let key = 0, shift = 0; while (true) { if (i >= buf.length) return null; const b = buf[i++]; key |= (b & 0x7f) << shift; if (!(b & 0x80)) break; shift += 7; if (shift > 35) return null; } const field = key >> 3, wire = key & 7; if (field === 0) return null; if (wire === 0) { let v = 0n, s = 0n; while (true) { if (i >= buf.length) return null; const b = buf[i++]; v |= BigInt(b & 0x7f) << s; if (!(b & 0x80)) break; s += 7n; } out.push([field, 0, v]); } else if (wire === 1) { if (i + 8 > buf.length) return null; out.push([field, 1, buf.slice(i, i + 8)]); i += 8; } else if (wire === 2) { let len = 0, sh = 0; while (true) { if (i >= buf.length) return null; const b = buf[i++]; len |= (b & 0x7f) << sh; if (!(b & 0x80)) break; sh += 7; if (sh > 30) return null; } if (i + len > buf.length) return null; out.push([field, 2, buf.slice(i, i + len)]); i += len; } else if (wire === 5) { if (i + 4 > buf.length) return null; out.push([field, 5, buf.slice(i, i + 4)]); i += 4; } else return null; } return out; } /** Get field values: getAll(buf, field) → array of values. */ export function getAll(buf, field) { const fields = tryParse(buf); if (!fields) return []; return fields.filter(([f]) => f === field).map(([, , v]) => v); } export function get(buf, field) { const all = getAll(buf, field); return all.length ? all[0] : undefined; }