/**
 * dataurl.ts — Encode/decode data: URLs
 * Zero deps (uses Buffer for base64).
 *
 * decode("data:text/plain;base64,aGVsbG8=") → "hello"
 * encode("text/plain", buf) → "data:text/plain;base64,aGVsbG8="
 * parse("data:text/plain;base64,aGVsbG8=") → { mime: "text/plain", base64: "aGVsbG8=" }
 */
export function decode(url: string): string {
  const i = url.indexOf(",")
  if (i === -1) return ""
  const head = url.slice(0, i)
  const body = url.slice(i + 1)
  if (head.includes(";base64")) return Buffer.from(body, "base64").toString("utf8")
  return decodeURIComponent(body)
}

export function encode(mime: string, data: string | ArrayBuffer | Uint8Array): string {
  const base64 = typeof data === "string"
    ? Buffer.from(data).toString("base64")
    : Buffer.from(data instanceof Uint8Array ? data : new Uint8Array(data)).toString("base64")
  return `data:${mime};base64,${base64}`
}

export function parse(url: string): { mime: string; base64: string; data: string } | undefined {
  const match = url.match(/^data:([^;]+);base64,(.*)$/)
  if (!match) return undefined
  return { mime: match[1], base64: match[2], data: decode(url) }
}
