qr-decoder-js 1.0.5 → 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 -121
  4. package/README_ZH.md +19 -117
  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} +18 -3
  52. package/package.json +17 -19
  53. package/dist/qr-decoder.js +0 -2611
  54. package/dist/qr-decoder.umd.cjs +0 -1
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ // Main decoding pipeline using the bundled TypeScript QR engine
3
+ // with robust multi-channel (blue/red/contrast), edge sharpening, CLAHE, tilt shear compensation,
4
+ // center-zoom for distant codes, and universal multi-encoding detection.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.decodeQRImageData = decodeQRImageData;
7
+ exports.decodeQRFile = decodeQRFile;
8
+ const scanner_js_1 = require("../native/scanner.js");
9
+ const preprocess_js_1 = require("./preprocess.js");
10
+ const encoding_js_1 = require("./encoding.js");
11
+ const DEFAULT_READER_OPTIONS = {
12
+ tryInvert: true,
13
+ };
14
+ const MODES = ['fast', 'balanced', 'aggressive'];
15
+ /**
16
+ * Decode a QR code from ImageData.
17
+ *
18
+ * @param {ImageData} imageData
19
+ * @param {object} [options]
20
+ * @param {'fast'|'balanced'|'aggressive'} [options.mode='aggressive']
21
+ * - fast: original only;
22
+ * - balanced: original + contrast-stretched red/blue-enhanced + sharpen + CLAHE + fast tilt shear + center-zoom;
23
+ * - aggressive: balanced + full 6-angle shear + color-aware quiet-zone, morphology,
24
+ * Otsu, adaptive-binary, and inverted variants.
25
+ * @returns {Promise<import('../types').DecodeResult>}
26
+ */
27
+ async function decodeQRImageData(imageData, options = {}) {
28
+ if (!imageData ||
29
+ typeof imageData.width !== 'number' ||
30
+ typeof imageData.height !== 'number' ||
31
+ !imageData.data) {
32
+ return { success: false, error: 'Invalid image data (expected ImageData or {width,height,data})' };
33
+ }
34
+ const { mode = 'aggressive', ...readerOverrides } = options;
35
+ const effectiveMode = MODES.includes(mode) ? mode : 'balanced';
36
+ const readerOptions = { ...DEFAULT_READER_OPTIONS, ...readerOverrides };
37
+ const attempts = buildDecodeAttempts(imageData, effectiveMode, readerOptions.tryInvert !== false);
38
+ let hit = null;
39
+ let successVersion = null;
40
+ for (const ver of attempts) {
41
+ try {
42
+ const pixels = ver.data.data instanceof Uint8ClampedArray
43
+ ? ver.data.data : new Uint8ClampedArray(ver.data.data);
44
+ hit = (0, scanner_js_1.scanQR)(pixels, ver.data.width, ver.data.height, readerOptions.tryInvert !== false, ver.soft === true);
45
+ if (hit) {
46
+ successVersion = ver.label;
47
+ break;
48
+ }
49
+ }
50
+ catch (e) {
51
+ console.warn(`Preprocess version "${ver.label}" decode failed:`, e);
52
+ }
53
+ }
54
+ if (!hit) {
55
+ return { success: false, error: 'No QR code found in the image' };
56
+ }
57
+ try {
58
+ const result = (0, encoding_js_1.decodeChunks)(hit.chunks, options.characterSet);
59
+ return {
60
+ success: true,
61
+ text: result.text,
62
+ encoding: result.encoding,
63
+ detectedEncoding: result.detectedEncoding,
64
+ rawBytes: new Uint8Array(hit.bytes),
65
+ qrVersion: hit.version,
66
+ version: successVersion,
67
+ };
68
+ }
69
+ catch (e) {
70
+ return { success: false, error: `Unable to decode QR text: ${e.message}` };
71
+ }
72
+ }
73
+ /**
74
+ * Build an ordered list of decode attempts lazily.
75
+ *
76
+ * @param {ImageData} imageData
77
+ * @param {'fast'|'balanced'|'aggressive'} mode
78
+ * @yields {{ data: ImageData, label: string }}
79
+ */
80
+ function* buildDecodeAttempts(imageData, mode = 'balanced', tryInvert = true) {
81
+ const { width, height } = imageData;
82
+ // Stage 1: original (covers standard B&W QR codes in single pass)
83
+ yield { data: imageData, label: 'original' };
84
+ if (mode === 'fast')
85
+ return;
86
+ // Stage 2: high-efficiency color/blue-ink rescue channels (contrast-stretched 2*R-B and red-channel)
87
+ const preprocessVariants = (0, preprocess_js_1.generatePreprocessVariants)(imageData);
88
+ for (const variant of preprocessVariants) {
89
+ yield { data: variant.data, label: variant.label };
90
+ }
91
+ // Stage 3: Sharpened red channel (directly restores blurry, out-of-focus, or distant blue QR codes)
92
+ const redVariant = preprocessVariants.find((variant) => variant.label === 'red-stretched') ||
93
+ preprocessVariants.find((variant) => variant.label === 'red-channel');
94
+ if (redVariant) {
95
+ yield {
96
+ data: (0, preprocess_js_1.sharpenImageData)(redVariant.data, 1.2),
97
+ label: 'sharpen-red',
98
+ };
99
+ }
100
+ // Try inexpensive threshold variants before the geometric rescue passes.
101
+ // These often resolve colored and low-contrast codes without shearing or cropping.
102
+ if (mode === 'aggressive') {
103
+ const sources = [
104
+ { data: imageData, label: 'gray' },
105
+ ...preprocessVariants.map((variant) => ({ data: variant.data, label: variant.label })),
106
+ ];
107
+ for (const source of sources) {
108
+ const gray = (0, preprocess_js_1.toGray)(source.data);
109
+ yield { data: (0, preprocess_js_1.grayToImageData)((0, preprocess_js_1.toOtsuBinary)(gray, width, height), width, height), label: `otsu-binary-${source.label}` };
110
+ yield { data: (0, preprocess_js_1.grayToImageData)((0, preprocess_js_1.toAdaptiveBinary)(gray, width, height), width, height), label: `adaptive-binary-${source.label}` };
111
+ }
112
+ const rescueSources = [
113
+ { data: imageData, label: '' },
114
+ ...preprocessVariants.map((variant) => ({ data: variant.data, label: `${variant.label}-` })),
115
+ ];
116
+ for (const source of rescueSources)
117
+ for (const variant of (0, preprocess_js_1.generateDotMatrixFixVariants)(source.data)) {
118
+ yield { data: variant.data, label: `${source.label}${variant.label}` };
119
+ }
120
+ }
121
+ // Stage 4: CLAHE (local-contrast enhancement: directly rescues faint, shadow-covered, or unevenly lit codes)
122
+ for (const variant of (0, preprocess_js_1.generateCLAHEVariants)(imageData)) {
123
+ yield { data: variant.data, label: variant.label };
124
+ }
125
+ // Stage 5: Fast Tilt / Perspective Shear on red-channel (primary pitch & yaw tilts)
126
+ // Essential for live camera scanning when phone or target is tilted forward/backward or sideways
127
+ const fastShearAngles = [
128
+ { sx: 0, sy: 0.35, label: 'tilt-pitch-down' },
129
+ { sx: 0, sy: -0.35, label: 'tilt-pitch-up' },
130
+ { sx: 0.35, sy: 0, label: 'tilt-yaw-right' },
131
+ { sx: -0.35, sy: 0, label: 'tilt-yaw-left' },
132
+ ];
133
+ for (const variant of (0, preprocess_js_1.generateShearVariants)(redVariant ? redVariant.data : imageData, fastShearAngles)) {
134
+ yield { data: variant.data, label: `${variant.label}-red` };
135
+ }
136
+ // Stage 6: Center crop for distant QR codes in large frames (>= 380px)
137
+ if (width >= 380 && height >= 380) {
138
+ const cropped = (0, preprocess_js_1.centerCrop)(imageData, 0.6);
139
+ const croppedVariants = (0, preprocess_js_1.generatePreprocessVariants)(cropped);
140
+ const croppedRed = croppedVariants.find((variant) => variant.label === 'red-stretched') ||
141
+ croppedVariants.find((variant) => variant.label === 'red-channel');
142
+ if (croppedRed) {
143
+ yield { data: croppedRed.data, label: 'center-crop-red' };
144
+ yield { data: (0, preprocess_js_1.sharpenImageData)(croppedRed.data, 1.2), label: 'center-crop-sharpen-red' };
145
+ }
146
+ }
147
+ if (mode === 'balanced')
148
+ return;
149
+ // Stage 7: Full 6-direction tilt shear on original image
150
+ for (const variant of (0, preprocess_js_1.generateShearVariants)(imageData)) {
151
+ yield { data: variant.data, label: variant.label };
152
+ }
153
+ // Stage 8: Pad each color-rescue channel so edge-cropped codes regain a quiet zone.
154
+ const quietZoneSources = [
155
+ { data: imageData, label: 'quiet-zone' },
156
+ ...preprocessVariants.map((variant) => ({
157
+ data: variant.data,
158
+ label: `quiet-zone-${variant.label}`,
159
+ })),
160
+ ];
161
+ for (const source of quietZoneSources) {
162
+ const padded = (0, preprocess_js_1.addQuietZone)(source.data);
163
+ if (padded) {
164
+ yield { data: padded, label: source.label };
165
+ }
166
+ }
167
+ const binarySources = [
168
+ { data: imageData, label: 'gray' },
169
+ ...preprocessVariants.map((variant) => ({
170
+ data: variant.data,
171
+ label: variant.label,
172
+ })),
173
+ ];
174
+ if (tryInvert)
175
+ for (const source of binarySources) {
176
+ const inverted = (0, preprocess_js_1.generateInvertedVariant)(source.data);
177
+ yield { data: inverted.data, label: `inverted-${source.label}` };
178
+ }
179
+ if (Math.max(width, height) <= 350) {
180
+ const enlarged = (0, preprocess_js_1.enlargeSmallColorCode)(imageData);
181
+ if (enlarged)
182
+ yield { data: enlarged, label: 'small-color-upscaled', soft: true };
183
+ }
184
+ }
185
+ /**
186
+ * Decode a QR code from various input types:
187
+ * File, Blob, ImageData, HTMLImageElement, HTMLCanvasElement, or OffscreenCanvas.
188
+ *
189
+ * @param {File|Blob|ImageData|HTMLImageElement|HTMLCanvasElement|OffscreenCanvas} input
190
+ * @param {object} [options]
191
+ * @returns {Promise<import('../types').DecodeResult>}
192
+ */
193
+ async function decodeQRFile(input, options = {}) {
194
+ const imgData = await toImageData(input);
195
+ const effectiveOptions = { mode: 'aggressive', ...options };
196
+ return decodeQRImageData(imgData, effectiveOptions);
197
+ }
198
+ /** Convert input types into a single ImageData. */
199
+ async function toImageData(input) {
200
+ if (typeof ImageData !== 'undefined' && input instanceof ImageData)
201
+ return input;
202
+ if (input &&
203
+ typeof input.width === 'number' &&
204
+ typeof input.height === 'number' &&
205
+ input.data) {
206
+ return input;
207
+ }
208
+ if (typeof HTMLImageElement !== 'undefined' && input instanceof HTMLImageElement) {
209
+ return imageDataFromElement(input);
210
+ }
211
+ if (typeof HTMLCanvasElement !== 'undefined' && input instanceof HTMLCanvasElement) {
212
+ const ctx = input.getContext('2d');
213
+ return ctx.getImageData(0, 0, input.width, input.height);
214
+ }
215
+ if (typeof OffscreenCanvas !== 'undefined' && input instanceof OffscreenCanvas) {
216
+ const ctx = input.getContext('2d');
217
+ return ctx.getImageData(0, 0, input.width, input.height);
218
+ }
219
+ if (typeof Blob !== 'undefined' && input instanceof Blob) {
220
+ return imageDataFromBlob(input);
221
+ }
222
+ throw new TypeError('Unsupported input type; expected File, Blob, ImageData, HTMLImageElement, or Canvas');
223
+ }
224
+ function imageDataFromElement(img) {
225
+ const canvas = document.createElement('canvas');
226
+ canvas.width = img.naturalWidth || img.width;
227
+ canvas.height = img.naturalHeight || img.height;
228
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
229
+ ctx.drawImage(img, 0, 0);
230
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
231
+ }
232
+ function imageDataFromBlob(blob) {
233
+ return new Promise((resolve, reject) => {
234
+ const url = URL.createObjectURL(blob);
235
+ const img = new Image();
236
+ img.onload = () => {
237
+ URL.revokeObjectURL(url);
238
+ resolve(imageDataFromElement(img));
239
+ };
240
+ img.onerror = () => {
241
+ URL.revokeObjectURL(url);
242
+ reject(new Error('Failed to load image from blob'));
243
+ };
244
+ img.src = url;
245
+ });
246
+ }
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ // Character encoding name normalization and multi-encoding fallback decoding.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.normalizeEncoding = normalizeEncoding;
5
+ exports.scoreText = scoreText;
6
+ exports.decodeWithFallback = decodeWithFallback;
7
+ exports.decodeChunks = decodeChunks;
8
+ const encodingAliasMap = {
9
+ // Simplified Chinese
10
+ GB: 'gbk',
11
+ GBK: 'gbk',
12
+ GB2312: 'gb2312',
13
+ GB_2312: 'gb2312',
14
+ GB18030: 'gb18030',
15
+ GB_18030: 'gb18030',
16
+ // Traditional Chinese
17
+ BIG5: 'big5',
18
+ BIG_5: 'big5',
19
+ BIG5_HKSCS: 'big5',
20
+ // UTF / ASCII
21
+ 'UTF-8': 'utf-8',
22
+ UTF8: 'utf-8',
23
+ UTF_8: 'utf-8',
24
+ UNICODEUTF8: 'utf-8',
25
+ 'UTF-16': 'utf-16',
26
+ UTF16: 'utf-16',
27
+ 'UTF-16LE': 'utf-16le',
28
+ 'UTF-16BE': 'utf-16be',
29
+ UCS2: 'utf-16le',
30
+ 'UCS-2': 'utf-16le',
31
+ ASCII: 'ascii',
32
+ 'US-ASCII': 'ascii',
33
+ // Western
34
+ 'WINDOWS-1252': 'windows-1252',
35
+ CP1252: 'windows-1252',
36
+ 'ISO-8859-1': 'windows-1252',
37
+ 'ISO8859-1': 'windows-1252',
38
+ LATIN1: 'windows-1252',
39
+ // Japanese
40
+ SHIFT_JIS: 'shift_jis',
41
+ SHIFTJIS: 'shift_jis',
42
+ SJIS: 'shift_jis',
43
+ MS_KANJI: 'shift_jis',
44
+ 'EUC-JP': 'euc-jp',
45
+ EUC_JP: 'euc-jp',
46
+ EUCJP: 'euc-jp',
47
+ // Korean
48
+ 'EUC-KR': 'euc-kr',
49
+ EUC_KR: 'euc-kr',
50
+ EUCKR: 'euc-kr',
51
+ 'KS_C_5601-1987': 'euc-kr',
52
+ // Other
53
+ 'ISO-2022-JP': 'iso-2022-jp',
54
+ 'ISO-2022-KR': 'iso-2022-kr',
55
+ };
56
+ /**
57
+ * Normalize an encoding name into a label understood by TextDecoder.
58
+ * Example: "GBK" -> "gbk", "Shift_JIS" -> "shift_jis".
59
+ */
60
+ function normalizeEncoding(enc) {
61
+ if (!enc)
62
+ return 'utf-8';
63
+ let upper = String(enc).trim().toUpperCase();
64
+ upper = upper.replace(/\(.*?\)/g, '').trim();
65
+ if (encodingAliasMap[upper])
66
+ return encodingAliasMap[upper];
67
+ return upper.replace(/_/g, '-').toLowerCase();
68
+ }
69
+ // Fallback candidate list: standard universal CJK and western encodings
70
+ const FALLBACK_ENCODINGS = [
71
+ 'utf-8',
72
+ 'gb18030',
73
+ 'gbk',
74
+ 'big5',
75
+ 'gb2312',
76
+ 'shift_jis',
77
+ 'euc-jp',
78
+ 'euc-kr',
79
+ 'windows-1252',
80
+ ];
81
+ const TIEBREAK_PREFERENCE = [
82
+ 'utf-8',
83
+ 'gb18030',
84
+ 'gbk',
85
+ 'gb2312',
86
+ 'big5',
87
+ 'shift_jis',
88
+ 'euc-jp',
89
+ 'euc-kr',
90
+ 'windows-1252',
91
+ ];
92
+ function tiebreakRank(enc) {
93
+ const idx = TIEBREAK_PREFERENCE.indexOf(enc);
94
+ return idx === -1 ? TIEBREAK_PREFERENCE.length : idx;
95
+ }
96
+ /**
97
+ * Universal text readability scorer.
98
+ * Gives positive points for valid readable CJK and printable ASCII,
99
+ * while heavily penalizing mojibake (replacement character \uFFFD) and unexpected control codes.
100
+ * Contains ZERO project-specific heuristics.
101
+ *
102
+ * @param {string} text
103
+ * @returns {number}
104
+ */
105
+ function scoreText(text) {
106
+ if (!text)
107
+ return -Infinity;
108
+ // CJK unified ideographs + kana + hangul
109
+ const cjkCount = (text.match(/[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af\uf900-\ufaff]/g) || []).length;
110
+ const replacementCount = (text.match(/\uFFFD/g) || []).length;
111
+ let printable = 0;
112
+ let garbage = 0;
113
+ for (let i = 0; i < text.length; i++) {
114
+ const c = text.charCodeAt(i);
115
+ // Printable characters + whitespace (\t, \n, \r)
116
+ if ((c >= 0x20 && c !== 0x7f) || c === 0x09 || c === 0x0a || c === 0x0d) {
117
+ printable++;
118
+ }
119
+ else {
120
+ garbage++;
121
+ }
122
+ }
123
+ // Heavy penalties for common mojibake sequences when multi-byte bytes are misinterpreted as Latin-1
124
+ let mojibakePenalty = 0;
125
+ if (/[¹ÐÖ¿ÅÆÑÌ]/.test(text))
126
+ mojibakePenalty += 40;
127
+ if (/Ã.|Â./.test(text))
128
+ mojibakePenalty += 30;
129
+ const ratioPenalty = text.length > 0 ? (replacementCount + garbage) / text.length : 1;
130
+ return (cjkCount * 10 +
131
+ printable * 2 -
132
+ mojibakePenalty -
133
+ (replacementCount + garbage) * 100 -
134
+ (ratioPenalty > 0.4 ? 10000 : 0));
135
+ }
136
+ /**
137
+ * Decode raw QR bytes with multi-encoding fallback.
138
+ * Uses native TextDecoder with automatic validation and heuristic scoring.
139
+ *
140
+ * @param {Uint8Array} bytes
141
+ * @param {string} [detectedEncoding] Optional encoding hint from the caller.
142
+ * @returns {{ text: string, score: number, encoding: string }}
143
+ */
144
+ function decodeWithFallback(bytes, detectedEncoding) {
145
+ // 1. Strict UTF-8 verification: if bytes form completely valid UTF-8 without error,
146
+ // UTF-8 has the highest confidence.
147
+ let validUtf8 = false;
148
+ try {
149
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
150
+ validUtf8 = true;
151
+ }
152
+ catch {
153
+ // Not valid UTF-8
154
+ }
155
+ const candidates = [normalizeEncoding(detectedEncoding), ...FALLBACK_ENCODINGS];
156
+ const unique = [];
157
+ for (const enc of candidates) {
158
+ if (enc && !unique.includes(enc))
159
+ unique.push(enc);
160
+ }
161
+ let best = { text: '', score: -Infinity, encoding: 'utf-8' };
162
+ for (const enc of unique) {
163
+ try {
164
+ const decoder = new TextDecoder(enc, { fatal: false });
165
+ const text = decoder.decode(bytes);
166
+ let score = scoreText(text);
167
+ if (validUtf8 && enc === 'utf-8') {
168
+ score += 5000;
169
+ }
170
+ if (score > best.score ||
171
+ (score === best.score && tiebreakRank(enc) < tiebreakRank(best.encoding))) {
172
+ best = { text, score, encoding: enc };
173
+ }
174
+ }
175
+ catch {
176
+ // Skip unsupported encodings in current JS environment
177
+ }
178
+ }
179
+ return best;
180
+ }
181
+ // Decode each byte segment separately: an ECI assignment applies to subsequent segments.
182
+ const ECI_ENCODINGS = { 3: 'iso-8859-1', 20: 'shift_jis', 26: 'utf-8', 28: 'big5', 29: 'gb18030', 30: 'euc-kr' };
183
+ function decodeChunks(chunks, characterSet) {
184
+ let eci = null;
185
+ const encodings = [];
186
+ let text = '';
187
+ let guessed = null;
188
+ for (const chunk of chunks) {
189
+ if (chunk.type === 'eci') {
190
+ eci = ECI_ENCODINGS[chunk.assignmentNumber];
191
+ if (!eci)
192
+ throw new Error(`Unsupported ECI assignment ${chunk.assignmentNumber}`);
193
+ }
194
+ else if (chunk.type === 'byte') {
195
+ const bytes = new Uint8Array(chunk.bytes);
196
+ const declared = eci || characterSet;
197
+ if (declared) {
198
+ const encoding = eci === 'iso-8859-1' ? eci : normalizeEncoding(declared);
199
+ text += eci === 'iso-8859-1'
200
+ ? Array.from(bytes, byte => String.fromCharCode(byte)).join('')
201
+ : new TextDecoder(encoding, { fatal: true }).decode(bytes);
202
+ encodings.push(encoding);
203
+ }
204
+ else {
205
+ const result = decodeWithFallback(bytes);
206
+ text += result.text;
207
+ guessed = result.encoding;
208
+ encodings.push(result.encoding);
209
+ }
210
+ }
211
+ else {
212
+ text += chunk.text || '';
213
+ }
214
+ }
215
+ const unique = [...new Set(encodings)];
216
+ return { text, encoding: unique.length === 1 ? unique[0] : unique.length ? 'mixed' : 'utf-8', detectedEncoding: guessed };
217
+ }