UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

86 lines (85 loc) • 2.52 kB
//#region packages/media-core/src/base64.ts /** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */ function estimateBase64DecodedBytes(e) { let t = e.length; const n = e.search(/[\x00-\x20]/); if (n !== -1) { for (let r = n; r < e.length; r += 1) if (e.charCodeAt(r) <= 32) t -= 1; } if (t === 0) return 0; let r = 0; let i = e.length - 1; while (i >= 0 && e.charCodeAt(i) <= 32) i -= 1; if (i >= 0 && e[i] === "=") { r = 1; i -= 1; while (i >= 0 && e.charCodeAt(i) <= 32) i -= 1; if (i >= 0 && e[i] === "=") r = 2; } const a = Math.floor(t * 3 / 4) - r; return Math.max(0, a); } /** Validates the attachment dialect: padded, no whitespace, nonzero pad bits allowed. */ function isValidBase64(e) { return inspectBase64(e, "attachment") !== void 0; } function base64DataValue(e) { if (e >= 65 && e <= 90) return e - 65; if (e >= 97 && e <= 122) return e - 97 + 26; if (e >= 48 && e <= 57) return e - 48 + 52; return e === 43 ? 62 : e === 47 ? 63 : -1; } /** * Normalizes and validates a base64 string, returning canonical no-whitespace * base64 only when the input has valid alphabet, padding, and length. */ function canonicalizeBase64(e) { const t = inspectBase64(e, "canonical"); return t?.canonicalPadBits ? t.base64 : void 0; } /** One validating pass for the canonical and strict attachment dialects. */ function inspectBase64(e, t) { if (t === "attachment" && (e.length === 0 || e.length % 4 !== 0)) return; let n; let r = 0; let i = 0; let a = 0; for (let o = 0; o < e.length; o += 1) { const s = e.charCodeAt(o); if (s <= 32) { if (t === "attachment") return; if (n === void 0) { n = Buffer.allocUnsafe(e.length - 1); for (let t = 0; t < o; t += 1) n[t] = e.charCodeAt(t); r = o; } continue; } if (s === 61) { i += 1; if (i > 2) return; } else { const e = base64DataValue(s); if (i > 0 || e < 0) return; a = e; } if (n !== void 0) { n[r] = s; r += 1; } } const o = n === void 0 ? e.length : r; if (o === 0) return; const s = o % 4; if (s !== 0 && (i > 0 || s === 1)) return; const c = s === 0 ? i : 4 - s; const l = c === 2 ? 15 : c === 1 ? 3 : 0; const u = n === void 0 ? e : n.subarray(0, r).toString("latin1"); return { base64: s === 0 ? u : u + "=".repeat(4 - s), decodedBytes: Math.floor(o * 3 / 4) - i, canonicalPadBits: (a & l) === 0 }; } //#endregion export { isValidBase64 as i, estimateBase64DecodedBytes as n, inspectBase64 as r, canonicalizeBase64 as t };