# @forgesworn/qr 0.3.14 Canonical documentation: https://forgesworn.github.io/qr/ Generated from the versioned repository documents. # @forgesworn/qr Make and read QR codes in TypeScript, with no dependencies. One small package encodes text or bytes into a symbol, renders it as SVG, canvas or terminal text, and decodes symbols from camera frames, screenshots and photographs. It runs in browsers, workers and Node. ```ts import { decode, encode, toSvg } from '@forgesworn/qr' const svg = toSvg(encode('https://example.com/')) // make one const text = decode(ctx.getImageData(0, 0, w, h))?.text // read one ``` - **Encoder:** versions 1-40, levels L/M/Q/H, and the smallest symbol for your text: numeric, alphanumeric and byte segments are mixed where that saves bits. - **Renderers:** an SVG string, any canvas, or half-block text for a terminal. - **Decoder:** takes RGBA or greyscale pixels and reads codes that are rotated, tilted, mirrored, light on dark, curved or close up. It returns the text, the raw bytes and where the code is. - **Careful by design:** the decoder is built to return nothing rather than a wrong text, which matters for payment links and sign-in codes. - **Small and plain:** no runtime dependencies, ESM with types, tree shaking. WebAssembly is available through a separate optional import. - **Portable:** Kotlin and Rust ports are in this repository, checked against the same vectors, and [SPEC.md](https://github.com/forgesworn/qr/blob/main/SPEC.md) with [test vectors](https://github.com/forgesworn/qr/blob/main/vectors/README.md) lets other languages match it exactly. [Documentation](https://forgesworn.github.io/qr/) · [npm](https://www.npmjs.com/package/@forgesworn/qr) · [Releases](https://github.com/forgesworn/qr/releases) · [Choosing QR](https://github.com/forgesworn/qr/blob/main/docs/CHOOSING.md) Native Rust: [`forgesworn-qr`](https://crates.io/crates/forgesworn-qr) · [Rust API docs](https://docs.rs/forgesworn-qr) · [Rust guide](https://github.com/forgesworn/qr/blob/main/rust/README.md) [JSR](https://jsr.io/@forgesworn/qr) · [Kotlin on Maven Central](https://central.sonatype.com/artifact/io.github.forgesworn/qr) ## Why use it? Generate and read codes with the same typed package, process frames locally, and choose your own camera UI. The optional WASM backend and tracked sessions help with repeated frames; the plain TypeScript entry needs no WASM setup. Accuracy takes priority: speed changes must preserve successful regression reads and must not introduce incorrect payloads. The recorded photograph comparison reads **180/184 versus ZXing-WASM's 171/184**, and the positive stress set reads **172/224 versus 150/224**. Version 0.3.14's qualified curved-image comparison reads **861/1,376 versus 646/1,376**, adding 143 exact reads over 0.3.13 while preserving earlier successful results. This includes **118/256 versus 77/256** on a separate synthetic set frozen before evaluation. ZXing still reads 14 curved frames QR misses, and is faster on the recorded random-noise workload. These finite sets do not prove superiority on every image or camera. See [choosing a library](https://github.com/forgesworn/qr/blob/main/docs/CHOOSING.md) for trade-offs and [reproducible evidence](https://github.com/forgesworn/qr/blob/main/benchmarks/2026-11-17-m4/quadratic-mesh-recovery/README.md). ## Contents - [Install](https://github.com/forgesworn/qr/blob/main/README.md#install) - [Recipes: making codes](https://github.com/forgesworn/qr/blob/main/README.md#recipes-making-codes) - [Recipes: reading codes](https://github.com/forgesworn/qr/blob/main/README.md#recipes-reading-codes) - [API](https://github.com/forgesworn/qr/blob/main/README.md#api) - [Common mistakes](https://github.com/forgesworn/qr/blob/main/README.md#common-mistakes) - [Migrating from another library](https://github.com/forgesworn/qr/blob/main/README.md#migrating-from-another-library) - [How the decoder works](https://github.com/forgesworn/qr/blob/main/README.md#how-the-decoder-works) - [How it is tested](https://github.com/forgesworn/qr/blob/main/README.md#how-it-is-tested) - [Kotlin](https://github.com/forgesworn/qr/blob/main/README.md#kotlin) - [Rust and WebAssembly](https://github.com/forgesworn/qr/blob/main/README.md#rust-and-webassembly) - [Development](https://github.com/forgesworn/qr/blob/main/README.md#development) ## Install ```bash npm install @forgesworn/qr ``` ESM only (`import`, not `require`). Node.js 22.13 or later, or any browser with ES2022 modules. Types are included. The API is still pre-1.0, so pin the version; changes are listed in [CHANGELOG.md](https://github.com/forgesworn/qr/blob/main/CHANGELOG.md). JSR uses the same TypeScript API, including the optional WASM entry point: ```ts import { encode, toSvg } from 'jsr:@forgesworn/qr@0.3.14' import { loadWasm, wasmUrl } from 'jsr:@forgesworn/qr@0.3.14/wasm' ``` For Deno projects, `deno add jsr:@forgesworn/qr@0.3.14` adds the package to your configuration. Continue to use npm for the ordinary Node/bundler installation. See [distribution](https://github.com/forgesworn/qr/blob/main/docs/DISTRIBUTION.md) for registry publication status and verification. ## Recipes: making codes The recipes show the imports and operations needed for each integration. Browser examples assume the named elements exist in your page. `encode` is synchronous and returns a plain object; the renderers turn that object into something to show. ### An SVG in the page ```ts import { encode, toSvg } from '@forgesworn/qr' const qr = encode('https://example.com/') const svg = toSvg(qr, { title: 'Link to example.com' }) document.querySelector('#qr')!.innerHTML = svg ``` The SVG has a `viewBox` and no fixed size, so it fills its container: size it with CSS. `title` becomes the accessible name. As an image source: ```ts import { encode, toSvg } from '@forgesworn/qr' const img = document.querySelector('img')! img.src = 'data:image/svg+xml;utf8,' + encodeURIComponent(toSvg(encode('https://example.com/'))) ``` ### A canvas, and a PNG to download ```ts import { drawCanvas, encode } from '@forgesworn/qr' const canvas = document.querySelector('canvas')! drawCanvas(canvas, encode('https://example.com/'), { width: 512 }) canvas.toBlob((png) => { if (!png) return const link = document.createElement('a') link.href = URL.createObjectURL(png) link.download = 'code.png' link.click() setTimeout(() => URL.revokeObjectURL(link.href), 0) }) ``` `drawCanvas` resizes the canvas to exactly `width` pixels square and puts module edges on whole pixels. `width` must be a whole number of at least one pixel a module, margin included, or it throws a `RangeError`. It takes an `OffscreenCanvas` too. ### A terminal, or a file, from Node ```ts import { writeFileSync } from 'node:fs' import { encode, toSvg, toTerminal } from '@forgesworn/qr' const qr = encode('https://example.com/') console.log(toTerminal(qr)) // dark terminal; { ink: 'dark' } for a light one writeFileSync('code.svg', toSvg(qr)) ``` ### Colours, margin and error correction ```ts import { encode, toSvg } from '@forgesworn/qr' const qr = encode('https://example.com/', { ecc: 'H' }) // 'L' | 'M' (default) | 'Q' | 'H' const svg = toSvg(qr, { dark: '#1a1a2e', light: null, margin: 2 }) // light: null leaves the background clear ``` A higher level survives more damage and makes a larger symbol. Keep the `margin` at 4 modules unless the code sits on a plain background already; readers need the quiet zone. ### Your own drawing `modules` is a row-by-row `Uint8Array` of `size * size` entries, 1 for dark, with no quiet zone. `isDark(qr, x, y)` reads it, and is `false` outside the symbol. ```ts import { encode, isDark } from '@forgesworn/qr' const qr = encode('https://example.com/') let dots = '' for (let y = 0; y < qr.size; y++) { for (let x = 0; x < qr.size; x++) { if (isDark(qr, x, y)) dots += `` } } const svg = `${dots}` ``` ### The smallest code for a payment link With no `mode`, text is split into the segments that take the fewest bits. An uppercase body after a lowercase scheme packs as alphanumeric, so it fits a smaller symbol than it would as bytes. ```ts import { encode } from '@forgesworn/qr' const invoice = 'lightning:LNBC' + '0123456789ACDEFGHJKLMNPQRSTUVWXYZ'.repeat(8) // 278 characters, made up const qr = encode(invoice) qr.segments // [{ mode: 'byte', count: 9 }, { mode: 'alphanumeric', count: 269 }] qr.version // 10, 57 modules a side; as bytes it would be version 12, 65 a side ``` ### Bytes, not text ```ts import { encode } from '@forgesworn/qr' const qr = encode(new Uint8Array([0xde, 0xad, 0xbe, 0xef])) // always one byte segment ``` ### When the data does not fit ```ts import { encode, QrCapacityError, type ErrorCorrection, type QrCode } from '@forgesworn/qr' /** The most robust code that still fits, or undefined if none does. */ function fit(text: string): QrCode | undefined { for (const ecc of ['H', 'Q', 'M', 'L'] as ErrorCorrection[]) { try { return encode(text, { ecc }) } catch (error) { if (!(error instanceof QrCapacityError)) throw error } } return undefined } ``` `QrCapacityError` extends `RangeError`. Bad options (a version outside 1-40, an unknown level) throw a plain `RangeError`, and data that is neither a string nor a `Uint8Array` throws a `TypeError`. ## Recipes: reading codes `decode` takes pixels, not an element: `{ data, width, height }` with RGBA (what a canvas gives) or one grey byte a pixel. It returns the result, or `undefined` when it finds no code it is sure of. It manages no camera; the loop below is all there is to it. ### Scan with the camera ```ts import { decode } from '@forgesworn/qr' /** Starts scanning; calls `onRead` once with the first code read. Returns a function that stops the camera. */ async function scan(video: HTMLVideoElement, onRead: (text: string) => void): Promise<() => void> { const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }) video.srcObject = stream video.playsInline = true try { await video.play() } catch (error) { for (const track of stream.getTracks()) track.stop() video.srcObject = null throw error } const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d', { willReadFrequently: true })! let running = true let last = 0 const stop = () => { running = false for (const track of stream.getTracks()) track.stop() if (video.srcObject === stream) video.srcObject = null } const tick = (now: number) => { if (!running) return if (now - last >= 100 && video.videoWidth > 0) { // ten looks a second is plenty last = now canvas.width = video.videoWidth canvas.height = video.videoHeight ctx.drawImage(video, 0, 0) const found = decode(ctx.getImageData(0, 0, canvas.width, canvas.height)) if (found) { stop() onRead(found.text) return } } requestAnimationFrame(tick) } requestAnimationFrame(tick) return stop } const stop = await scan(document.querySelector('video')!, (text) => console.log(text)) ``` Cameras need a secure page (HTTPS or localhost) and the user's permission. Start with a bounded frame size such as 1280×720 and measure on your devices. Small or distant codes may need more resolution; larger frames cost more time and memory. Use a worker for decoding when page responsiveness matters. ### Read an uploaded picture or a screenshot ```ts import { decode } from '@forgesworn/qr' async function readFile(file: Blob): Promise { const bitmap = await createImageBitmap(file) try { const canvas = new OffscreenCanvas(bitmap.width, bitmap.height) const ctx = canvas.getContext('2d')! ctx.drawImage(bitmap, 0, 0) return decode(ctx.getImageData(0, 0, bitmap.width, bitmap.height))?.text } finally { bitmap.close() } } document.querySelector('input[type=file]')!.addEventListener('change', async (event) => { const file = (event.target as HTMLInputElement).files?.[0] if (file) console.log((await readFile(file)) ?? 'no code found') }) ``` ### Keep the page smooth: decode in a worker ```ts // main.ts const worker = new Worker(new URL('./scan-worker.ts', import.meta.url), { type: 'module' }) worker.onmessage = (event: MessageEvent) => { if (event.data !== undefined) console.log(event.data) } function look(frame: ImageData): void { worker.postMessage(frame, [frame.data.buffer]) // moves the pixels, no copy } ``` ```ts // scan-worker.ts import { decode } from '@forgesworn/qr' addEventListener('message', (event: MessageEvent) => { postMessage(decode(event.data)?.text) }) ``` Most bundlers understand `new Worker(new URL(...), { type: 'module' })` as written. Send the next frame only when the last has answered, so frames do not queue. ### Read pixels in Node Node has no image decoder of its own. Use any that gives raw RGBA or grey bytes, and hand them over with their size: ```ts import { decode } from '@forgesworn/qr' function read(rgba: Uint8Array, width: number, height: number): string | undefined { return decode({ data: rgba, width, height })?.text } ``` ### Greyscale camera planes A camera's luminance (Y) plane is already what the decoder wants, and skips the colour conversion. `rowStride` is the number of pixels from one row to the next, for planes with padding. ```ts import { decode } from '@forgesworn/qr' function readPlane(y: Uint8Array, width: number, height: number, rowStride: number): string | undefined { return decode({ data: y, width, height }, { channels: 1, rowStride })?.text } ``` The data must hold at least `rowStride * (height - 1) + width` bytes, and `rowStride` may not be less than `width`. A Node `Buffer` is a `Uint8Array` and works as it is. `decode` copies what it needs: it neither changes your buffer nor keeps it. ### Repeated camera frames Use an independent decoder for each camera stream: ```ts import { createDecoder, type ImageLike } from '@forgesworn/qr' const reader = createDecoder() function readFrame(frame: ImageLike) { return reader.decode(frame) // the same image and options as decode() } reader.reset() // call when stopping or switching cameras ``` It reuses luminance storage and tries the previous symbol's region first. When that region misses, it searches the full frame in the same call. Each call reads fresh pixels; it never returns a cached payload. With several codes visible, it favours the previous region. Cropping can change the reported location slightly. `reset()` forgets the region and releases working storage. Keep using a worker and avoid queueing frames, as in the recipe above. ### Everything a read gives you ```ts import { decode, type DecodeResult, type ImageLike } from '@forgesworn/qr' function describe(frame: ImageLike): string { const found: DecodeResult | undefined = decode(frame) if (!found) return 'nothing read' const { topLeft, topRight, bottomLeft } = found.location // finder pattern centres, in pixels const width = Math.hypot(topRight.x - topLeft.x, topRight.y - topLeft.y) const height = Math.hypot(bottomLeft.x - topLeft.x, bottomLeft.y - topLeft.y) return [ `text: ${found.text}`, `bytes: ${found.bytes.length}`, // the payload as stored, for data that is not text `version ${found.version}, level ${found.ecc}, ${found.corrected} codewords corrected`, found.inverted ? 'light on dark' : 'dark on light', found.mirrored ? 'mirrored' : 'not mirrored', `about ${Math.round(width)} by ${Math.round(height)} pixels between finders`, ].join('\n') } ``` The three points of `location` are the centres of the finder patterns, each 3.5 modules in from a corner of the symbol, so the symbol's outline lies a little outside them. `alignment` is the alignment pattern's centre when one was used. `found.structuredAppend` (`{ index, total, parity }`) is present when the code is one part of a message split across several, and `found.fnc1` when it is a GS1 or industry code. ### Only dark-on-light codes ```ts import { decode, type ImageLike } from '@forgesworn/qr' const readNormal = (frame: ImageLike) => decode(frame, { inversion: 'normal' }) // 'inverted' | 'both' (default) ``` Naming the polarity avoids searching the other polarity. The saving depends on the image and which search budgets are reached. ### Check a code you just made ```ts import { decodeModules, encode } from '@forgesworn/qr' const qr = encode('https://example.com/') console.assert(decodeModules(qr.modules, qr.size)?.text === 'https://example.com/') ``` ## API Everything the package exports: ```ts function encode(data: string | Uint8Array, options?: EncodeOptions): QrCode function isDark(qr: QrCode, x: number, y: number): boolean function toSvg(qr: QrCode, options?: SvgOptions): string function drawCanvas(canvas: CanvasLike, qr: QrCode, options?: CanvasOptions): void function toTerminal(qr: QrCode, options?: TerminalOptions): string function decode(image: ImageLike, options?: DecodeOptions): DecodeResult | undefined function createDecoder(): Decoder function decodeModules(modules: ArrayLike, size: number): (Payload & { mirrored: boolean }) | undefined class QrCapacityError extends RangeError {} type ErrorCorrection = 'L' | 'M' | 'Q' | 'H' type Mode = 'numeric' | 'alphanumeric' | 'byte' interface EncodeOptions { ecc?: ErrorCorrection // default 'M' version?: number // 1-40; default: the smallest that fits minVersion?: number // default 1 mask?: number // 0-7; default: the lowest penalty mode?: Mode // the whole text as one segment; default: the fewest-bits mix eci?: boolean // mark byte data as UTF-8; default false } interface QrCode { version: number ecc: ErrorCorrection mask: number mode: Mode // the widest mode among the segments segments: readonly { mode: Mode; count: number }[] size: number // modules a side, 17 + 4 * version, no quiet zone modules: Uint8Array // size * size, row by row, 1 for dark } interface SvgOptions { margin?: number; dark?: string; light?: string | null; title?: string } /** An HTMLCanvasElement, an OffscreenCanvas, or anything shaped like one. */ interface CanvasLike { width: number; height: number; getContext(type: '2d'): { fillStyle: unknown; fillRect(x: number, y: number, width: number, height: number): void } | null } interface CanvasOptions { width?: number; margin?: number; dark?: string; light?: string | null } interface TerminalOptions { margin?: number; ink?: 'light' | 'dark' } interface ImageLike { data: Uint8Array | Uint8ClampedArray; width: number; height: number } interface Decoder { decode(image: ImageLike, options?: DecodeOptions): DecodeResult | undefined reset(): void } interface DecodeOptions { rowStride?: number // pixels from row to row; default width channels?: 1 | 4 // default: worked out from the data length inversion?: 'normal' | 'inverted' | 'both' // default 'both' } interface Payload { text: string bytes: Uint8Array version: number ecc: ErrorCorrection mask: number eci: readonly number[] // ECI assignments in the order met corrected: number // codewords error correction put right structuredAppend?: { index: number; total: number; parity: number } fnc1?: { position: 'first' | 'second'; applicationIndicator?: string } } interface DecodeResult extends Payload { mirrored: boolean inverted: boolean location: { topLeft: Point; topRight: Point; bottomLeft: Point; alignment: Point | undefined } } interface Point { x: number; y: number } ``` Defaults worth knowing: `margin` is 4 modules everywhere; `dark` is `'#000'` and `light` is `'#fff'`; a canvas is 8 pixels a module unless `width` says otherwise. **Text.** A string is encoded as UTF-8. When reading, `text` follows the symbol's ECI if it has one; under an ECI the platform cannot read, what cannot be read is U+FFFD and never a guess. Without one, byte data is UTF-8 when it is valid UTF-8, Shift_JIS when it has the shape of Shift_JIS text, and Latin-1 otherwise; kanji and hanzi segments read as text. `bytes` is there for payloads that are not text. [SPEC.md](https://github.com/forgesworn/qr/blob/main/SPEC.md) has the detail. **What `decode` throws.** Nothing for a picture with no code: that is `undefined`. It throws `TypeError` or `RangeError` only for arguments that cannot be a picture: data that is not a `Uint8Array` or `Uint8ClampedArray`, a size that does not match the data, or three bytes a pixel (pass RGBA or grey). **Wrong text.** The decoder refuses a block that needed more corrections than the standard allows, and holds its later, harder searches of a frame to a stricter check than the first. The tests require damaged symbols to read as nothing or as exactly what was written. **Speed.** The recorded M4 Max/native Node 24.21.0 run measures clean 720p RGBA decoding at 4.661 ms for TypeScript and 1.590 ms for optional WASM. Random noise takes 55.485 ms and 20.569 ms respectively. These are workload- and hardware-specific medians, not a latency guarantee or phone measurement. [PERFORMANCE.md](https://github.com/forgesworn/qr/blob/main/PERFORMANCE.md) records the inputs, warm-up, competing readers, medians, tails and limitations. Use a worker and keep only one frame in flight. ## Common mistakes - **`require('@forgesworn/qr')`:** the package is ESM only. Use `import`. - **Passing an `` or `