qr-decoder-js 1.0.7 → 1.0.8

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.
Files changed (54) hide show
  1. package/LICENSE.jsQR +201 -0
  2. package/LICENSE.qcore +21 -0
  3. package/README.md +19 -127
  4. package/README_ZH.md +19 -122
  5. package/dist/cjs/core/decoder.js +246 -0
  6. package/dist/cjs/core/encoding.js +217 -0
  7. package/dist/cjs/core/preprocess.js +687 -0
  8. package/dist/cjs/index.js +12 -0
  9. package/dist/cjs/native/binarize.js +76 -0
  10. package/dist/cjs/native/bitstream.js +138 -0
  11. package/dist/cjs/native/format.js +33 -0
  12. package/dist/cjs/native/gf256.js +50 -0
  13. package/dist/cjs/native/locator.js +159 -0
  14. package/dist/cjs/native/matrix-decoder.js +166 -0
  15. package/dist/cjs/native/matrix.js +31 -0
  16. package/dist/cjs/native/reed-solomon.js +106 -0
  17. package/dist/cjs/native/sampling.js +71 -0
  18. package/dist/cjs/native/scanner.js +60 -0
  19. package/dist/cjs/native/versions.js +45 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/esm/core/decoder.d.ts +59 -0
  22. package/dist/esm/core/decoder.js +242 -0
  23. package/dist/esm/core/encoding.d.ts +33 -0
  24. package/dist/esm/core/encoding.js +211 -0
  25. package/dist/esm/core/preprocess.d.ts +191 -0
  26. package/dist/esm/core/preprocess.js +670 -0
  27. package/dist/esm/index.d.ts +7 -0
  28. package/dist/esm/index.js +7 -0
  29. package/dist/esm/native/binarize.d.ts +6 -0
  30. package/dist/esm/native/binarize.js +73 -0
  31. package/dist/esm/native/bitstream.d.ts +14 -0
  32. package/dist/esm/native/bitstream.js +135 -0
  33. package/dist/esm/native/format.d.ts +9 -0
  34. package/dist/esm/native/format.js +30 -0
  35. package/dist/esm/native/gf256.d.ts +5 -0
  36. package/dist/esm/native/gf256.js +44 -0
  37. package/dist/esm/native/locator.d.ts +14 -0
  38. package/dist/esm/native/locator.js +156 -0
  39. package/dist/esm/native/matrix-decoder.d.ts +5 -0
  40. package/dist/esm/native/matrix-decoder.js +162 -0
  41. package/dist/esm/native/matrix.d.ts +12 -0
  42. package/dist/esm/native/matrix.js +27 -0
  43. package/dist/esm/native/reed-solomon.d.ts +2 -0
  44. package/dist/esm/native/reed-solomon.js +103 -0
  45. package/dist/esm/native/sampling.d.ts +7 -0
  46. package/dist/esm/native/sampling.js +68 -0
  47. package/dist/esm/native/scanner.d.ts +2 -0
  48. package/dist/esm/native/scanner.js +57 -0
  49. package/dist/esm/native/versions.d.ts +9 -0
  50. package/dist/esm/native/versions.js +42 -0
  51. package/dist/{index.d.ts → esm/types.d.ts} +15 -0
  52. package/package.json +17 -19
  53. package/dist/qr-decoder.js +0 -2670
  54. package/dist/qr-decoder.umd.cjs +0 -1
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.correctCodewords = correctCodewords;
4
+ const gf256_js_1 = require("./gf256.js");
5
+ /** Correct QR codewords using their Reed–Solomon parity, or return null. */
6
+ function correctCodewords(input, parityCount, erasures = []) {
7
+ if (input.length === 0 || input.length > 255 || parityCount <= 0 || parityCount >= input.length) {
8
+ throw new RangeError('Invalid Reed–Solomon block dimensions');
9
+ }
10
+ if (erasures.length > parityCount || new Set(erasures).size !== erasures.length ||
11
+ erasures.some(index => !Number.isInteger(index) || index < 0 || index >= input.length)) {
12
+ throw new RangeError('Invalid Reed–Solomon erasures');
13
+ }
14
+ const syndrome = (0, gf256_js_1.syndromes)(input, parityCount);
15
+ if (syndrome.every(value => value === 0))
16
+ return input.slice();
17
+ // Remove known error locations from the syndrome sequence before finding
18
+ // the remaining unknown locations with Berlekamp–Massey.
19
+ let modified = Array.from(syndrome);
20
+ for (const index of erasures) {
21
+ const root = (0, gf256_js_1.power)(2, input.length - 1 - index);
22
+ modified = modified.slice(1).map((value, i) => value ^ (0, gf256_js_1.multiply)(root, modified[i]));
23
+ }
24
+ // Berlekamp–Massey: coefficients are ordered from constant term upward.
25
+ let locator = new Uint8Array(parityCount + 1);
26
+ let previous = new Uint8Array(parityCount + 1);
27
+ locator[0] = previous[0] = 1;
28
+ let degree = 0;
29
+ let shift = 1;
30
+ let lastDiscrepancy = 1;
31
+ for (let n = 0; n < modified.length; n++) {
32
+ let discrepancy = modified[n];
33
+ for (let i = 1; i <= degree; i++)
34
+ discrepancy ^= (0, gf256_js_1.multiply)(locator[i], modified[n - i]);
35
+ if (discrepancy === 0) {
36
+ shift++;
37
+ continue;
38
+ }
39
+ const saved = locator.slice();
40
+ const factor = (0, gf256_js_1.divide)(discrepancy, lastDiscrepancy);
41
+ for (let i = 0; i + shift <= parityCount; i++) {
42
+ locator[i + shift] ^= (0, gf256_js_1.multiply)(factor, previous[i]);
43
+ }
44
+ if (2 * degree <= n) {
45
+ degree = n + 1 - degree;
46
+ previous = saved;
47
+ lastDiscrepancy = discrepancy;
48
+ shift = 1;
49
+ }
50
+ else {
51
+ shift++;
52
+ }
53
+ }
54
+ if (2 * degree + erasures.length > parityCount)
55
+ return null;
56
+ // Chien search maps roots to codeword indices.
57
+ const locations = [];
58
+ for (let index = 0; index < input.length; index++) {
59
+ const exponent = input.length - 1 - index;
60
+ const root = (0, gf256_js_1.power)(2, -exponent);
61
+ let evaluation = 0;
62
+ for (let i = degree; i >= 0; i--)
63
+ evaluation = (0, gf256_js_1.multiply)(evaluation, root) ^ locator[i];
64
+ if (evaluation === 0)
65
+ locations.push(index);
66
+ }
67
+ if (locations.length !== degree)
68
+ return null;
69
+ if (locations.some(index => erasures.includes(index)))
70
+ return null;
71
+ locations.push(...erasures);
72
+ if (!locations.length)
73
+ return null;
74
+ // Solve the syndrome equations for error magnitudes in the finite field.
75
+ const errorCount = locations.length;
76
+ const equations = Array.from({ length: errorCount }, (_, row) => {
77
+ const equation = new Uint8Array(errorCount + 1);
78
+ for (let column = 0; column < errorCount; column++) {
79
+ equation[column] = (0, gf256_js_1.power)(2, (input.length - 1 - locations[column]) * row);
80
+ }
81
+ equation[errorCount] = syndrome[row];
82
+ return equation;
83
+ });
84
+ for (let column = 0; column < errorCount; column++) {
85
+ let pivot = column;
86
+ while (pivot < errorCount && equations[pivot][column] === 0)
87
+ pivot++;
88
+ if (pivot === errorCount)
89
+ return null;
90
+ [equations[column], equations[pivot]] = [equations[pivot], equations[column]];
91
+ const divisor = equations[column][column];
92
+ for (let i = column; i <= errorCount; i++)
93
+ equations[column][i] = (0, gf256_js_1.divide)(equations[column][i], divisor);
94
+ for (let row = 0; row < errorCount; row++) {
95
+ if (row === column)
96
+ continue;
97
+ const factor = equations[row][column];
98
+ for (let i = column; i <= errorCount; i++)
99
+ equations[row][i] ^= (0, gf256_js_1.multiply)(factor, equations[column][i]);
100
+ }
101
+ }
102
+ const corrected = input.slice();
103
+ for (let i = 0; i < errorCount; i++)
104
+ corrected[locations[i]] ^= equations[i][errorCount];
105
+ return (0, gf256_js_1.syndromes)(corrected, parityCount).every(value => value === 0) ? corrected : null;
106
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extract = extract;
4
+ const matrix_js_1 = require("./matrix.js");
5
+ const matrix_decoder_js_1 = require("./matrix-decoder.js");
6
+ // Solve a projective mapping from four module coordinates to four image coordinates.
7
+ function projection(from, to) {
8
+ const rows = [];
9
+ for (let i = 0; i < 4; i++) {
10
+ const { x, y } = from[i];
11
+ const { x: u, y: v } = to[i];
12
+ rows.push([x, y, 1, 0, 0, 0, -u * x, -u * y, u]);
13
+ rows.push([0, 0, 0, x, y, 1, -v * x, -v * y, v]);
14
+ }
15
+ for (let col = 0; col < 8; col++) {
16
+ let pivot = col;
17
+ for (let row = col + 1; row < 8; row++) {
18
+ if (Math.abs(rows[row][col]) > Math.abs(rows[pivot][col]))
19
+ pivot = row;
20
+ }
21
+ if (Math.abs(rows[pivot][col]) < 1e-10)
22
+ throw new Error('Degenerate QR geometry');
23
+ [rows[col], rows[pivot]] = [rows[pivot], rows[col]];
24
+ const divisor = rows[col][col];
25
+ for (let j = col; j <= 8; j++)
26
+ rows[col][j] /= divisor;
27
+ for (let row = 0; row < 8; row++) {
28
+ if (row === col)
29
+ continue;
30
+ const factor = rows[row][col];
31
+ for (let j = col; j <= 8; j++)
32
+ rows[row][j] -= factor * rows[col][j];
33
+ }
34
+ }
35
+ const h = rows.map(row => row[8]);
36
+ return (x, y) => {
37
+ const scale = h[6] * x + h[7] * y + 1;
38
+ return { x: (h[0] * x + h[1] * y + h[2]) / scale, y: (h[3] * x + h[4] * y + h[5]) / scale };
39
+ };
40
+ }
41
+ function extract(image, location, soft = false, checkVersion = false) {
42
+ const n = location.dimension;
43
+ const mappingFunction = projection([{ x: 3.5, y: 3.5 }, { x: n - 3.5, y: 3.5 }, { x: n - 6.5, y: n - 6.5 }, { x: 3.5, y: n - 3.5 }], [location.topLeft, location.topRight, location.alignmentPattern, location.bottomLeft]);
44
+ // The two version fields swap when mirrored, so one check covers both orientations.
45
+ if (checkVersion && !soft && !(0, matrix_decoder_js_1.isVersionValid)(n, (x, y) => {
46
+ const point = mappingFunction(x + 0.5, y + 0.5);
47
+ return image.get(Math.floor(point.x), Math.floor(point.y));
48
+ }))
49
+ return null;
50
+ const matrix = matrix_js_1.BitMatrix.createEmpty(n, n);
51
+ const confidence = soft ? new Uint8Array(n * n) : undefined;
52
+ for (let y = 0; y < n; y++)
53
+ for (let x = 0; x < n; x++) {
54
+ const point = mappingFunction(x + 0.5, y + 0.5);
55
+ if (point.x < 0 || point.x >= image.width || point.y < 0 || point.y >= image.height) {
56
+ if (confidence)
57
+ confidence[y * n + x] = 0;
58
+ continue;
59
+ }
60
+ const sample = (dx, dy) => image.get(Math.floor(point.x + dx), Math.floor(point.y + dy));
61
+ const center = sample(0, 0);
62
+ if (!confidence) {
63
+ matrix.set(x, y, center);
64
+ continue;
65
+ }
66
+ const votes = Number(center) * 2 + Number(sample(-0.25, 0)) + Number(sample(0.25, 0)) + Number(sample(0, -0.25)) + Number(sample(0, 0.25));
67
+ matrix.set(x, y, votes >= 3);
68
+ confidence[y * n + x] = votes === 0 || votes === 6 ? 210 : 40 + Math.abs(2 * votes - 6) * 20;
69
+ }
70
+ return { matrix, mappingFunction, confidence };
71
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scanQR = scanQR;
4
+ const binarize_js_1 = require("./binarize.js");
5
+ const locator_js_1 = require("./locator.js");
6
+ const sampling_js_1 = require("./sampling.js");
7
+ const matrix_decoder_js_1 = require("./matrix-decoder.js");
8
+ function scanMatrix(image, soft) {
9
+ const retryLocations = [];
10
+ for (const location of (0, locator_js_1.locate)(image)) {
11
+ if (soft && retryLocations.length < 6)
12
+ retryLocations.push(location);
13
+ try {
14
+ const sampled = (0, sampling_js_1.extract)(image, location, false, true);
15
+ if (!sampled)
16
+ continue;
17
+ const result = (0, matrix_decoder_js_1.decode)(sampled.matrix);
18
+ if (result)
19
+ return result;
20
+ }
21
+ catch {
22
+ // A degenerate candidate does not prevent trying other finder triples.
23
+ }
24
+ }
25
+ if (soft) {
26
+ // Small, blurred symbols can shift a finder center by a fraction of a module.
27
+ // Only accept a soft-corrected payload when two nearby samples agree.
28
+ for (const location of retryLocations) {
29
+ const moduleSize = (Math.hypot(location.topRight.x - location.topLeft.x, location.topRight.y - location.topLeft.y) +
30
+ Math.hypot(location.bottomLeft.x - location.topLeft.x, location.bottomLeft.y - location.topLeft.y)) / (2 * (location.dimension - 7));
31
+ for (const point of ['bottomLeft', 'topRight', 'topLeft', 'alignmentPattern']) {
32
+ for (const axis of ['x', 'y'])
33
+ for (const direction of [-1, 1]) {
34
+ let previous = null;
35
+ for (const offset of [0.08, 0.14]) {
36
+ const adjusted = { ...location, [point]: { ...location[point], [axis]: location[point][axis] + direction * offset * moduleSize } };
37
+ try {
38
+ const sampled = (0, sampling_js_1.extract)(image, adjusted, true);
39
+ const result = (0, matrix_decoder_js_1.decode)(sampled.matrix, sampled.confidence);
40
+ if (result && previous && result.version === previous.version && result.bytes.length === previous.bytes.length &&
41
+ result.bytes.every((byte, i) => byte === previous.bytes[i]) && JSON.stringify(result.chunks) === JSON.stringify(previous.chunks))
42
+ return result;
43
+ previous = result;
44
+ }
45
+ catch {
46
+ previous = null;
47
+ }
48
+ if (!previous)
49
+ break;
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return null;
56
+ }
57
+ function scanQR(data, width, height, tryInvert = true, soft = false) {
58
+ const { binarized, inverted } = (0, binarize_js_1.binarize)(data, width, height, tryInvert);
59
+ return scanMatrix(binarized, soft) || (inverted ? scanMatrix(inverted, soft) : null);
60
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSIONS = void 0;
4
+ exports.VERSIONS = [
5
+ { alignment: [], blocks: { L: { parity: 7, groups: [[1, 19]] }, M: { parity: 10, groups: [[1, 16]] }, Q: { parity: 13, groups: [[1, 13]] }, H: { parity: 17, groups: [[1, 9]] } } },
6
+ { alignment: [6, 18], blocks: { L: { parity: 10, groups: [[1, 34]] }, M: { parity: 16, groups: [[1, 28]] }, Q: { parity: 22, groups: [[1, 22]] }, H: { parity: 28, groups: [[1, 16]] } } },
7
+ { alignment: [6, 22], blocks: { L: { parity: 15, groups: [[1, 55]] }, M: { parity: 26, groups: [[1, 44]] }, Q: { parity: 18, groups: [[2, 17]] }, H: { parity: 22, groups: [[2, 13]] } } },
8
+ { alignment: [6, 26], blocks: { L: { parity: 20, groups: [[1, 80]] }, M: { parity: 18, groups: [[2, 32]] }, Q: { parity: 26, groups: [[2, 24]] }, H: { parity: 16, groups: [[4, 9]] } } },
9
+ { alignment: [6, 30], blocks: { L: { parity: 26, groups: [[1, 108]] }, M: { parity: 24, groups: [[2, 43]] }, Q: { parity: 18, groups: [[2, 15], [2, 16]] }, H: { parity: 22, groups: [[2, 11], [2, 12]] } } },
10
+ { alignment: [6, 34], blocks: { L: { parity: 18, groups: [[2, 68]] }, M: { parity: 16, groups: [[4, 27]] }, Q: { parity: 24, groups: [[4, 19]] }, H: { parity: 28, groups: [[4, 15]] } } },
11
+ { alignment: [6, 22, 38], blocks: { L: { parity: 20, groups: [[2, 78]] }, M: { parity: 18, groups: [[4, 31]] }, Q: { parity: 18, groups: [[2, 14], [4, 15]] }, H: { parity: 26, groups: [[4, 13], [1, 14]] } } },
12
+ { alignment: [6, 24, 42], blocks: { L: { parity: 24, groups: [[2, 97]] }, M: { parity: 22, groups: [[2, 38], [2, 39]] }, Q: { parity: 22, groups: [[4, 18], [2, 19]] }, H: { parity: 26, groups: [[4, 14], [2, 15]] } } },
13
+ { alignment: [6, 26, 46], blocks: { L: { parity: 30, groups: [[2, 116]] }, M: { parity: 22, groups: [[3, 36], [2, 37]] }, Q: { parity: 20, groups: [[4, 16], [4, 17]] }, H: { parity: 24, groups: [[4, 12], [4, 13]] } } },
14
+ { alignment: [6, 28, 50], blocks: { L: { parity: 18, groups: [[2, 68], [2, 69]] }, M: { parity: 26, groups: [[4, 43], [1, 44]] }, Q: { parity: 24, groups: [[6, 19], [2, 20]] }, H: { parity: 28, groups: [[6, 15], [2, 16]] } } },
15
+ { alignment: [6, 30, 54], blocks: { L: { parity: 20, groups: [[4, 81]] }, M: { parity: 30, groups: [[1, 50], [4, 51]] }, Q: { parity: 28, groups: [[4, 22], [4, 23]] }, H: { parity: 24, groups: [[3, 12], [8, 13]] } } },
16
+ { alignment: [6, 32, 58], blocks: { L: { parity: 24, groups: [[2, 92], [2, 93]] }, M: { parity: 22, groups: [[6, 36], [2, 37]] }, Q: { parity: 26, groups: [[4, 20], [6, 21]] }, H: { parity: 28, groups: [[7, 14], [4, 15]] } } },
17
+ { alignment: [6, 34, 62], blocks: { L: { parity: 26, groups: [[4, 107]] }, M: { parity: 22, groups: [[8, 37], [1, 38]] }, Q: { parity: 24, groups: [[8, 20], [4, 21]] }, H: { parity: 22, groups: [[12, 11], [4, 12]] } } },
18
+ { alignment: [6, 26, 46, 66], blocks: { L: { parity: 30, groups: [[3, 115], [1, 116]] }, M: { parity: 24, groups: [[4, 40], [5, 41]] }, Q: { parity: 20, groups: [[11, 16], [5, 17]] }, H: { parity: 24, groups: [[11, 12], [5, 13]] } } },
19
+ { alignment: [6, 26, 48, 70], blocks: { L: { parity: 22, groups: [[5, 87], [1, 88]] }, M: { parity: 24, groups: [[5, 41], [5, 42]] }, Q: { parity: 30, groups: [[5, 24], [7, 25]] }, H: { parity: 24, groups: [[11, 12], [7, 13]] } } },
20
+ { alignment: [6, 26, 50, 74], blocks: { L: { parity: 24, groups: [[5, 98], [1, 99]] }, M: { parity: 28, groups: [[7, 45], [3, 46]] }, Q: { parity: 24, groups: [[15, 19], [2, 20]] }, H: { parity: 30, groups: [[3, 15], [13, 16]] } } },
21
+ { alignment: [6, 30, 54, 78], blocks: { L: { parity: 28, groups: [[1, 107], [5, 108]] }, M: { parity: 28, groups: [[10, 46], [1, 47]] }, Q: { parity: 28, groups: [[1, 22], [15, 23]] }, H: { parity: 28, groups: [[2, 14], [17, 15]] } } },
22
+ { alignment: [6, 30, 56, 82], blocks: { L: { parity: 30, groups: [[5, 120], [1, 121]] }, M: { parity: 26, groups: [[9, 43], [4, 44]] }, Q: { parity: 28, groups: [[17, 22], [1, 23]] }, H: { parity: 28, groups: [[2, 14], [19, 15]] } } },
23
+ { alignment: [6, 30, 58, 86], blocks: { L: { parity: 28, groups: [[3, 113], [4, 114]] }, M: { parity: 26, groups: [[3, 44], [11, 45]] }, Q: { parity: 26, groups: [[17, 21], [4, 22]] }, H: { parity: 26, groups: [[9, 13], [16, 14]] } } },
24
+ { alignment: [6, 34, 62, 90], blocks: { L: { parity: 28, groups: [[3, 107], [5, 108]] }, M: { parity: 26, groups: [[3, 41], [13, 42]] }, Q: { parity: 30, groups: [[15, 24], [5, 25]] }, H: { parity: 28, groups: [[15, 15], [10, 16]] } } },
25
+ { alignment: [6, 28, 50, 72, 94], blocks: { L: { parity: 28, groups: [[4, 116], [4, 117]] }, M: { parity: 26, groups: [[17, 42]] }, Q: { parity: 28, groups: [[17, 22], [6, 23]] }, H: { parity: 30, groups: [[19, 16], [6, 17]] } } },
26
+ { alignment: [6, 26, 50, 74, 98], blocks: { L: { parity: 28, groups: [[2, 111], [7, 112]] }, M: { parity: 28, groups: [[17, 46]] }, Q: { parity: 30, groups: [[7, 24], [16, 25]] }, H: { parity: 24, groups: [[34, 13]] } } },
27
+ { alignment: [6, 30, 54, 78, 102], blocks: { L: { parity: 30, groups: [[4, 121], [5, 122]] }, M: { parity: 28, groups: [[4, 47], [14, 48]] }, Q: { parity: 30, groups: [[11, 24], [14, 25]] }, H: { parity: 30, groups: [[16, 15], [14, 16]] } } },
28
+ { alignment: [6, 28, 54, 80, 106], blocks: { L: { parity: 30, groups: [[6, 117], [4, 118]] }, M: { parity: 28, groups: [[6, 45], [14, 46]] }, Q: { parity: 30, groups: [[11, 24], [16, 25]] }, H: { parity: 30, groups: [[30, 16], [2, 17]] } } },
29
+ { alignment: [6, 32, 58, 84, 110], blocks: { L: { parity: 26, groups: [[8, 106], [4, 107]] }, M: { parity: 28, groups: [[8, 47], [13, 48]] }, Q: { parity: 30, groups: [[7, 24], [22, 25]] }, H: { parity: 30, groups: [[22, 15], [13, 16]] } } },
30
+ { alignment: [6, 30, 58, 86, 114], blocks: { L: { parity: 28, groups: [[10, 114], [2, 115]] }, M: { parity: 28, groups: [[19, 46], [4, 47]] }, Q: { parity: 28, groups: [[28, 22], [6, 23]] }, H: { parity: 30, groups: [[33, 16], [4, 17]] } } },
31
+ { alignment: [6, 34, 62, 90, 118], blocks: { L: { parity: 30, groups: [[8, 122], [4, 123]] }, M: { parity: 28, groups: [[22, 45], [3, 46]] }, Q: { parity: 30, groups: [[8, 23], [26, 24]] }, H: { parity: 30, groups: [[12, 15], [28, 16]] } } },
32
+ { alignment: [6, 26, 50, 74, 98, 122], blocks: { L: { parity: 30, groups: [[3, 117], [10, 118]] }, M: { parity: 28, groups: [[3, 45], [23, 46]] }, Q: { parity: 30, groups: [[4, 24], [31, 25]] }, H: { parity: 30, groups: [[11, 15], [31, 16]] } } },
33
+ { alignment: [6, 30, 54, 78, 102, 126], blocks: { L: { parity: 30, groups: [[7, 116], [7, 117]] }, M: { parity: 28, groups: [[21, 45], [7, 46]] }, Q: { parity: 30, groups: [[1, 23], [37, 24]] }, H: { parity: 30, groups: [[19, 15], [26, 16]] } } },
34
+ { alignment: [6, 26, 52, 78, 104, 130], blocks: { L: { parity: 30, groups: [[5, 115], [10, 116]] }, M: { parity: 28, groups: [[19, 47], [10, 48]] }, Q: { parity: 30, groups: [[15, 24], [25, 25]] }, H: { parity: 30, groups: [[23, 15], [25, 16]] } } },
35
+ { alignment: [6, 30, 56, 82, 108, 134], blocks: { L: { parity: 30, groups: [[13, 115], [3, 116]] }, M: { parity: 28, groups: [[2, 46], [29, 47]] }, Q: { parity: 30, groups: [[42, 24], [1, 25]] }, H: { parity: 30, groups: [[23, 15], [28, 16]] } } },
36
+ { alignment: [6, 34, 60, 86, 112, 138], blocks: { L: { parity: 30, groups: [[17, 115]] }, M: { parity: 28, groups: [[10, 46], [23, 47]] }, Q: { parity: 30, groups: [[10, 24], [35, 25]] }, H: { parity: 30, groups: [[19, 15], [35, 16]] } } },
37
+ { alignment: [6, 30, 58, 86, 114, 142], blocks: { L: { parity: 30, groups: [[17, 115], [1, 116]] }, M: { parity: 28, groups: [[14, 46], [21, 47]] }, Q: { parity: 30, groups: [[29, 24], [19, 25]] }, H: { parity: 30, groups: [[11, 15], [46, 16]] } } },
38
+ { alignment: [6, 34, 62, 90, 118, 146], blocks: { L: { parity: 30, groups: [[13, 115], [6, 116]] }, M: { parity: 28, groups: [[14, 46], [23, 47]] }, Q: { parity: 30, groups: [[44, 24], [7, 25]] }, H: { parity: 30, groups: [[59, 16], [1, 17]] } } },
39
+ { alignment: [6, 30, 54, 78, 102, 126, 150], blocks: { L: { parity: 30, groups: [[12, 121], [7, 122]] }, M: { parity: 28, groups: [[12, 47], [26, 48]] }, Q: { parity: 30, groups: [[39, 24], [14, 25]] }, H: { parity: 30, groups: [[22, 15], [41, 16]] } } },
40
+ { alignment: [6, 24, 50, 76, 102, 128, 154], blocks: { L: { parity: 30, groups: [[6, 121], [14, 122]] }, M: { parity: 28, groups: [[6, 47], [34, 48]] }, Q: { parity: 30, groups: [[46, 24], [10, 25]] }, H: { parity: 30, groups: [[2, 15], [64, 16]] } } },
41
+ { alignment: [6, 28, 54, 80, 106, 132, 158], blocks: { L: { parity: 30, groups: [[17, 122], [4, 123]] }, M: { parity: 28, groups: [[29, 46], [14, 47]] }, Q: { parity: 30, groups: [[49, 24], [10, 25]] }, H: { parity: 30, groups: [[24, 15], [46, 16]] } } },
42
+ { alignment: [6, 32, 58, 84, 110, 136, 162], blocks: { L: { parity: 30, groups: [[4, 122], [18, 123]] }, M: { parity: 28, groups: [[13, 46], [32, 47]] }, Q: { parity: 30, groups: [[48, 24], [14, 25]] }, H: { parity: 30, groups: [[42, 15], [32, 16]] } } },
43
+ { alignment: [6, 26, 54, 82, 110, 138, 166], blocks: { L: { parity: 30, groups: [[20, 117], [4, 118]] }, M: { parity: 28, groups: [[40, 47], [7, 48]] }, Q: { parity: 30, groups: [[43, 24], [22, 25]] }, H: { parity: 30, groups: [[10, 15], [67, 16]] } } },
44
+ { alignment: [6, 30, 58, 86, 114, 142, 170], blocks: { L: { parity: 30, groups: [[19, 118], [6, 119]] }, M: { parity: 28, groups: [[18, 47], [31, 48]] }, Q: { parity: 30, groups: [[34, 24], [34, 25]] }, H: { parity: 30, groups: [[20, 15], [61, 16]] } } },
45
+ ];
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,59 @@
1
+ import type { ReaderOptions } from '../types.js';
2
+ /**
3
+ * Decode a QR code from ImageData.
4
+ *
5
+ * @param {ImageData} imageData
6
+ * @param {object} [options]
7
+ * @param {'fast'|'balanced'|'aggressive'} [options.mode='aggressive']
8
+ * - fast: original only;
9
+ * - balanced: original + contrast-stretched red/blue-enhanced + sharpen + CLAHE + fast tilt shear + center-zoom;
10
+ * - aggressive: balanced + full 6-angle shear + color-aware quiet-zone, morphology,
11
+ * Otsu, adaptive-binary, and inverted variants.
12
+ * @returns {Promise<import('../types').DecodeResult>}
13
+ */
14
+ export declare function decodeQRImageData(imageData: any, options?: ReaderOptions): Promise<{
15
+ success: boolean;
16
+ error: string;
17
+ text?: undefined;
18
+ encoding?: undefined;
19
+ detectedEncoding?: undefined;
20
+ rawBytes?: undefined;
21
+ qrVersion?: undefined;
22
+ version?: undefined;
23
+ } | {
24
+ success: boolean;
25
+ text: string;
26
+ encoding: any;
27
+ detectedEncoding: any;
28
+ rawBytes: Uint8Array<any>;
29
+ qrVersion: any;
30
+ version: any;
31
+ error?: undefined;
32
+ }>;
33
+ /**
34
+ * Decode a QR code from various input types:
35
+ * File, Blob, ImageData, HTMLImageElement, HTMLCanvasElement, or OffscreenCanvas.
36
+ *
37
+ * @param {File|Blob|ImageData|HTMLImageElement|HTMLCanvasElement|OffscreenCanvas} input
38
+ * @param {object} [options]
39
+ * @returns {Promise<import('../types').DecodeResult>}
40
+ */
41
+ export declare function decodeQRFile(input: any, options?: ReaderOptions): Promise<{
42
+ success: boolean;
43
+ error: string;
44
+ text?: undefined;
45
+ encoding?: undefined;
46
+ detectedEncoding?: undefined;
47
+ rawBytes?: undefined;
48
+ qrVersion?: undefined;
49
+ version?: undefined;
50
+ } | {
51
+ success: boolean;
52
+ text: string;
53
+ encoding: any;
54
+ detectedEncoding: any;
55
+ rawBytes: Uint8Array<any>;
56
+ qrVersion: any;
57
+ version: any;
58
+ error?: undefined;
59
+ }>;
@@ -0,0 +1,242 @@
1
+ // Main decoding pipeline using the bundled TypeScript QR engine
2
+ // with robust multi-channel (blue/red/contrast), edge sharpening, CLAHE, tilt shear compensation,
3
+ // center-zoom for distant codes, and universal multi-encoding detection.
4
+ import { scanQR } from '../native/scanner.js';
5
+ import { generatePreprocessVariants, sharpenImageData, generateCLAHEVariants, generateShearVariants, centerCrop, addQuietZone, generateInvertedVariant, generateDotMatrixFixVariants, toGray, toOtsuBinary, toAdaptiveBinary, grayToImageData, enlargeSmallColorCode, } from './preprocess.js';
6
+ import { decodeChunks } from './encoding.js';
7
+ const DEFAULT_READER_OPTIONS = {
8
+ tryInvert: true,
9
+ };
10
+ const MODES = ['fast', 'balanced', 'aggressive'];
11
+ /**
12
+ * Decode a QR code from ImageData.
13
+ *
14
+ * @param {ImageData} imageData
15
+ * @param {object} [options]
16
+ * @param {'fast'|'balanced'|'aggressive'} [options.mode='aggressive']
17
+ * - fast: original only;
18
+ * - balanced: original + contrast-stretched red/blue-enhanced + sharpen + CLAHE + fast tilt shear + center-zoom;
19
+ * - aggressive: balanced + full 6-angle shear + color-aware quiet-zone, morphology,
20
+ * Otsu, adaptive-binary, and inverted variants.
21
+ * @returns {Promise<import('../types').DecodeResult>}
22
+ */
23
+ export async function decodeQRImageData(imageData, options = {}) {
24
+ if (!imageData ||
25
+ typeof imageData.width !== 'number' ||
26
+ typeof imageData.height !== 'number' ||
27
+ !imageData.data) {
28
+ return { success: false, error: 'Invalid image data (expected ImageData or {width,height,data})' };
29
+ }
30
+ const { mode = 'aggressive', ...readerOverrides } = options;
31
+ const effectiveMode = MODES.includes(mode) ? mode : 'balanced';
32
+ const readerOptions = { ...DEFAULT_READER_OPTIONS, ...readerOverrides };
33
+ const attempts = buildDecodeAttempts(imageData, effectiveMode, readerOptions.tryInvert !== false);
34
+ let hit = null;
35
+ let successVersion = null;
36
+ for (const ver of attempts) {
37
+ try {
38
+ const pixels = ver.data.data instanceof Uint8ClampedArray
39
+ ? ver.data.data : new Uint8ClampedArray(ver.data.data);
40
+ hit = scanQR(pixels, ver.data.width, ver.data.height, readerOptions.tryInvert !== false, ver.soft === true);
41
+ if (hit) {
42
+ successVersion = ver.label;
43
+ break;
44
+ }
45
+ }
46
+ catch (e) {
47
+ console.warn(`Preprocess version "${ver.label}" decode failed:`, e);
48
+ }
49
+ }
50
+ if (!hit) {
51
+ return { success: false, error: 'No QR code found in the image' };
52
+ }
53
+ try {
54
+ const result = decodeChunks(hit.chunks, options.characterSet);
55
+ return {
56
+ success: true,
57
+ text: result.text,
58
+ encoding: result.encoding,
59
+ detectedEncoding: result.detectedEncoding,
60
+ rawBytes: new Uint8Array(hit.bytes),
61
+ qrVersion: hit.version,
62
+ version: successVersion,
63
+ };
64
+ }
65
+ catch (e) {
66
+ return { success: false, error: `Unable to decode QR text: ${e.message}` };
67
+ }
68
+ }
69
+ /**
70
+ * Build an ordered list of decode attempts lazily.
71
+ *
72
+ * @param {ImageData} imageData
73
+ * @param {'fast'|'balanced'|'aggressive'} mode
74
+ * @yields {{ data: ImageData, label: string }}
75
+ */
76
+ function* buildDecodeAttempts(imageData, mode = 'balanced', tryInvert = true) {
77
+ const { width, height } = imageData;
78
+ // Stage 1: original (covers standard B&W QR codes in single pass)
79
+ yield { data: imageData, label: 'original' };
80
+ if (mode === 'fast')
81
+ return;
82
+ // Stage 2: high-efficiency color/blue-ink rescue channels (contrast-stretched 2*R-B and red-channel)
83
+ const preprocessVariants = generatePreprocessVariants(imageData);
84
+ for (const variant of preprocessVariants) {
85
+ yield { data: variant.data, label: variant.label };
86
+ }
87
+ // Stage 3: Sharpened red channel (directly restores blurry, out-of-focus, or distant blue QR codes)
88
+ const redVariant = preprocessVariants.find((variant) => variant.label === 'red-stretched') ||
89
+ preprocessVariants.find((variant) => variant.label === 'red-channel');
90
+ if (redVariant) {
91
+ yield {
92
+ data: sharpenImageData(redVariant.data, 1.2),
93
+ label: 'sharpen-red',
94
+ };
95
+ }
96
+ // Try inexpensive threshold variants before the geometric rescue passes.
97
+ // These often resolve colored and low-contrast codes without shearing or cropping.
98
+ if (mode === 'aggressive') {
99
+ const sources = [
100
+ { data: imageData, label: 'gray' },
101
+ ...preprocessVariants.map((variant) => ({ data: variant.data, label: variant.label })),
102
+ ];
103
+ for (const source of sources) {
104
+ const gray = toGray(source.data);
105
+ yield { data: grayToImageData(toOtsuBinary(gray, width, height), width, height), label: `otsu-binary-${source.label}` };
106
+ yield { data: grayToImageData(toAdaptiveBinary(gray, width, height), width, height), label: `adaptive-binary-${source.label}` };
107
+ }
108
+ const rescueSources = [
109
+ { data: imageData, label: '' },
110
+ ...preprocessVariants.map((variant) => ({ data: variant.data, label: `${variant.label}-` })),
111
+ ];
112
+ for (const source of rescueSources)
113
+ for (const variant of generateDotMatrixFixVariants(source.data)) {
114
+ yield { data: variant.data, label: `${source.label}${variant.label}` };
115
+ }
116
+ }
117
+ // Stage 4: CLAHE (local-contrast enhancement: directly rescues faint, shadow-covered, or unevenly lit codes)
118
+ for (const variant of generateCLAHEVariants(imageData)) {
119
+ yield { data: variant.data, label: variant.label };
120
+ }
121
+ // Stage 5: Fast Tilt / Perspective Shear on red-channel (primary pitch & yaw tilts)
122
+ // Essential for live camera scanning when phone or target is tilted forward/backward or sideways
123
+ const fastShearAngles = [
124
+ { sx: 0, sy: 0.35, label: 'tilt-pitch-down' },
125
+ { sx: 0, sy: -0.35, label: 'tilt-pitch-up' },
126
+ { sx: 0.35, sy: 0, label: 'tilt-yaw-right' },
127
+ { sx: -0.35, sy: 0, label: 'tilt-yaw-left' },
128
+ ];
129
+ for (const variant of generateShearVariants(redVariant ? redVariant.data : imageData, fastShearAngles)) {
130
+ yield { data: variant.data, label: `${variant.label}-red` };
131
+ }
132
+ // Stage 6: Center crop for distant QR codes in large frames (>= 380px)
133
+ if (width >= 380 && height >= 380) {
134
+ const cropped = centerCrop(imageData, 0.6);
135
+ const croppedVariants = generatePreprocessVariants(cropped);
136
+ const croppedRed = croppedVariants.find((variant) => variant.label === 'red-stretched') ||
137
+ croppedVariants.find((variant) => variant.label === 'red-channel');
138
+ if (croppedRed) {
139
+ yield { data: croppedRed.data, label: 'center-crop-red' };
140
+ yield { data: sharpenImageData(croppedRed.data, 1.2), label: 'center-crop-sharpen-red' };
141
+ }
142
+ }
143
+ if (mode === 'balanced')
144
+ return;
145
+ // Stage 7: Full 6-direction tilt shear on original image
146
+ for (const variant of generateShearVariants(imageData)) {
147
+ yield { data: variant.data, label: variant.label };
148
+ }
149
+ // Stage 8: Pad each color-rescue channel so edge-cropped codes regain a quiet zone.
150
+ const quietZoneSources = [
151
+ { data: imageData, label: 'quiet-zone' },
152
+ ...preprocessVariants.map((variant) => ({
153
+ data: variant.data,
154
+ label: `quiet-zone-${variant.label}`,
155
+ })),
156
+ ];
157
+ for (const source of quietZoneSources) {
158
+ const padded = addQuietZone(source.data);
159
+ if (padded) {
160
+ yield { data: padded, label: source.label };
161
+ }
162
+ }
163
+ const binarySources = [
164
+ { data: imageData, label: 'gray' },
165
+ ...preprocessVariants.map((variant) => ({
166
+ data: variant.data,
167
+ label: variant.label,
168
+ })),
169
+ ];
170
+ if (tryInvert)
171
+ for (const source of binarySources) {
172
+ const inverted = generateInvertedVariant(source.data);
173
+ yield { data: inverted.data, label: `inverted-${source.label}` };
174
+ }
175
+ if (Math.max(width, height) <= 350) {
176
+ const enlarged = enlargeSmallColorCode(imageData);
177
+ if (enlarged)
178
+ yield { data: enlarged, label: 'small-color-upscaled', soft: true };
179
+ }
180
+ }
181
+ /**
182
+ * Decode a QR code from various input types:
183
+ * File, Blob, ImageData, HTMLImageElement, HTMLCanvasElement, or OffscreenCanvas.
184
+ *
185
+ * @param {File|Blob|ImageData|HTMLImageElement|HTMLCanvasElement|OffscreenCanvas} input
186
+ * @param {object} [options]
187
+ * @returns {Promise<import('../types').DecodeResult>}
188
+ */
189
+ export async function decodeQRFile(input, options = {}) {
190
+ const imgData = await toImageData(input);
191
+ const effectiveOptions = { mode: 'aggressive', ...options };
192
+ return decodeQRImageData(imgData, effectiveOptions);
193
+ }
194
+ /** Convert input types into a single ImageData. */
195
+ async function toImageData(input) {
196
+ if (typeof ImageData !== 'undefined' && input instanceof ImageData)
197
+ return input;
198
+ if (input &&
199
+ typeof input.width === 'number' &&
200
+ typeof input.height === 'number' &&
201
+ input.data) {
202
+ return input;
203
+ }
204
+ if (typeof HTMLImageElement !== 'undefined' && input instanceof HTMLImageElement) {
205
+ return imageDataFromElement(input);
206
+ }
207
+ if (typeof HTMLCanvasElement !== 'undefined' && input instanceof HTMLCanvasElement) {
208
+ const ctx = input.getContext('2d');
209
+ return ctx.getImageData(0, 0, input.width, input.height);
210
+ }
211
+ if (typeof OffscreenCanvas !== 'undefined' && input instanceof OffscreenCanvas) {
212
+ const ctx = input.getContext('2d');
213
+ return ctx.getImageData(0, 0, input.width, input.height);
214
+ }
215
+ if (typeof Blob !== 'undefined' && input instanceof Blob) {
216
+ return imageDataFromBlob(input);
217
+ }
218
+ throw new TypeError('Unsupported input type; expected File, Blob, ImageData, HTMLImageElement, or Canvas');
219
+ }
220
+ function imageDataFromElement(img) {
221
+ const canvas = document.createElement('canvas');
222
+ canvas.width = img.naturalWidth || img.width;
223
+ canvas.height = img.naturalHeight || img.height;
224
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
225
+ ctx.drawImage(img, 0, 0);
226
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
227
+ }
228
+ function imageDataFromBlob(blob) {
229
+ return new Promise((resolve, reject) => {
230
+ const url = URL.createObjectURL(blob);
231
+ const img = new Image();
232
+ img.onload = () => {
233
+ URL.revokeObjectURL(url);
234
+ resolve(imageDataFromElement(img));
235
+ };
236
+ img.onerror = () => {
237
+ URL.revokeObjectURL(url);
238
+ reject(new Error('Failed to load image from blob'));
239
+ };
240
+ img.src = url;
241
+ });
242
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Normalize an encoding name into a label understood by TextDecoder.
3
+ * Example: "GBK" -> "gbk", "Shift_JIS" -> "shift_jis".
4
+ */
5
+ export declare function normalizeEncoding(enc: any): any;
6
+ /**
7
+ * Universal text readability scorer.
8
+ * Gives positive points for valid readable CJK and printable ASCII,
9
+ * while heavily penalizing mojibake (replacement character \uFFFD) and unexpected control codes.
10
+ * Contains ZERO project-specific heuristics.
11
+ *
12
+ * @param {string} text
13
+ * @returns {number}
14
+ */
15
+ export declare function scoreText(text: any): number;
16
+ /**
17
+ * Decode raw QR bytes with multi-encoding fallback.
18
+ * Uses native TextDecoder with automatic validation and heuristic scoring.
19
+ *
20
+ * @param {Uint8Array} bytes
21
+ * @param {string} [detectedEncoding] Optional encoding hint from the caller.
22
+ * @returns {{ text: string, score: number, encoding: string }}
23
+ */
24
+ export declare function decodeWithFallback(bytes: Uint8Array, detectedEncoding?: string): {
25
+ text: string;
26
+ score: number;
27
+ encoding: string;
28
+ };
29
+ export declare function decodeChunks(chunks: any, characterSet: any): {
30
+ text: string;
31
+ encoding: any;
32
+ detectedEncoding: any;
33
+ };