@sythos/js_barcode_universal 1.1.0 → 1.2.5

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 (44) hide show
  1. package/LICENSE +16 -17
  2. package/NOTICE.md +24 -22
  3. package/README.md +100 -49
  4. package/bundle/sythos-barcode.esm.js +2058 -54
  5. package/bundle/sythos-barcode.js +2050 -54
  6. package/examples/create.html +2 -1
  7. package/licenses/README.md +58 -30
  8. package/licenses/aztec-code.license +12 -12
  9. package/licenses/codabar.license +9 -9
  10. package/licenses/code-11.license +9 -9
  11. package/licenses/code-128.license +6 -6
  12. package/licenses/code-39.license +6 -6
  13. package/licenses/code-93.license +7 -7
  14. package/licenses/data-matrix.license +11 -11
  15. package/licenses/ean-13.license +6 -6
  16. package/licenses/ean-8.license +6 -6
  17. package/licenses/gs1-128.license +6 -6
  18. package/licenses/isbn.license +7 -7
  19. package/licenses/itf-14.license +6 -6
  20. package/licenses/itf.license +6 -6
  21. package/licenses/micropdf417.license +96 -0
  22. package/licenses/msi-plessey.license +7 -7
  23. package/licenses/pdf417.license +37 -0
  24. package/licenses/pharmacode.license +7 -7
  25. package/licenses/qr-code.license +6 -6
  26. package/licenses/upc-a.license +7 -7
  27. package/licenses/upc-e.license +6 -6
  28. package/package.json +9 -2
  29. package/src/core/reed-solomon.js +326 -312
  30. package/src/index.js +77 -3
  31. package/src/micropdf417/compaction.js +116 -0
  32. package/src/micropdf417/decoder.js +183 -0
  33. package/src/micropdf417/detector.js +149 -0
  34. package/src/micropdf417/encoder.js +209 -0
  35. package/src/micropdf417/error-correction.js +55 -0
  36. package/src/micropdf417/index.js +49 -0
  37. package/src/micropdf417/tables.js +184 -0
  38. package/src/pdf417/compaction.js +298 -0
  39. package/src/pdf417/decoder.js +75 -0
  40. package/src/pdf417/detector.js +468 -0
  41. package/src/pdf417/encoder.js +91 -0
  42. package/src/pdf417/error-correction.js +47 -0
  43. package/src/pdf417/index.js +6 -0
  44. package/src/pdf417/tables.js +317 -0
package/src/index.js CHANGED
@@ -54,6 +54,8 @@ import { decodeOneD } from './oned/reader.js';
54
54
  import * as datamatrix from './datamatrix/index.js';
55
55
  import * as qr from './qr/index.js';
56
56
  import * as aztec from './aztec/index.js';
57
+ import * as pdf417 from './pdf417/index.js';
58
+ import * as micropdf417 from './micropdf417/index.js';
57
59
 
58
60
  export { BitMatrix };
59
61
  export {
@@ -72,6 +74,10 @@ export {
72
74
  encodeDataMatrix, decodeDataMatrix, detectDataMatrix, detectAndDecodeDataMatrix,
73
75
  } from './datamatrix/index.js';
74
76
  export { encodeAztec, decodeAztec, detectAztec, detectAndDecodeAztec } from './aztec/index.js';
77
+ export { encodePDF417, decodePDF417, detectPDF417, detectAndDecodePDF417 } from './pdf417/index.js';
78
+ export {
79
+ encodeMicroPDF417, decodeMicroPDF417, detectMicroPDF417, detectAndDecodeMicroPDF417,
80
+ } from './micropdf417/index.js';
75
81
 
76
82
  /**
77
83
  * @typedef {object} FormatInfo
@@ -99,6 +105,14 @@ const dataMatrixCanEncode = typeof datamatrix.encodeDataMatrix === 'function';
99
105
  const dataMatrixCanDecode = typeof datamatrix.detectAndDecodeDataMatrix === 'function';
100
106
  const aztecCanEncode = typeof aztec.encodeAztec === 'function';
101
107
  const aztecCanDecode = typeof aztec.detectAndDecodeAztec === 'function';
108
+ const pdf417CanEncode = typeof pdf417.encodePDF417 === 'function';
109
+ // The matrix decoder is complete, but automatic image localization is still
110
+ // limited to clean module-aligned symbols or an application-supplied
111
+ // quadrilateral. Keep the generic scanner capability opt-in until a
112
+ // perspective/noise corpus is passed.
113
+ const pdf417CanDecode = typeof pdf417.detectAndDecodePDF417 === 'function';
114
+ const microPdf417CanEncode = typeof micropdf417.encodeMicroPDF417 === 'function';
115
+ const microPdf417CanDecode = typeof micropdf417.detectAndDecodeMicroPDF417 === 'function';
102
116
 
103
117
  /**
104
118
  * Every format this build supports.
@@ -140,6 +154,20 @@ export function listFormats() {
140
154
  canRead: aztecCanDecode,
141
155
  kind: /** @type {'2D'} */ ('2D'),
142
156
  });
