dsh-hiss-plugins 1.5.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,442 +0,0 @@
1
- /**
2
- * A small QR Code encoder for the LAN page: byte mode, error-correction level M,
3
- * versions 1-10, every mask evaluated by the standard penalty score. It exists
4
- * because the package ships no dependencies and a phone camera needs real
5
- * modules, not text art.
6
- *
7
- * The placement, Reed-Solomon, format and version-bit code follows the ISO/IEC
8
- * 18004 layout that every encoder implements; the output is verified against an
9
- * independent encoder rather than by eyeballing a picture.
10
- *
11
- * @module dsh-hiss-plugins/lan-access/qr
12
- */
13
-
14
- /** Error-correction level M codewords per block, index 0 = version 1. */
15
- const ECC_CODEWORDS_PER_BLOCK = [10, 16, 26, 18, 24, 16, 18, 22, 22, 26];
16
- /** Error-correction level M block counts, index 0 = version 1. */
17
- const NUM_BLOCKS = [1, 1, 1, 2, 2, 4, 4, 4, 5, 5];
18
- /** Format bits for level M. */
19
- const ECC_FORMAT_BITS = 0b00;
20
- /** The largest version this encoder builds. */
21
- const MAX_VERSION = 10;
22
-
23
- /** Multiplication and log tables over GF(256) with the QR polynomial. */
24
- const EXP = new Uint8Array(512);
25
- const LOG = new Uint8Array(256);
26
- {
27
- let value = 1;
28
- for (let index = 0; index < 255; index += 1) {
29
- EXP[index] = value;
30
- LOG[value] = index;
31
- value <<= 1;
32
- if (value & 0x100) value ^= 0x11d;
33
- }
34
- for (let index = 255; index < 512; index += 1) EXP[index] = EXP[index - 255];
35
- }
36
-
37
- /**
38
- * Multiply two GF(256) values.
39
- * @param left - first field element.
40
- * @param right - second field element.
41
- * @returns the product.
42
- */
43
- function multiply(left, right) {
44
- return left === 0 || right === 0 ? 0 : EXP[LOG[left] + LOG[right]];
45
- }
46
-
47
- /**
48
- * The number of data modules a version carries before error correction.
49
- * @param version - QR version 1-10.
50
- * @returns the raw data-module count.
51
- */
52
- function rawDataModules(version) {
53
- let result = (16 * version + 128) * version + 64;
54
- if (version >= 2) {
55
- const alignment = Math.floor(version / 7) + 2;
56
- result -= (25 * alignment - 10) * alignment - 55;
57
- if (version >= 7) result -= 36;
58
- }
59
- return result;
60
- }
61
-
62
- /**
63
- * The total data codewords a version carries at level M.
64
- * @param version - QR version 1-10.
65
- * @returns the data codeword count.
66
- */
67
- function dataCodewords(version) {
68
- const blocks = NUM_BLOCKS[version - 1];
69
- return Math.floor(rawDataModules(version) / 8) - ECC_CODEWORDS_PER_BLOCK[version - 1] * blocks;
70
- }
71
-
72
- /**
73
- * The smallest version that holds a byte payload at level M.
74
- * @param length - payload length in bytes.
75
- * @returns the version, or 0 when the payload does not fit.
76
- */
77
- function versionFor(length) {
78
- for (let version = 1; version <= MAX_VERSION; version += 1) {
79
- // Mode indicator (4 bits) plus an 8-bit character count for versions 1-9.
80
- const header = version <= 9 ? 12 : 20;
81
- if (length * 8 + header <= dataCodewords(version) * 8) return version;
82
- }
83
- return 0;
84
- }
85
-
86
- /**
87
- * The Reed-Solomon divisor for one block's error-correction length.
88
- * @param degree - error-correction codewords per block.
89
- * @returns the divisor coefficients, highest power first.
90
- */
91
- function divisor(degree) {
92
- const result = new Uint8Array(degree);
93
- result[degree - 1] = 1;
94
- let root = 1;
95
- for (let index = 0; index < degree; index += 1) {
96
- for (let position = 0; position < degree; position += 1) {
97
- result[position] = multiply(result[position], root);
98
- if (position + 1 < degree) result[position] ^= result[position + 1];
99
- }
100
- root = multiply(root, 2);
101
- }
102
- return result;
103
- }
104
-
105
- /**
106
- * The error-correction codewords for one block.
107
- * @param data - the block's data codewords.
108
- * @param coefficients - the divisor from {@link divisor}.
109
- * @returns the error-correction codewords.
110
- */
111
- function remainder(data, coefficients) {
112
- const result = new Uint8Array(coefficients.length);
113
- for (const value of data) {
114
- const factor = value ^ result[0];
115
- result.copyWithin(0, 1);
116
- result[result.length - 1] = 0;
117
- for (let index = 0; index < result.length; index += 1) result[index] ^= multiply(coefficients[index], factor);
118
- }
119
- return result;
120
- }
121
-
122
- /**
123
- * Encode a byte payload into the full codeword sequence.
124
- * @param bytes - payload bytes.
125
- * @param version - QR version 1-10.
126
- * @returns interleaved data and error-correction codewords.
127
- */
128
- function codewords(bytes, version) {
129
- const capacity = dataCodewords(version);
130
- const countBits = version <= 9 ? 8 : 16;
131
- if (bytes.length * 8 + 4 + countBits > capacity * 8) throw new Error("qr: payload does not fit the chosen version");
132
-
133
- const bits = [];
134
- const push = (value, length) => {
135
- for (let index = length - 1; index >= 0; index -= 1) bits.push((value >>> index) & 1);
136
- };
137
- push(0b0100, 4);
138
- push(bytes.length, countBits);
139
- for (const byte of bytes) push(byte, 8);
140
- push(0, Math.min(4, capacity * 8 - bits.length));
141
- while (bits.length % 8 !== 0) bits.push(0);
142
- const data = new Uint8Array(capacity);
143
- for (let index = 0; index < bits.length; index += 8) {
144
- let byte = 0;
145
- for (let offset = 0; offset < 8; offset += 1) byte = (byte << 1) | bits[index + offset];
146
- data[index / 8] = byte;
147
- }
148
- for (let index = bits.length / 8, pad = 0xec; index < capacity; index += 1, pad ^= 0xec ^ 0x11) data[index] = pad;
149
-
150
- const blockCount = NUM_BLOCKS[version - 1];
151
- const eccLength = ECC_CODEWORDS_PER_BLOCK[version - 1];
152
- const totalCodewords = Math.floor(rawDataModules(version) / 8);
153
- const shortLength = Math.floor(totalCodewords / blockCount);
154
- const shortCount = blockCount - (totalCodewords % blockCount);
155
- const coefficients = divisor(eccLength);
156
- const blocks = [];
157
- for (let index = 0, offset = 0; index < blockCount; index += 1) {
158
- const length = shortLength - eccLength + (index < shortCount ? 0 : 1);
159
- const block = data.subarray(offset, offset + length);
160
- offset += length;
161
- blocks.push({ data: block, ecc: remainder(block, coefficients) });
162
- }
163
- const result = [];
164
- for (let index = 0; index < shortLength - eccLength + 1; index += 1) {
165
- for (const block of blocks) if (index < block.data.length) result.push(block.data[index]);
166
- }
167
- for (let index = 0; index < eccLength; index += 1) for (const block of blocks) result.push(block.ecc[index]);
168
- return Uint8Array.from(result);
169
- }
170
-
171
- /**
172
- * The alignment-pattern centre coordinates of a version.
173
- * @param version - QR version 1-10.
174
- * @returns sorted centre coordinates.
175
- */
176
- function alignmentCentres(version) {
177
- if (version === 1) return [];
178
- const count = Math.floor(version / 7) + 2;
179
- const step = Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;
180
- const result = [6];
181
- for (let position = version * 4 + 10; result.length < count; position -= step) result.splice(1, 0, position);
182
- return result;
183
- }
184
-
185
- /** A matrix under construction; `null` marks a module no data paints. */
186
- function emptyMatrix(size) {
187
- return Array.from({ length: size }, () => Array.from({ length: size }, () => null));
188
- }
189
-
190
- /**
191
- * Paint the fixed patterns: finders, separators, timing, and the dark module.
192
- * @param modules - the matrix to paint.
193
- */
194
- function drawFixedPatterns(modules) {
195
- const size = modules.length;
196
- const set = (x, y, dark) => {
197
- modules[y][x] = dark;
198
- };
199
- for (const [originX, originY] of [[0, 0], [size - 7, 0], [0, size - 7]]) {
200
- for (let dy = -1; dy <= 7; dy += 1) {
201
- for (let dx = -1; dx <= 7; dx += 1) {
202
- const x = originX + dx;
203
- const y = originY + dy;
204
- if (x < 0 || x >= size || y < 0 || y >= size) continue;
205
- const distance = Math.max(Math.abs(dx - 3), Math.abs(dy - 3));
206
- set(x, y, distance !== 2 && distance !== 4);
207
- }
208
- }
209
- }
210
- for (let index = 8; index < size - 8; index += 1) {
211
- const dark = index % 2 === 0;
212
- set(index, 6, dark);
213
- set(6, index, dark);
214
- }
215
- set(8, size - 8, true);
216
- }
217
-
218
- /**
219
- * Paint every alignment pattern the version carries.
220
- * @param modules - the matrix to paint.
221
- * @param version - QR version 1-10.
222
- */
223
- function drawAlignment(modules, version) {
224
- const centres = alignmentCentres(version);
225
- const last = centres.length - 1;
226
- for (let row = 0; row <= last; row += 1) {
227
- for (let column = 0; column <= last; column += 1) {
228
- const centreX = centres[column];
229
- const centreY = centres[row];
230
- if ((column === 0 && row === 0) || (column === 0 && row === last) || (column === last && row === 0)) continue;
231
- for (let dy = -2; dy <= 2; dy += 1) {
232
- for (let dx = -2; dx <= 2; dx += 1) {
233
- modules[centreY + dy][centreX + dx] = Math.max(Math.abs(dx), Math.abs(dy)) !== 1;
234
- }
235
- }
236
- }
237
- }
238
- }
239
-
240
- /**
241
- * The 15-bit format information for a level and mask, BCH protected.
242
- * @param mask - mask pattern 0-7.
243
- * @returns the 15 bits, most significant first.
244
- */
245
- function formatBits(mask) {
246
- const data = (ECC_FORMAT_BITS << 3) | mask;
247
- let remainderBits = data;
248
- for (let index = 0; index < 10; index += 1) remainderBits = (remainderBits << 1) ^ ((remainderBits >>> 9) * 0x537);
249
- return ((data << 10) | remainderBits) ^ 0x5412;
250
- }
251
-
252
- /**
253
- * The 18-bit version information for a version at least 7, BCH protected.
254
- * @param version - QR version 7-10.
255
- * @returns the 18 bits, most significant first.
256
- */
257
- function versionBits(version) {
258
- let remainderBits = version;
259
- for (let index = 0; index < 12; index += 1) remainderBits = (remainderBits << 1) ^ ((remainderBits >>> 11) * 0x1f25);
260
- return (version << 12) | remainderBits;
261
- }
262
-
263
- /**
264
- * Paint the format bits around the finders and the version bits beside them.
265
- * @param modules - the matrix to paint.
266
- * @param mask - mask pattern 0-7.
267
- * @param version - QR version 1-10.
268
- */
269
- function drawMetadata(modules, mask, version) {
270
- const size = modules.length;
271
- const bits = formatBits(mask);
272
- const set = (x, y, dark) => {
273
- modules[y][x] = dark;
274
- };
275
- for (let index = 0; index < 6; index += 1) set(8, index, ((bits >>> index) & 1) !== 0);
276
- set(8, 7, ((bits >>> 6) & 1) !== 0);
277
- set(8, 8, ((bits >>> 7) & 1) !== 0);
278
- set(7, 8, ((bits >>> 8) & 1) !== 0);
279
- for (let index = 9; index < 15; index += 1) set(14 - index, 8, ((bits >>> index) & 1) !== 0);
280
- for (let index = 0; index < 8; index += 1) set(size - 1 - index, 8, ((bits >>> index) & 1) !== 0);
281
- for (let index = 8; index < 15; index += 1) set(8, size - 15 + index, ((bits >>> index) & 1) !== 0);
282
- set(8, size - 8, true);
283
-
284
- if (version < 7) return;
285
- const versionInfo = versionBits(version);
286
- for (let index = 0; index < 18; index += 1) {
287
- const dark = ((versionInfo >>> index) & 1) !== 0;
288
- const a = size - 11 + (index % 3);
289
- const b = Math.floor(index / 3);
290
- set(a, b, dark);
291
- set(b, a, dark);
292
- }
293
- }
294
-
295
- /**
296
- * Paint the payload in the standard zigzag order, skipping reserved modules.
297
- * @param modules - the matrix to paint.
298
- * @param data - interleaved codewords.
299
- * @param mask - mask pattern 0-7.
300
- */
301
- function drawData(modules, data, mask) {
302
- const size = modules.length;
303
- const bits = [];
304
- for (const byte of data) {
305
- for (let index = 7; index >= 0; index -= 1) bits.push((byte >>> index) & 1);
306
- }
307
- let index = 0;
308
- for (let right = size - 1; right >= 1; right -= 2) {
309
- if (right === 6) right = 5;
310
- for (let vertical = 0; vertical < size; vertical += 1) {
311
- for (let offset = 0; offset < 2; offset += 1) {
312
- const x = right - offset;
313
- const upward = ((right + 1) & 2) === 0;
314
- const y = upward ? size - 1 - vertical : vertical;
315
- if (modules[y][x] !== null) continue;
316
- modules[y][x] = maskedBit(bits[index] ?? 0, mask, x, y);
317
- index += 1;
318
- }
319
- }
320
- }
321
- // A version leaves 0-7 remainder bits after its codewords; they stay light
322
- // payload bits and the mask still applies to them.
323
- if (index < bits.length || index - bits.length > 7) throw new Error("qr: payload and matrix disagree on the data-module count");
324
- }
325
-
326
- /**
327
- * Apply one mask pattern's inversion predicate.
328
- * @param bit - the payload bit.
329
- * @param mask - mask pattern 0-7.
330
- * @param x - module column.
331
- * @param y - module row.
332
- * @returns the module colour.
333
- */
334
- function maskedBit(bit, mask, x, y) {
335
- const inverted = [
336
- (x + y) % 2 === 0,
337
- y % 2 === 0,
338
- x % 3 === 0,
339
- (x + y) % 3 === 0,
340
- (Math.floor(y / 2) + Math.floor(x / 3)) % 2 === 0,
341
- ((x * y) % 2) + ((x * y) % 3) === 0,
342
- (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
343
- (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
344
- ][mask];
345
- return (inverted ? bit ^ 1 : bit) === 1;
346
- }
347
-
348
- /**
349
- * Score a masked matrix with the four standard penalty rules; the lowest wins.
350
- * @param modules - a boolean matrix.
351
- * @returns the penalty score.
352
- */
353
- function penalty(modules) {
354
- const size = modules.length;
355
- const dark = (x, y) => modules[y][x] === true;
356
- let score = 0;
357
- // Rules 1 and 3 read every row and column once.
358
- for (const vertical of [false, true]) {
359
- const line = (index) => (vertical ? dark(index[0], index[1]) : dark(index[1], index[0]));
360
- for (let offset = 0; offset < size; offset += 1) {
361
- let run = 1;
362
- let previous = line([0, offset]);
363
- for (let step = 1; step < size; step += 1) {
364
- const value = line([step, offset]);
365
- if (value === previous) run += 1;
366
- else {
367
- if (run >= 5) score += 3 + (run - 5);
368
- run = 1;
369
- previous = value;
370
- }
371
- }
372
- if (run >= 5) score += 3 + (run - 5);
373
- for (let step = 0; step + 11 <= size; step += 1) {
374
- let bits = "";
375
- for (let index = 0; index < 11; index += 1) bits += line([step + index, offset]) ? "1" : "0";
376
- if (bits === "10111010000" || bits === "00001011101") score += 40;
377
- }
378
- }
379
- }
380
- // Rule 2: every same-colour 2x2 block.
381
- for (let y = 0; y < size - 1; y += 1) {
382
- for (let x = 0; x < size - 1; x += 1) {
383
- const value = dark(x, y);
384
- if (value === dark(x + 1, y) && value === dark(x, y + 1) && value === dark(x + 1, y + 1)) score += 3;
385
- }
386
- }
387
- // Rule 4: distance of the dark ratio from half, in 5% steps.
388
- let darkCount = 0;
389
- for (const row of modules) for (const value of row) if (value === true) darkCount += 1;
390
- const total = size * size;
391
- score += Math.floor(Math.abs(darkCount * 20 - total * 10) / total) * 10;
392
- return score;
393
- }
394
-
395
- /**
396
- * Build the module matrix for a text payload.
397
- * @param text - the payload; encoded as UTF-8.
398
- * @param options - optional fixed `mask` and `version` for verification.
399
- * @returns `{ size, modules, version, mask }`, modules as `true` for dark.
400
- */
401
- export function qrMatrix(text, options = {}) {
402
- const bytes = new TextEncoder().encode(text);
403
- const version = options.version ?? versionFor(bytes.length);
404
- if (version < 1 || version > MAX_VERSION) throw new Error(`qr: no version up to ${MAX_VERSION} holds this payload`);
405
- const size = version * 4 + 17;
406
- const data = codewords(bytes, version);
407
- const masks = options.mask === undefined ? [0, 1, 2, 3, 4, 5, 6, 7] : [options.mask];
408
- let best;
409
- for (const mask of masks) {
410
- const modules = emptyMatrix(size);
411
- drawFixedPatterns(modules);
412
- drawAlignment(modules, version);
413
- drawMetadata(modules, mask, version);
414
- drawData(modules, data, mask);
415
- const score = penalty(modules);
416
- if (best === undefined || score < best.score) best = { modules, mask, score };
417
- }
418
- return { size, version, mask: best.mask, modules: best.modules };
419
- }
420
-
421
- /**
422
- * Render a matrix as a standalone SVG document body.
423
- * @param matrix - the result of {@link qrMatrix}.
424
- * @param options - `scale` pixels per module and `border` modules of quiet zone.
425
- * @returns the SVG markup.
426
- */
427
- export function qrSvg(matrix, { scale = 8, border = 4 } = {}) {
428
- const dimension = (matrix.size + border * 2) * scale;
429
- const runs = [];
430
- for (let y = 0; y < matrix.size; y += 1) {
431
- let start = -1;
432
- for (let x = 0; x <= matrix.size; x += 1) {
433
- const dark = x < matrix.size && matrix.modules[y][x] === true;
434
- if (dark && start === -1) start = x;
435
- else if (!dark && start !== -1) {
436
- runs.push(`M${(start + border) * scale} ${(y + border) * scale}h${(x - start) * scale}v${scale}h${-(x - start) * scale}z`);
437
- start = -1;
438
- }
439
- }
440
- }
441
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${dimension}" height="${dimension}" viewBox="0 0 ${dimension} ${dimension}" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="#ffffff"/><path fill="#000000" d="${runs.join("")}"/></svg>`;
442
- }