aztec.ts

11.0 KB · raw

1/**2 * aztec.ts — Aztec 2D barcode generation with round-trip verification.3 *4 * The library has two entry points:5 *   - browser:  `bwip-js` — uses Canvas/OffscreenCanvas for rasterization6 *   - node:     `bwip-js/node` — uses zlib-PNG, returns a Buffer directly7 *8 * We resolve which one to use at runtime so the popup (browser context) and9 * vitest (node context) both work without any build-time conditional. The10 * resolved module is cached because importing parses ~500KB of generated JS.11 *12 * Round-trip verification: every generated Aztec is decoded back via @zxing13 * and the decoded text is compared byte-for-byte with the original envelope14 * JSON. Without the round-trip we have no proof that what we printed is15 * actually readable. In the popup the decode runs through OffscreenCanvas.16 * In a pure node test environment OffscreenCanvas is unavailable, so we17 * fall back to a no-op verification — the generation tests for that path18 * cover the encoder via separate code paths.19 */2021import {22  BarcodeFormat,23  BinaryBitmap,24  DecodeHintType,25  HybridBinarizer,26  MultiFormatReader,27  RGBLuminanceSource,28} from "@zxing/library";29import {30  AZTEC_ECC_PERCENT,31  CodexError,32  type ChunkEnvelope,33} from "../../shared/codex-types";3435export interface AztecImage {36  pngBytes: Uint8Array;37  width: number;38  height: number;39}4041// ── bwip-js loader ───────────────────────────────────────────────────────────4243/**44 * In browser builds the popup bundler resolves `bwip-js` to the browser entry45 * which exports `toCanvas`. In node (vitest) we want `bwip-js/node` which46 * exports `toBuffer`. We can't import both unconditionally — node can't load47 * the browser entry's canvas code, and the browser can't load `node:zlib`.48 *49 * The detection is "do we have a working OffscreenCanvas?" rather than50 * "is `process` defined?" because the popup runs in an MV3 worker context51 * where some Node globals leak via polyfills.52 */53interface BwipBrowserModule {54  toCanvas: (55    canvas: OffscreenCanvas | HTMLCanvasElement,56    opts: Record<string, unknown>,57  ) => OffscreenCanvas | HTMLCanvasElement;58}5960interface BwipNodeModule {61  toBuffer: (opts: Record<string, unknown>) => Promise<Buffer>;62}6364let cachedBwip: BwipBrowserModule | BwipNodeModule | null = null;65let cachedIsBrowser: boolean | null = null;6667async function loadBwip(): Promise<{68  mod: BwipBrowserModule | BwipNodeModule;69  isBrowser: boolean;70}> {71  if (cachedBwip && cachedIsBrowser !== null) {72    return { mod: cachedBwip, isBrowser: cachedIsBrowser };73  }74  const isBrowser = typeof OffscreenCanvas !== "undefined";7576  // Pick the entrypoint explicitly. Vite (and therefore vitest) tends to77  // resolve the bare `bwip-js` specifier against the package's browser export78  // condition even when running under node — so we route node test runs79  // through `bwip-js/node` directly, which gives us the toBuffer-shaped API.80  const spec = isBrowser ? "bwip-js" : "bwip-js" + "/node";81  const ns = (await import(/* @vite-ignore */ spec)) as Record<string, unknown>;82  const defaultExport = ns["default"] as Record<string, unknown> | undefined;83  // ESM dynamic import surface differs between the two builds: the browser84  // bundle exports `toCanvas` as a named export, while the node bundle is85  // CJS-shaped and exposes `toBuffer` on `default`. Merge both so callers86  // can use either method without caring which path resolved.87  const merged = { ...(defaultExport ?? {}), ...ns } as Record<string, unknown>;88  const resolved = merged as unknown as BwipBrowserModule | BwipNodeModule;89  cachedBwip = resolved;90  cachedIsBrowser = isBrowser;91  return { mod: resolved, isBrowser };92}9394// ── Aztec PNG generation ────────────────────────────────────────────────────9596/**97 * Render an Aztec barcode at 25% ECC and return its PNG bytes. The PNG is98 * intentionally monochrome at scale 4 — that's the smallest scale that still99 * looks crisp at print resolution while keeping per-code rendering well under100 * 100ms on modest hardware.101 */102export async function generateAztecPng(payload: string): Promise<AztecImage> {103  const { mod, isBrowser } = await loadBwip();104  const opts = {105    bcid: "azteccode",106    text: payload,107    eclevel: AZTEC_ECC_PERCENT.toString(),108    scale: 4,109    // padding: 2 adds 8px (2 modules at scale 4) of quiet zone on each side.110    // ZXing's finder pattern search fails when the code is flush against the111    // image edge with no quiet zone, causing spurious AZTEC_ROUNDTRIP_FAILED.112    padding: 2,113    monochrome: true,114  } as const;115116  try {117    if (isBrowser) {118      const canvas = new OffscreenCanvas(1, 1);119      const drawn = (mod as BwipBrowserModule).toCanvas(canvas, opts);120      const out = drawn as OffscreenCanvas;121      const blob = await out.convertToBlob({ type: "image/png" });122      const pngBytes = new Uint8Array(await blob.arrayBuffer());123      return { pngBytes, width: out.width, height: out.height };124    }125126    const buf = await (mod as BwipNodeModule).toBuffer(opts);127    const pngBytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).slice();128    const { width, height } = readPngDimensions(pngBytes);129    return { pngBytes, width, height };130  } catch (err) {131    throw new CodexError(132      "AZTEC_GENERATION_FAILED",133      `Aztec render failed: ${err instanceof Error ? err.message : String(err)}`,134    );135  }136}137138/** Read a PNG's IHDR width/height. PNGs always have IHDR as the first chunk. */139function readPngDimensions(png: Uint8Array): { width: number; height: number } {140  // PNG signature: 8 bytes, then 4-byte chunk length, "IHDR", then width/height as big-endian uint32.141  if (png.length < 24) {142    throw new CodexError("AZTEC_GENERATION_FAILED", "PNG buffer too small to contain IHDR");143  }144  const view = new DataView(png.buffer, png.byteOffset, png.byteLength);145  const width = view.getUint32(16, false);146  const height = view.getUint32(20, false);147  return { width, height };148}149150// ── Aztec PNG decoding (round-trip) ─────────────────────────────────────────151152/**153 * Decode an Aztec PNG via @zxing. Returns the decoded UTF-8 text, or `null`154 * if decoding fails for any reason (no DOM, malformed PNG, no match found).155 * Never throws — the caller decides whether a `null` result is a verification156 * failure or a deliberate skip.157 */158export async function decodeAztecFromPng(pngBytes: Uint8Array): Promise<string | null> {159  // The decoder needs raw pixel data, which means we need a canvas to160  // rasterize the PNG into ImageData. Skip the round-trip in environments161  // without OffscreenCanvas (vitest with environment: 'node').162  if (typeof OffscreenCanvas === "undefined" || typeof createImageBitmap === "undefined") {163    return null;164  }165166  try {167    // Copy into a fresh ArrayBuffer-backed view so Blob's typing is satisfied168    // (the input Uint8Array may be backed by a SharedArrayBuffer in some169    // bundler typings, which Blob's BlobPart union rejects).170    const owned = new Uint8Array(pngBytes.byteLength);171    owned.set(pngBytes);172    const blob = new Blob([owned], { type: "image/png" });173    const bitmap = await createImageBitmap(blob);174    const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);175    const ctx = canvas.getContext("2d");176    if (!ctx) return null;177    // White-fill before drawing so any transparent pixels in the PNG178    // composite to white rather than (0,0,0,0). Transparent pixels get179    // packed as 0xFF000000 (black) in the ARGB array, which would make180    // the quiet-zone border appear black and confuse ZXing.181    ctx.fillStyle = "#ffffff";182    ctx.fillRect(0, 0, bitmap.width, bitmap.height);183    ctx.drawImage(bitmap, 0, 0);184    const imageData = ctx.getImageData(0, 0, bitmap.width, bitmap.height);185186    // RGBLuminanceSource wants packed 32-bit ARGB values, not raw Uint8 RGBA.187    const argb = new Int32Array(bitmap.width * bitmap.height);188    const raw = imageData.data;189    for (let i = 0, j = 0; i < raw.length; i += 4, j++) {190      argb[j] = (0xff << 24) | (raw[i]! << 16) | (raw[i + 1]! << 8) | raw[i + 2]!;191    }192193    const source = new RGBLuminanceSource(argb, bitmap.width, bitmap.height);194    const binarizer = new HybridBinarizer(source);195    const bitmapBinary = new BinaryBitmap(binarizer);196197    const reader = new MultiFormatReader();198    const hints = new Map();199    hints.set(DecodeHintType.POSSIBLE_FORMATS, [BarcodeFormat.AZTEC]);200    hints.set(DecodeHintType.TRY_HARDER, true);201    reader.setHints(hints);202203    const result = reader.decode(bitmapBinary);204    return result.getText();205  } catch {206    return null;207  }208}209210// ── Verified Aztec generation ───────────────────────────────────────────────211212/**213 * Generate the Aztec code for one envelope and confirm it round-trips. The214 * envelope JSON is serialized once and reused as the decode target so any215 * encoding mismatch (e.g. UTF-8 surrogate corruption) is caught immediately.216 *217 * In environments where round-trip decoding is unavailable (vitest node), the218 * verification step is skipped — the generator still throws on encoder219 * failure, which is the only condition this path can detect without a DOM.220 */221export async function generateVerifiedAztec(envelope: ChunkEnvelope): Promise<AztecImage> {222  const envelopeJson = JSON.stringify(envelope);223224  let image: AztecImage;225  try {226    image = await generateAztecPng(envelopeJson);227  } catch (err) {228    if (err instanceof CodexError) throw err;229    throw new CodexError(230      "AZTEC_GENERATION_FAILED",231      `Failed to generate Aztec code for chunk ${envelope.i}: ${err instanceof Error ? err.message : String(err)}`,232    );233  }234235  if (!image.pngBytes || image.pngBytes.length < 32) {236    throw new CodexError(237      "AZTEC_GENERATION_FAILED",238      `Aztec PNG for chunk ${envelope.i} was empty`,239    );240  }241242  // Skip round-trip when we can't rasterize — see decodeAztecFromPng().243  if (typeof OffscreenCanvas === "undefined" || typeof createImageBitmap === "undefined") {244    return image;245  }246247  // @zxing occasionally returns null on a valid barcode due to transient248  // rasterisation issues. Five attempts avoids aborting a full Codex build249  // for a momentary DOM hiccup. Content-mismatch is never retried.250  let decoded: string | null = null;251  for (let attempt = 0; attempt < 5; attempt++) {252    decoded = await decodeAztecFromPng(image.pngBytes);253    if (decoded !== null) break;254  }255  if (decoded === null) {256    throw new CodexError(257      "AZTEC_ROUNDTRIP_FAILED",258      `Chunk ${envelope.i} generated but cannot be decoded back after 3 attempts. This Codex cannot be trusted.`,259    );260  }261  if (decoded !== envelopeJson) {262    throw new CodexError(263      "AZTEC_CONTENT_MISMATCH",264      `Chunk ${envelope.i} decoded content does not match original envelope. Possible encoding corruption.`,265    );266  }267  return image;268}