157
+ formats.push({
158
+ id: 'pdf417',
159
+ label: 'PDF417',
160
+ canWrite: pdf417CanEncode,
161
+ canRead: pdf417CanDecode,
162
+ kind: /** @type {'2D'} */ ('2D'),
163
+ });
164
+ formats.push({
165
+ id: 'micropdf417',
166
+ label: 'MicroPDF417',
167
+ canWrite: microPdf417CanEncode,
168
+ canRead: microPdf417CanDecode,
169
+ kind: /** @type {'2D'} */ ('2D'),
170
+ });
143
171
 
144
172
  return formats;
145
173
  }
@@ -163,6 +191,13 @@ export function listFormats() {
163
191
  * @param {number} [options.layers] Aztec layer count; automatic if omitted.
164
192
  * @param {boolean} [options.compact] Force an Aztec Compact or Full symbol.
165
193
  * @param {number} [options.eccPercent] Requested Aztec error-correction percentage.
194
+ * @param {number} [options.eccLevel] PDF417 error-correction level, 0-8.
195
+ * @param {number} [options.columns] PDF417 columns, 1-30.
196
+ * @param {number} [options.rows] PDF417 rows, 3-90.
197
+ * @param {number} [options.rowHeight] PDF417 row height in modules.
198
+ * @param {'auto'|'text'|'byte'|'numeric'} [options.compaction] PDF417 compaction mode.
199
+ * @param {number} [options.eci] MicroPDF417 byte-compaction ECI assignment (3 or 26).
200
+ * @param {number} [options.aspectRatio] Preferred MicroPDF417 symbol aspect ratio.
166
201
  * @returns {BitMatrix}
167
202
  */
168
203
  export function encode(text, options = {}) {
@@ -178,10 +213,16 @@ export function encode(text, options = {}) {
178
213
  if (format === 'aztec' || format === 'aztec-code') {
179
214
  return aztec.encodeAztec(value, options);
180
215
  }
216
+ if (format === 'pdf417' || format === 'pdf-417') {
217
+ return pdf417.encodePDF417(value, options);
218
+ }
219
+ if (format === 'micropdf417' || format === 'micro-pdf417' || format === 'micro-pdf-417') {
220
+ return micropdf417.encodeMicroPDF417(value, options);
221
+ }
181
222
 
182
223
  const entry = ONED_FORMATS[format];
183
224
  if (!entry) {
184
- const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix', 'aztec'].join(', ');
225
+ const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix', 'aztec', 'pdf417', 'micropdf417'].join(', ');
185
226
  throw new EncodeError(`Unknown format "${format}". Known formats: ${known}`);
186
227
  }
187
228
  return entry.encode(value, options);
@@ -191,12 +232,19 @@ export function encode(text, options = {}) {
191
232
  * @typedef {object} DecodeResult
192
233
  * @property {string} text
193
234
  * @property {string} format
194
- * @property {Uint8Array} [bytes] Raw payload, before text decoding.
235
+ * @property {Uint8Array} [bytes] Raw octets exposed by byte-oriented payload modes, before text decoding.
236
+ * @property {{mode: 'text'|'byte'|'numeric', text: string, bytes: Uint8Array, eci: number, latch: number|null, codewordStart: number, codewordEnd: number}[]} [segments] PDF417 compaction segments in source order.
195
237
  * @property {number} [version] QR version.
196
238
  * @property {string} [ecc] QR error-correction level.
197
239
  * @property {number} [layers] Aztec layer count.
198
240
  * @property {boolean} [compact] Whether an Aztec symbol is Compact.
199
241
  * @property {number} [corrections] Reed–Solomon corrections applied by an Aztec decode.
242
+ * @property {number} [rows] PDF417 row count.
243
+ * @property {number} [columns] PDF417 column count.
244
+ * @property {number} [eccLevel] PDF417 error-correction level.
245
+ * @property {number} [rowHeight] PDF417 row height in modules.
246
+ * @property {number} [variant] MicroPDF417 predefined variant number.
247
+ * @property {number} [eccCodewords] MicroPDF417 fixed error-correction codewords.
200
248
  */
201
249
 
202
250
  /**
@@ -219,6 +267,8 @@ export function decode(image, options = {}) {
219
267
  const wantQR = !want || want.has('qr') || want.has('qrcode');
220
268
  const wantDataMatrix = !want || want.has('datamatrix') || want.has('data-matrix');
221
269
  const wantAztec = !want || want.has('aztec') || want.has('aztec-code');
270
+ const wantPDF417 = !want || want.has('pdf417') || want.has('pdf-417');
271
+ const wantMicroPDF417 = !want || want.has('micropdf417') || want.has('micro-pdf417') || want.has('micro-pdf-417');
222
272
  const wantOneD = !want || [...want].some((f) => f in ONED_FORMATS);
223
273
 
224
274
  const source = LuminanceSource.fromImageData(image);
@@ -271,6 +321,30 @@ export function decode(image, options = {}) {
271
321
  }
272
322
  }
273
323
 
324
+ if (wantPDF417 && pdf417CanDecode) {
325
+ try {
326
+ const found = pdf417.detectAndDecodePDF417(bits);
327
+ if (found) results.push({ ...found, format: 'pdf417' });
328
+ } catch {
329
+ /* no PDF417 in this pass */
330
+ }
331
+ }
332
+
333
+ if (wantMicroPDF417 && microPdf417CanDecode) {
334
+ // MicroPDF417 detection measures runs across the whole raster. Hybrid
335
+ // thresholding can alter uniform modules near local-window boundaries,
336
+ // so retry the global threshold in auto mode as for the other 2D codes.
337
+ const microPdf417Bits = binarizer === 'auto' ? [bits, binarize(pass, 'global')] : [bits];
338
+ for (const candidateBits of microPdf417Bits) {
339
+ try {
340
+ const found = micropdf417.detectAndDecodeMicroPDF417(candidateBits);
341
+ if (found) { results.push({ ...found, format: 'micropdf417' }); break; }
342
+ } catch {
343
+ /* no MicroPDF417 with this threshold */
344
+ }
345
+ }
346
+ }
347
+
274
348
  if (wantOneD) {
275
349
  const oneDFormats = want ? [...want].filter((f) => f in ONED_FORMATS) : null;
276
350
  for (const found of decodeOneD(bits, { formats: oneDFormats, tryHarder })) {
@@ -305,4 +379,4 @@ export function decodeStrict(image, options) {
305
379
  }
306
380
 
307
381
  /** Library version, matching package.json. */
308
- export const VERSION = '1.1.0';
382
+ export const VERSION = '1.2.5';
@@ -0,0 +1,116 @@
1
+ /*!
2
+ * Sythos Barcode Suite
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Sythos
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ * SPDX-License-Identifier: MIT
27
+ *
28
+ * Original work. No code from any other barcode implementation.
29
+ */
30
+
31
+ /** MicroPDF417 high-level compaction adapter. @module micropdf417/compaction */
32
+
33
+ import { EncodeError } from '../core/errors.js';
34
+ import {
35
+ compactPdf417Bytes,
36
+ compactPdf417Numeric,
37
+ compactPdf417Text,
38
+ } from '../pdf417/compaction.js';
39
+
40
+ function byteLength(value) {
41
+ if (value instanceof Uint8Array) return value.byteLength;
42
+ if (ArrayBuffer.isView(value)) return value.byteLength;
43
+ return -1;
44
+ }
45
+
46
+ function assertNotEmpty(value) {
47
+ if ((typeof value === 'string' && value.length === 0) || byteLength(value) === 0) {
48
+ throw new EncodeError('MicroPDF417: value must not be empty');
49
+ }
50
+ }
51
+
52
+ function latin1Bytes(value) {
53
+ if (typeof value !== 'string') return value;
54
+ const bytes = [];
55
+ for (const character of value) {
56
+ const codePoint = character.codePointAt(0);
57
+ if (codePoint > 255) {
58
+ throw new EncodeError('MicroPDF417 ECI 3: string contains a character outside ISO-8859-1');
59
+ }
60
+ bytes.push(codePoint);
61
+ }
62
+ return Uint8Array.from(bytes);
63
+ }
64
+
65
+ function compactByte(value, eci) {
66
+ if (eci === undefined) return compactPdf417Bytes(value);
67
+ if (eci === 3) return compactPdf417Bytes(latin1Bytes(value));
68
+ if (eci === 26) {
69
+ if (typeof value !== 'string') {
70
+ throw new EncodeError('MicroPDF417 ECI 26: value must be a string so UTF-8 validity is known');
71
+ }
72
+ const encoded = compactPdf417Bytes(value);
73
+ return encoded[0] === 927 && encoded[1] === 26 ? encoded : [927, 26, ...encoded];
74
+ }
75
+ throw new EncodeError('MicroPDF417: supported ECI assignment numbers are 3 and 26');
76
+ }
77
+
78
+ /**
79
+ * Compact one MicroPDF417 value.
80
+ *
81
+ * Unlike PDF417, MicroPDF417 starts in Byte Compaction. Text therefore needs
82
+ * an explicit 900 latch. Byte compaction always emits 901 or 924 so its start
83
+ * state is unambiguous, including when an ECI designator precedes it.
84
+ */
85
+ export function compactMicroPDF417(value, options = {}) {
86
+ assertNotEmpty(value);
87
+ const mode = options.compaction ?? 'auto';
88
+ const eci = options.eci;
89
+ if (eci !== undefined && eci !== 3 && eci !== 26) {
90
+ throw new EncodeError('MicroPDF417: supported ECI assignment numbers are 3 and 26');
91
+ }
92
+
93
+ if (mode === 'text') {
94
+ if (eci !== undefined) throw new EncodeError('MicroPDF417: explicit ECI is supported only with byte compaction');
95
+ return [900, ...compactPdf417Text(value)];
96
+ }
97
+ if (mode === 'numeric') {
98
+ if (eci !== undefined) throw new EncodeError('MicroPDF417: explicit ECI is supported only with byte compaction');
99
+ return compactPdf417Numeric(value);
100
+ }
101
+ if (mode === 'byte') return compactByte(value, eci);
102
+ if (mode !== 'auto') {
103
+ throw new EncodeError(`MicroPDF417: unsupported compaction mode ${JSON.stringify(mode)}`);
104
+ }
105
+
106
+ if (eci !== undefined) return compactByte(value, eci);
107
+ if (typeof value === 'string' && /^\d{13,}$/.test(value)) return compactPdf417Numeric(value);
108
+ if (typeof value === 'string') {
109
+ try {
110
+ return [900, ...compactPdf417Text(value)];
111
+ } catch (error) {
112
+ if (!(error instanceof EncodeError)) throw error;
113
+ }
114
+ }
115
+ return compactPdf417Bytes(value);
116
+ }
@@ -0,0 +1,183 @@
1
+ /*!
2
+ * Sythos Barcode Suite
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Sythos
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ * SPDX-License-Identifier: MIT
27
+ *
28
+ * Original work. No code from any other barcode implementation.
29
+ */
30
+
31
+ /**
32
+ * Direct-module MicroPDF417 decoder.
33
+ *
34
+ * This module reads an already sampled, axis-aligned `BitMatrix`. Image finding,
35
+ * perspective correction, and recognition from photographic pixels are deliberately
36
+ * outside this first decoder boundary. The RAP sequence is authoritative for format
37
+ * detection; matrix metadata is used only as an optional row-height hint.
38
+ *
39
+ * @module micropdf417/decoder
40
+ */
41
+
42
+ import { FormatError } from '../core/errors.js';
43
+ import { decodePdf417CompactionDetailed } from '../pdf417/compaction.js';
44
+ import { pdf417CodewordForPattern } from '../pdf417/tables.js';
45
+ import { microPdf417CorrectErrors } from './error-correction.js';
46
+ import {
47
+ MICROPDF417_VARIANTS,
48
+ microPdf417RapSequence,
49
+ microPdf417RowAddress,
50
+ microPdf417VariantByNumber,
51
+ } from './tables.js';
52
+
53
+ function symbolWidth(columns) {
54
+ return 21 + columns * 17 + (columns > 2 ? 10 : 0);
55
+ }
56
+
57
+ function bits(matrix, y, x, width) {
58
+ let value = 0;
59
+ for (let i = 0; i < width; i++) value = (value << 1) | (matrix.get(x + i, y) ? 1 : 0);
60
+ return value;
61
+ }
62
+
63
+ function widthsToBits(widths) {
64
+ let dark = true;
65
+ let out = '';
66
+ for (const digit of widths) {
67
+ out += (dark ? '1' : '0').repeat(digit.charCodeAt(0) - 48);
68
+ dark = !dark;
69
+ }
70
+ return out;
71
+ }
72
+
73
+ function hasExpectedBits(matrix, y, x, sequence) {
74
+ const expected = widthsToBits(sequence);
75
+ for (let i = 0; i < expected.length; i++) {
76
+ if ((matrix.get(x + i, y) ? '1' : '0') !== expected[i]) return false;
77
+ }
78
+ return true;
79
+ }
80
+
81
+ function centralRapAfter(entry, column) {
82
+ return (entry.columns === 3 && column === 0) ||
83
+ (entry.columns === 4 && column === 1);
84
+ }
85
+
86
+ /** Return true when all address patterns for this format candidate agree. */
87
+ function hasValidRowAddresses(matrix, entry, rowHeight) {
88
+ for (let row = 0; row < entry.rows; row++) {
89
+ const y = row * rowHeight;
90
+ const address = microPdf417RowAddress(entry, row);
91
+ let x = 0;
92
+ if (!hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.left, 'side'))) return false;
93
+ x += 10;
94
+ for (let column = 0; column < entry.columns; column++) {
95
+ x += 17;
96
+ if (centralRapAfter(entry, column)) {
97
+ if (address.center === null ||
98
+ !hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.center, 'center'))) return false;
99
+ x += 10;
100
+ }
101
+ }
102
+ if (!hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.right, 'side'))) return false;
103
+ x += 10;
104
+ if (!matrix.get(x, y) || x + 1 !== matrix.width) return false;
105
+ }
106
+ return true;
107
+ }
108
+
109
+ function candidateFormats(matrix, options) {
110
+ const metadataHeight = matrix.micropdf417?.rowHeight;
111
+ const requestedHeight = options.rowHeight ?? metadataHeight;
112
+ if (requestedHeight !== undefined && (!Number.isInteger(requestedHeight) || requestedHeight < 1)) {
113
+ throw new FormatError('MicroPDF417: rowHeight must be a positive integer');
114
+ }
115
+ const requestedVariant = options.variant === undefined ? null : microPdf417VariantByNumber(options.variant);
116
+ const pool = requestedVariant ? [requestedVariant] : MICROPDF417_VARIANTS;
117
+ const candidates = [];
118
+ for (const entry of pool) {
119
+ if (matrix.width !== symbolWidth(entry.columns)) continue;
120
+ if (matrix.height % entry.rows) continue;
121
+ const rowHeight = matrix.height / entry.rows;
122
+ if (requestedHeight !== undefined && rowHeight !== requestedHeight) continue;
123
+ if (hasValidRowAddresses(matrix, entry, rowHeight)) candidates.push({ entry, rowHeight });
124
+ }
125
+ return candidates;
126
+ }
127
+
128
+ function resolveFormat(matrix, options) {
129
+ if (!matrix?.width || !matrix?.height || typeof matrix.get !== 'function') {
130
+ throw new FormatError('MicroPDF417: matrix with width, height and get() is required');
131
+ }
132
+ const candidates = candidateFormats(matrix, options);
133
+ if (!candidates.length) throw new FormatError('MicroPDF417: no variant matches matrix geometry and row-address patterns');
134
+ if (candidates.length > 1) throw new FormatError('MicroPDF417: row-address patterns do not identify a unique variant');
135
+ return candidates[0];
136
+ }
137
+
138
+ function readCodewords(matrix, entry, rowHeight) {
139
+ const codewords = [];
140
+ const erasures = [];
141
+ for (let row = 0; row < entry.rows; row++) {
142
+ const y = row * rowHeight;
143
+ const address = microPdf417RowAddress(entry, row);
144
+ let x = 10;
145
+ for (let column = 0; column < entry.columns; column++) {
146
+ const decoded = pdf417CodewordForPattern(bits(matrix, y, x, 17));
147
+ if (!decoded || decoded.cluster !== address.cluster) {
148
+ erasures.push(codewords.length);
149
+ codewords.push(0);
150
+ } else {
151
+ codewords.push(decoded.codeword);
152
+ }
153
+ x += 17;
154
+ if (centralRapAfter(entry, column)) x += 10;
155
+ }
156
+ }
157
+ return { codewords, erasures };
158
+ }
159
+
160
+ /**
161
+ * Decode a sampled MicroPDF417 matrix.
162
+ *
163
+ * The complete fixed data region is compacted after correction. Encoder padding
164
+ * is PDF417 Text latch 900, which contributes no characters at the end of the
165
+ * payload. This avoids relying on non-symbol metadata for payload length.
166
+ */
167
+ export function decodeMicroPDF417(matrix, options = {}) {
168
+ const { entry, rowHeight } = resolveFormat(matrix, options);
169
+ const { codewords, erasures } = readCodewords(matrix, entry, rowHeight);
170
+ const corrections = microPdf417CorrectErrors(codewords, entry, erasures);
171
+ const data = codewords.slice(0, entry.dataCodewords);
172
+ const decoded = decodePdf417CompactionDetailed(data);
173
+ return {
174
+ ...decoded,
175
+ codewords,
176
+ rows: entry.rows,
177
+ columns: entry.columns,
178
+ variant: entry.id,
179
+ eccCodewords: entry.eccCodewords,
180
+ rowHeight,
181
+ corrections,
182
+ };
183
+ }
@@ -0,0 +1,149 @@
1
+ /*!
2
+ * Sythos Barcode Suite
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Sythos
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ * SPDX-License-Identifier: MIT
27
+ *
28
+ * Original work. No code from any other barcode implementation.
29
+ */
30
+
31
+ /**
32
+ * Axis-aligned MicroPDF417 raster detection.
33
+ *
34
+ * A MicroPDF417 symbol has a fixed module width for each column count and a
35
+ * dark leading and trailing module in every row. Consequently the bounding
36
+ * rectangle of dark pixels identifies the complete symbol even when a light
37
+ * quiet zone surrounds it. Its width determines the integer raster scale;
38
+ * the existing direct-module decoder then verifies every row-address pattern
39
+ * and selects the exact variant. This is intentionally narrower than the
40
+ * PDF417 photo detector: it handles clean binarized rasters only, not skew or
41
+ * projective camera images.
42
+ *
43
+ * @module micropdf417/detector
44
+ */
45
+
46
+ import { BitMatrix } from '../core/bit-matrix.js';
47
+ import { decodeMicroPDF417 } from './decoder.js';
48
+
49
+ /** @typedef {{x:number, y:number}} Point */
50
+
51
+ // Each row has two 10-module side RAPs, a final separator, and 17 modules for
52
+ // each data column. Three and four columns also contain one central RAP.
53
+ function symbolWidth(columns) { return 21 + columns * 17 + (columns > 2 ? 10 : 0); }
54
+ const WIDTHS = [1, 2, 3, 4].map(symbolWidth);
55
+
56
+ function rotateClockwise(source) {
57
+ const rotated = new BitMatrix(source.height, source.width);
58
+ for (let y = 0; y < source.height; y++) for (let x = 0; x < source.width; x++) {
59
+ if (source.get(x, y)) rotated.set(source.height - 1 - y, x);
60
+ }
61
+ return rotated;
62
+ }
63
+
64
+ function integerScale(width, modules) {
65
+ if (width % modules) return 0;
66
+ const scale = width / modules;
67
+ return Number.isInteger(scale) && scale > 0 ? scale : 0;
68
+ }
69
+
70
+ /** Collapse exact integer scale blocks using a majority vote. */
71
+ function sampleRaster(image, bounds, modulesWide, scale) {
72
+ const modulesHigh = bounds.height / scale;
73
+ if (!Number.isInteger(modulesHigh) || modulesHigh < 1) return null;
74
+ const matrix = new BitMatrix(modulesWide, modulesHigh);
75
+ for (let y = 0; y < modulesHigh; y++) for (let x = 0; x < modulesWide; x++) {
76
+ let dark = 0;
77
+ for (let py = 0; py < scale; py++) for (let px = 0; px < scale; px++) {
78
+ if (image.get(bounds.x + x * scale + px, bounds.y + y * scale + py)) dark++;
79
+ }
80
+ if (dark * 2 >= scale * scale) matrix.set(x, y);
81
+ }
82
+ return matrix;
83
+ }
84
+
85
+ function rectangle(bounds) {
86
+ return [
87
+ { x: bounds.x, y: bounds.y },
88
+ { x: bounds.x + bounds.width, y: bounds.y },
89
+ { x: bounds.x + bounds.width, y: bounds.y + bounds.height },
90
+ { x: bounds.x, y: bounds.y + bounds.height },
91
+ ];
92
+ }
93
+
94
+ function detectAxisAligned(image, options) {
95
+ const bounds = image.getBounds();
96
+ if (!bounds) return null;
97
+ for (const width of WIDTHS) {
98
+ const scale = integerScale(bounds.width, width);
99
+ if (!scale || bounds.height % scale) continue;
100
+ const matrix = sampleRaster(image, bounds, width, scale);
101
+ if (!matrix) continue;
102
+ try {
103
+ const decoded = decodeMicroPDF417(matrix, options);
104
+ return { matrix, corners: rectangle(bounds), moduleSize: scale, ...decoded };
105
+ } catch { /* The RAP sequence is not a MicroPDF417 symbol of this width. */ }
106
+ }
107
+ return null;
108
+ }
109
+
110
+ /**
111
+ * Detect and decode one clean, binarized MicroPDF417 raster.
112
+ *
113
+ * Integer upscaling and quiet zones are accepted. The image is retried at all
114
+ * quarter-turns, but arbitrary angles and perspective require caller-side
115
+ * rectification before this function is used. `rotation` reports the clockwise
116
+ * orientation of the supplied input relative to a normally oriented symbol;
117
+ * it is not the inverse correction applied internally while searching.
118
+ *
119
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
120
+ * @param {object} [options] Passed to {@link decodeMicroPDF417}.
121
+ * @returns {(ReturnType<typeof decodeMicroPDF417> & {matrix: BitMatrix, corners: Point[], moduleSize: number, rotation: number}) | null}
122
+ */
123
+ export function detectMicroPDF417(binaryImage, options = {}) {
124
+ if (!binaryImage?.width || !binaryImage?.height || typeof binaryImage.get !== 'function') return null;
125
+ let oriented = binaryImage;
126
+ let toOriginal = (point) => ({ x: point.x, y: point.y });
127
+ for (let turns = 0; turns < 4; turns++) {
128
+ const found = detectAxisAligned(oriented, options);
129
+ // Search rotates clockwise to normalize the input. Public rotation has the
130
+ // opposite meaning: it describes how the input itself was rotated.
131
+ if (found) return {
132
+ ...found,
133
+ rotation: (360 - turns * 90) % 360,
134
+ corners: found.corners.map(toOriginal),
135
+ };
136
+ const previous = oriented;
137
+ const previousToOriginal = toOriginal;
138
+ oriented = rotateClockwise(previous);
139
+ // Boundary coordinates (rather than just pixel centres) are transformed
140
+ // here, so callers can draw the returned rectangle directly on the input.
141
+ toOriginal = (point) => previousToOriginal({ x: point.y, y: previous.height - point.x });
142
+ }
143
+ return null;
144
+ }
145
+
146
+ /** Alias kept symmetric with the other 2D readers. */
147
+ export function detectAndDecodeMicroPDF417(binaryImage, options = {}) {
148
+ return detectMicroPDF417(binaryImage, options);
149
+ }