Skip to content

Commit 9aeaa3c

Browse files
authored
feat(util): add a QR encoder (anomalyco#59056)
1 parent 28907e8 commit 9aeaa3c

5 files changed

Lines changed: 1066 additions & 1 deletion

File tree

‎bun.lock‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/util/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
"@types/npm-package-arg": "6.1.4",
7171
"@types/npmcli__arborist": "6.3.3",
7272
"@types/pacote": "11.1.8",
73-
"@typescript/native": "catalog:"
73+
"@typescript/native": "catalog:",
74+
"jsqr": "1.4.0"
7475
}
7576
}

‎packages/util/src/qr.ts‎

Lines changed: 323 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,323 @@
1+
// QR Code encoder (ISO/IEC 18004) for byte-mode text at error correction level L, following the structure of
2+
// Project Nayuki's QR Code generator (MIT): https://www.nayuki.io/page/qr-code-generator-library
3+
4+
// Error correction codewords per block and block count at level L, for versions 1 to 40.
5+
const ECC_PER_BLOCK = [
6+
7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30,
7+
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
8+
]
9+
const BLOCKS = [
10+
1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19,
11+
20, 21, 22, 24, 25,
12+
]
13+
14+
const MASKS = [
15+
(x: number, y: number) => (x + y) % 2 === 0,
16+
(_: number, y: number) => y % 2 === 0,
17+
(x: number) => x % 3 === 0,
18+
(x: number, y: number) => (x + y) % 3 === 0,
19+
(x: number, y: number) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
20+
(x: number, y: number) => ((x * y) % 2) + ((x * y) % 3) === 0,
21+
(x: number, y: number) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
22+
(x: number, y: number) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
23+
]
24+
25+
type Draw = (x: number, y: number, dark: boolean) => void
26+
27+
/** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
28+
export function encode(text: string) {
29+
const bytes = new TextEncoder().encode(text)
30+
const version = Array.from({ length: 40 }, (_, i) => i + 1).find(
31+
(v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8 <= dataCapacity(v) * 8,
32+
)
33+
if (version === undefined) throw new RangeError(`Text is too long for a QR Code: ${bytes.length} bytes`)
34+
35+
const size = version * 4 + 17
36+
const modules = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
37+
const reserved = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
38+
drawFunctionPatterns(version, size, (x, y, dark) => {
39+
modules[y][x] = dark
40+
reserved[y][x] = true
41+
})
42+
drawCodewords(modules, reserved, addErrorCorrection(dataCodewords(bytes, version), version))
43+
44+
const candidates = MASKS.map((mask, index) => {
45+
const masked = modules.map((row, y) => row.map((dark, x) => dark !== (!reserved[y][x] && mask(x, y))))
46+
drawFormat(index, size, (x, y, dark) => {
47+
masked[y][x] = dark
48+
})
49+
return masked
50+
})
51+
const scores = candidates.map(penalty)
52+
return candidates[scores.indexOf(Math.min(...scores))]
53+
}
54+
55+
/** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
56+
export function renderSVG(text: string, options: { border?: number; blackColor?: string; whiteColor?: string } = {}) {
57+
const modules = addBorder(encode(text), options.border ?? 1)
58+
const width = modules.length * 10
59+
const path = modules
60+
.flatMap((row, y) => row.flatMap((dark, x) => (dark ? [`M${x * 10},${y * 10}h10v10h-10z`] : [])))
61+
.join("")
62+
return (
63+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${width}">` +
64+
`<rect fill="${escapeAttribute(options.whiteColor ?? "white")}" width="${width}" height="${width}"/>` +
65+
`<path fill="${escapeAttribute(options.blackColor ?? "black")}" d="${path}"/></svg>`
66+
)
67+
}
68+
69+
/**
70+
* Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
71+
* and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
72+
*/
73+
export function renderUnicodeCompact(text: string, options: { border?: number } = {}) {
74+
const modules = addBorder(encode(text), options.border ?? 1)
75+
return Array.from({ length: Math.ceil(modules.length / 2) }, (_, line) =>
76+
modules[line * 2]
77+
.map((top, x) => {
78+
// The symbol has an odd number of rows, so the last line's missing bottom half shows the terminal background.
79+
const bottom = modules[line * 2 + 1]?.[x] ?? true
80+
if (top) return bottom ? " " : "\u2584"
81+
return bottom ? "\u2580" : "\u2588"
82+
})
83+
.join(""),
84+
).join("\n")
85+
}
86+
87+
function drawFunctionPatterns(version: number, size: number, set: Draw) {
88+
for (let i = 0; i < size; i++) {
89+
set(6, i, i % 2 === 0)
90+
set(i, 6, i % 2 === 0)
91+
}
92+
for (const [cx, cy] of [
93+
[3, 3],
94+
[size - 4, 3],
95+
[3, size - 4],
96+
])
97+
for (let dy = -4; dy <= 4; dy++)
98+
for (let dx = -4; dx <= 4; dx++) {
99+
const x = cx + dx
100+
const y = cy + dy
101+
const distance = Math.max(Math.abs(dx), Math.abs(dy))
102+
if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, distance !== 2 && distance !== 4)
103+
}
104+
105+
const positions = alignmentPositions(version, size)
106+
const last = positions.length - 1
107+
positions.forEach((cx, i) =>
108+
positions.forEach((cy, j) => {
109+
// Skip the three corners that hold finder patterns.
110+
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return
111+
for (let dy = -2; dy <= 2; dy++)
112+
for (let dx = -2; dx <= 2; dx++) set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
113+
}),
114+
)
115+
116+
// Reserves the format areas; the real format bits are drawn once the mask is chosen.
117+
drawFormat(0, size, set)
118+
if (version < 7) return
119+
const bits = bch(version, 12, 0x1f25)
120+
for (let i = 0; i < 18; i++) {
121+
const a = size - 11 + (i % 3)
122+
const b = Math.floor(i / 3)
123+
const dark = ((bits >>> i) & 1) === 1
124+
set(a, b, dark)
125+
set(b, a, dark)
126+
}
127+
}
128+
129+
function alignmentPositions(version: number, size: number) {
130+
if (version === 1) return []
131+
const count = Math.floor(version / 7) + 2
132+
const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2
133+
return [6, ...Array.from({ length: count - 1 }, (_, i) => size - 7 - (count - 2 - i) * step)]
134+
}
135+
136+
function drawFormat(mask: number, size: number, set: Draw) {
137+
// Level L is 0b01 in the format information.
138+
const bits = bch((1 << 3) | mask, 10, 0x537) ^ 0x5412
139+
const bit = (i: number) => ((bits >>> i) & 1) === 1
140+
for (let i = 0; i <= 5; i++) set(8, i, bit(i))
141+
set(8, 7, bit(6))
142+
set(8, 8, bit(7))
143+
set(7, 8, bit(8))
144+
for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i))
145+
for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i))
146+
for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i))
147+
set(8, size - 8, true)
148+
}
149+
150+
// Appends the BCH remainder of `data` for a generator polynomial of the given degree.
151+
function bch(data: number, degree: number, generator: number) {
152+
let remainder = data
153+
for (let i = 0; i < degree; i++) remainder = (remainder << 1) ^ ((remainder >>> (degree - 1)) * generator)
154+
return (data << degree) | remainder
155+
}
156+
157+
function dataCodewords(bytes: Uint8Array, version: number) {
158+
const capacity = dataCapacity(version)
159+
const bits: number[] = []
160+
const append = (value: number, length: number) => {
161+
for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1)
162+
}
163+
append(0b0100, 4)
164+
append(bytes.length, version < 10 ? 8 : 16)
165+
bytes.forEach((byte) => append(byte, 8))
166+
append(0, Math.min(4, capacity * 8 - bits.length))
167+
append(0, (8 - (bits.length % 8)) % 8)
168+
const data = Array.from({ length: bits.length / 8 }, (_, i) =>
169+
bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0),
170+
)
171+
return [...data, ...Array.from({ length: capacity - data.length }, (_, i) => (i % 2 === 0 ? 0xec : 0x11))]
172+
}
173+
174+
function addErrorCorrection(data: number[], version: number) {
175+
const blocks = BLOCKS[version - 1]
176+
const ecc = ECC_PER_BLOCK[version - 1]
177+
const raw = Math.floor(rawModules(version) / 8)
178+
// The first `short` blocks hold one data codeword fewer than the rest.
179+
const short = blocks - (raw % blocks)
180+
const shortLength = Math.floor(raw / blocks) - ecc
181+
const divisor = reedSolomonDivisor(ecc)
182+
const split = Array.from({ length: blocks }, (_, i) => {
183+
const start = i * shortLength + Math.max(0, i - short)
184+
return data.slice(start, start + shortLength + (i < short ? 0 : 1))
185+
})
186+
const interleave = (rows: number[][], length: number) =>
187+
Array.from({ length }, (_, i) => rows.flatMap((row) => (i < row.length ? [row[i]] : []))).flat()
188+
return [
189+
...interleave(split, shortLength + 1),
190+
...interleave(
191+
split.map((block) => reedSolomonRemainder(block, divisor)),
192+
ecc,
193+
),
194+
]
195+
}
196+
197+
function drawCodewords(modules: boolean[][], reserved: boolean[][], codewords: number[]) {
198+
const size = modules.length
199+
let i = 0
200+
for (let right = size - 1; right >= 1; right -= 2) {
201+
// The vertical timing pattern takes column 6, so the column pair shifts left past it.
202+
if (right === 6) right = 5
203+
for (let vertical = 0; vertical < size; vertical++)
204+
for (let j = 0; j < 2; j++) {
205+
const x = right - j
206+
const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical
207+
if (reserved[y][x] || i >= codewords.length * 8) continue
208+
modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) === 1
209+
i++
210+
}
211+
}
212+
}
213+
214+
function penalty(modules: boolean[][]) {
215+
const size = modules.length
216+
const columns = modules.map((_, x) => modules.map((row) => row[x]))
217+
const lines = [...modules, ...columns].reduce((sum, line) => sum + linePenalty(line), 0)
218+
// Each 2x2 block of one colour, found from its bottom-right module.
219+
const boxes = modules
220+
.slice(1)
221+
.flatMap((row, y) =>
222+
row.slice(1).filter((dark, x) => dark === row[x] && dark === modules[y][x] && dark === modules[y][x + 1]),
223+
).length
224+
const dark = modules.flat().filter(Boolean).length
225+
const total = size * size
226+
return lines + boxes * 3 + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10
227+
}
228+
229+
// Scores runs of five or more same-coloured modules, and 1:1:3:1:1 finder-like patterns with 4 light modules on a side.
230+
function linePenalty(line: boolean[]) {
231+
const size = line.length
232+
const history = [0, 0, 0, 0, 0, 0, 0]
233+
const push = (length: number) => {
234+
history.pop()
235+
history.unshift(history[0] === 0 ? length + size : length)
236+
}
237+
const finders = () => {
238+
const n = history[1]
239+
const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n
240+
return (
241+
(core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) +
242+
(core && history[6] >= n * 4 && history[0] >= n ? 1 : 0)
243+
)
244+
}
245+
let result = 0
246+
let color = false
247+
let run = 0
248+
for (const dark of line) {
249+
if (dark === color) {
250+
run++
251+
if (run === 5) result += 3
252+
if (run > 5) result++
253+
continue
254+
}
255+
push(run)
256+
if (!color) result += finders() * 40
257+
color = dark
258+
run = 1
259+
}
260+
if (color) {
261+
push(run)
262+
run = 0
263+
}
264+
push(run + size)
265+
return result + finders() * 40
266+
}
267+
268+
function reedSolomonDivisor(degree: number) {
269+
const result = Array<number>(degree).fill(0)
270+
result[degree - 1] = 1
271+
let root = 1
272+
for (let i = 0; i < degree; i++) {
273+
for (let j = 0; j < degree; j++) {
274+
result[j] = multiply(result[j], root)
275+
if (j + 1 < degree) result[j] ^= result[j + 1]
276+
}
277+
root = multiply(root, 2)
278+
}
279+
return result
280+
}
281+
282+
function reedSolomonRemainder(data: number[], divisor: number[]) {
283+
return data.reduce(
284+
(remainder, byte) => {
285+
const factor = byte ^ remainder[0]
286+
return [...remainder.slice(1), 0].map((value, i) => value ^ multiply(divisor[i], factor))
287+
},
288+
divisor.map(() => 0),
289+
)
290+
}
291+
292+
// Multiplies in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1.
293+
function multiply(x: number, y: number) {
294+
let z = 0
295+
for (let i = 7; i >= 0; i--) {
296+
z = (z << 1) ^ ((z >>> 7) * 0x11d)
297+
z ^= ((y >>> i) & 1) * x
298+
}
299+
return z
300+
}
301+
302+
function rawModules(version: number) {
303+
const base = (16 * version + 128) * version + 64
304+
if (version < 2) return base
305+
const count = Math.floor(version / 7) + 2
306+
return base - ((25 * count - 10) * count - 55) - (version >= 7 ? 36 : 0)
307+
}
308+
309+
function dataCapacity(version: number) {
310+
return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[version - 1] * BLOCKS[version - 1]
311+
}
312+
313+
function addBorder(modules: boolean[][], border: number) {
314+
const width = modules.length + border * 2
315+
const blank = () => Array<boolean>(width).fill(false)
316+
const edge = Array.from({ length: border }, blank)
317+
const padding = Array<boolean>(border).fill(false)
318+
return [...edge, ...modules.map((row) => [...padding, ...row, ...padding]), ...Array.from({ length: border }, blank)]
319+
}
320+
321+
function escapeAttribute(value: string) {
322+
return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
323+
}

0 commit comments

Comments
 (0)