@trustchex/react-native-sdk 1.464.0 → 1.475.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.
Files changed (64) hide show
  1. package/android/build.gradle +3 -3
  2. package/android/src/main/java/com/trustchex/reactnativesdk/camera/TrustchexCameraView.kt +190 -12
  3. package/ios/Camera/TrustchexCameraView.swift +244 -46
  4. package/ios/Permission/PermissionModule.m +22 -0
  5. package/ios/Permission/PermissionModule.swift +67 -0
  6. package/lib/module/Screens/Debug/MRZTestScreen.js +121 -147
  7. package/lib/module/Screens/Dynamic/LivenessDetectionScreen.js +24 -3
  8. package/lib/module/Screens/Dynamic/VerbalConsentScreen.js +1 -1
  9. package/lib/module/Screens/Dynamic/VideoCallScreen.js +7 -12
  10. package/lib/module/Screens/Static/ResultScreen.js +9 -1
  11. package/lib/module/Shared/Components/EIDScanner.js +166 -163
  12. package/lib/module/Shared/Components/FaceCamera.js +14 -8
  13. package/lib/module/Shared/Components/IdentityDocumentCamera.js +45 -10
  14. package/lib/module/Shared/Libs/MRZ_KNOWN_ISSUES.md +112 -0
  15. package/lib/module/Shared/Libs/PERMISSIONS_MANAGER.md +268 -0
  16. package/lib/module/Shared/Libs/index.js +20 -0
  17. package/lib/module/Shared/Libs/mrz.utils.js +570 -16
  18. package/lib/module/Shared/Libs/mrzFrameAggregator.js +301 -0
  19. package/lib/module/Shared/Libs/mrzOcrIntegration.js +109 -0
  20. package/lib/module/Shared/Libs/permissions.utils.js +199 -0
  21. package/lib/module/Translation/Resources/en.js +1 -0
  22. package/lib/module/Translation/Resources/tr.js +1 -0
  23. package/lib/module/version.js +1 -1
  24. package/lib/typescript/src/Screens/Debug/MRZTestScreen.d.ts.map +1 -1
  25. package/lib/typescript/src/Screens/Dynamic/LivenessDetectionScreen.d.ts.map +1 -1
  26. package/lib/typescript/src/Screens/Dynamic/VideoCallScreen.d.ts.map +1 -1
  27. package/lib/typescript/src/Screens/Static/ResultScreen.d.ts.map +1 -1
  28. package/lib/typescript/src/Shared/Components/EIDScanner.d.ts.map +1 -1
  29. package/lib/typescript/src/Shared/Components/FaceCamera.d.ts.map +1 -1
  30. package/lib/typescript/src/Shared/Components/IdentityDocumentCamera.d.ts.map +1 -1
  31. package/lib/typescript/src/Shared/Libs/index.d.ts +20 -0
  32. package/lib/typescript/src/Shared/Libs/index.d.ts.map +1 -0
  33. package/lib/typescript/src/Shared/Libs/mrz.utils.d.ts +8 -0
  34. package/lib/typescript/src/Shared/Libs/mrz.utils.d.ts.map +1 -1
  35. package/lib/typescript/src/Shared/Libs/mrzFrameAggregator.d.ts +76 -0
  36. package/lib/typescript/src/Shared/Libs/mrzFrameAggregator.d.ts.map +1 -0
  37. package/lib/typescript/src/Shared/Libs/mrzOcrIntegration.d.ts +73 -0
  38. package/lib/typescript/src/Shared/Libs/mrzOcrIntegration.d.ts.map +1 -0
  39. package/lib/typescript/src/Shared/Libs/permissions.utils.d.ts +58 -0
  40. package/lib/typescript/src/Shared/Libs/permissions.utils.d.ts.map +1 -0
  41. package/lib/typescript/src/Translation/Resources/en.d.ts +1 -0
  42. package/lib/typescript/src/Translation/Resources/en.d.ts.map +1 -1
  43. package/lib/typescript/src/Translation/Resources/tr.d.ts +1 -0
  44. package/lib/typescript/src/Translation/Resources/tr.d.ts.map +1 -1
  45. package/lib/typescript/src/version.d.ts +1 -1
  46. package/package.json +14 -10
  47. package/src/Screens/Debug/MRZTestScreen.tsx +137 -166
  48. package/src/Screens/Dynamic/LivenessDetectionScreen.tsx +45 -5
  49. package/src/Screens/Dynamic/VerbalConsentScreen.tsx +1 -1
  50. package/src/Screens/Dynamic/VideoCallScreen.tsx +8 -19
  51. package/src/Screens/Static/ResultScreen.tsx +18 -9
  52. package/src/Shared/Components/EIDScanner.tsx +210 -160
  53. package/src/Shared/Components/FaceCamera.tsx +19 -16
  54. package/src/Shared/Components/IdentityDocumentCamera.tsx +53 -13
  55. package/src/Shared/Libs/MRZ_KNOWN_ISSUES.md +112 -0
  56. package/src/Shared/Libs/PERMISSIONS_MANAGER.md +268 -0
  57. package/src/Shared/Libs/index.ts +63 -0
  58. package/src/Shared/Libs/mrz.utils.ts +639 -11
  59. package/src/Shared/Libs/mrzFrameAggregator.ts +370 -0
  60. package/src/Shared/Libs/mrzOcrIntegration.ts +175 -0
  61. package/src/Shared/Libs/permissions.utils.ts +251 -0
  62. package/src/Translation/Resources/en.ts +1 -0
  63. package/src/Translation/Resources/tr.ts +1 -0
  64. package/src/version.ts +1 -1
@@ -1,6 +1,18 @@
1
1
  "use strict";
2
2
 
3
3
  import { parse } from 'mrz';
4
+ // Inherent limitations & deliberate trade-offs (ICAO check-digit collisions,
5
+ // unprotected fields, conservative filler normalisation): see MRZ_KNOWN_ISSUES.md
6
+ // in this directory.
7
+
8
+ // Wall-clock budget for a single validateMRZ call's recovery search. Recovery on
9
+ // a garbage frame can otherwise exhaustively parse thousands of permutations and
10
+ // block the JS thread for ~1s, freezing the UI during continuous scanning. The
11
+ // search loops check this deadline and bail; a real misread is found in <5ms, so
12
+ // a modest budget never costs a genuine correction.
13
+ const RECOVERY_BUDGET_MS = 80;
14
+ let recoveryDeadline = 0;
15
+ const recoveryExpired = () => Date.now() > recoveryDeadline;
4
16
 
5
17
  /**
6
18
  * MRZ Format Types according to ICAO 9303
@@ -78,6 +90,28 @@ const fixMRZ = rawText => {
78
90
  // e.g., "<<K<<" → "<<<<<" (clearly a filler position)
79
91
  cleanedText = cleanedText.replace(/(<+)K(<+)/g, '$1<$2');
80
92
 
93
+ // Pattern 3b: "K" is the dominant OCR misread of the "<" filler glyph in OCR-B.
94
+ // Normalise "K" → "<" ONLY in the trailing filler region (the run after the
95
+ // last real data), which is unambiguously padding. A mid-line "K" is left
96
+ // intact: a single "<" also separates given names (e.g. "KAYA<KEMAL"), so a
97
+ // lone "K" beside fillers cannot be safely distinguished from a real name
98
+ // letter — a surname like "AKTAS" must keep its "K".
99
+ cleanedText = cleanedText.split('\n').map(line => {
100
+ if (!line.includes('<')) return line;
101
+ // Collapse a trailing run of fillers + K to "<" (e.g. "…TEST<KK"→"…TEST<<<").
102
+ let out = line.replace(/(?<=<)[<K]+$/g, m => '<'.repeat(m.length));
103
+ // Document-code filler: a TD1 line-1 starts with the doc code, a "<", a
104
+ // short issuing state, and then the DOCUMENT NUMBER (a long alphanumeric
105
+ // run). When the filler after the code is misread as "K" ("IKD<<SPEC1234…"
106
+ // for "I<D<<SPEC1234…"), fix it — but ONLY when that long doc-number run is
107
+ // present, so a short NAME line that merely starts with a doc-code letter
108
+ // (e.g. "AKTAS<<MEHMET" or "AK<<MERT") never matches and keeps its real "K".
109
+ if (/^[ACIPV]K[A-Z0-9<]{0,2}<[A-Z0-9]{6,}/.test(out)) {
110
+ out = out.replace(/^([ACIPV])K/, '$1<');
111
+ }
112
+ return out;
113
+ }).join('\n');
114
+
81
115
  // Pattern 4: Fix trailing filler area corruption at line end
82
116
  // e.g., "TUR<<<<<KK" → "TUR<<<<<<<" (only at end after clear filler sequence)
83
117
  cleanedText = cleanedText.replace(/(<{5,})[KGB]+$/gm, (match, fillers) => {
@@ -163,6 +197,115 @@ const fixMRZ = rawText => {
163
197
  const fixedMRZ = mrzLines.join('\n');
164
198
  return fixedMRZ;
165
199
  };
200
+
201
+ /**
202
+ * Reconstructs fixed-width MRZ line-sets from a noisy multi-block OCR frame
203
+ * where the band may be split across extra newlines, mixed with front-of-card
204
+ * text, broken by internal spaces, or missing its trailing fillers.
205
+ *
206
+ * Supports all ICAO 9303 machine-readable formats:
207
+ * - TD1: 3 lines × 30 (national ID cards)
208
+ * - TD2: 2 lines × 36
209
+ * - TD3: 2 lines × 44 (passports)
210
+ *
211
+ * It returns an array of CANDIDATE line-sets (most-likely first). Each
212
+ * candidate is just a structural guess — the caller MUST validate every
213
+ * candidate with the `mrz` parser + check-digit recovery and keep only one
214
+ * that passes its check digits. A wrong reconstruction therefore never leaks
215
+ * through; it simply fails validation and is discarded.
216
+ */
217
+ const reconstructMRZCandidates = rawText => {
218
+ if (!rawText) return [];
219
+ const upper = applyOCRBCorrections(rawText.toUpperCase());
220
+
221
+ // Per-OCR-line strip to MRZ-legal chars (drops spaces, punctuation, « …).
222
+ // The "<" filler glyph in OCR-B is frequently misread as a letter — most often
223
+ // "K", but under glare also "C", "E" and "G". Normalise those letters to "<"
224
+ // ONLY in an UNAMBIGUOUS filler context, never where the letter could be part
225
+ // of a real name. The safe contexts are runs (the trailing/internal filler
226
+ // region) or a single filler-letter flanked by 2+ real fillers — NOT a lone
227
+ // letter next to a single "<", because a single "<" also separates given names
228
+ // (e.g. "KAYA<KEMAL"), so the "K" of "KEMAL" must be left intact. The
229
+ // check-digit recovery downstream still vets the result.
230
+ // Only normalise filler-letters in the TRAILING filler region — the run of
231
+ // characters after the last real data, which is unambiguously "<" padding. A
232
+ // mid-line filler-letter cannot be distinguished from a real name letter
233
+ // (names follow the "<<" separator and may start with K/C/E/G, e.g.
234
+ // "KAYA<<KEMAL"), so we never touch those — leaving them avoids corrupting
235
+ // names, and the trailing region is where the K↔< glare misread actually shows.
236
+ const FILLER_LETTERS = 'KCEG';
237
+ const fillerClass = `[${FILLER_LETTERS}]`;
238
+ const normaliseFillers = l =>
239
+ // A tail of fillers and filler-letters (with at least one real "<" present)
240
+ // is the padding region — collapse the whole tail to "<".
241
+ l.replace(new RegExp(`(?<=<)(?:<|${fillerClass}){1,}$`), m => '<'.repeat(m.length));
242
+ const ocrLines = upper.split('\n').map(l => normaliseFillers(l.replace(/[^A-Z0-9<]/g, ''))).filter(l => l.length > 0);
243
+ const flat = ocrLines.join('');
244
+ const pad = (s, len) => s.length >= len ? s.slice(0, len) : s.padEnd(len, '<');
245
+
246
+ // Restore the filler right after the document code. In TD1/TD2/TD3 the second
247
+ // character of line 1 is always "<". OCR commonly reads it as "K" or drops it:
248
+ // "IKD…" -> "I<D…", "ITUR…" -> "I<TUR…", "I<D…" unchanged.
249
+ const fixDocStart = s => s.replace(/^([ACIPV])([A-Z0-9<])/, (_m, code, next) => next === '<' ? code + next : code + '<' + (next === 'K' ? '' : next));
250
+ const candidates = [];
251
+
252
+ // Helper: the OCR line that actually starts the MRZ (doc code + state pattern),
253
+ // so title/front-of-card text mixed into the blob can't create a false anchor.
254
+ const docLine = ocrLines.find(l => /^[ACIPV][A-Z0-9<]{3,}<</.test(l));
255
+
256
+ // ---- TD3 (passport): line1 "P<XXX…", line2 starts with a 9-char doc number ----
257
+ // Line 2 signature: docNumber(9) + check + nationality(3) + birth(6)+check+sex+expiry(6)+check…
258
+ {
259
+ const l1m = flat.match(/P[<A-Z]TUR[A-Z<]{2,}|P<[A-Z]{3}[A-Z<]+/);
260
+ const l2m = flat.match(/[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/);
261
+ if (l1m && l2m) {
262
+ candidates.push([pad(fixDocStart(l1m[0]), 44), pad(l2m[0], 44)]);
263
+ }
264
+ }
265
+
266
+ // ---- TD2: line1 "X<XXX…", line2 starts with docNumber ----
267
+ {
268
+ const l1m = flat.match(/[ACIPV]<[A-Z]{3}[A-Z<]+/);
269
+ const l2m = flat.match(/[A-Z0-9<]{9}[0-9<][A-Z]{3}[0-9]{6}[0-9<][MF<][0-9]{6}[0-9<]/);
270
+ if (l1m && l2m) {
271
+ candidates.push([pad(fixDocStart(l1m[0]), 36), pad(l2m[0], 36)]);
272
+ }
273
+ }
274
+
275
+ // ---- TD1 (national ID): 3 independent 30-char records ----
276
+ {
277
+ // Prefer the dedicated MRZ line (avoids title/front text in the blob); fall
278
+ // back to a blob match if OCR merged the line with adjacent content.
279
+ const l1Source = docLine ?? flat.match(/[ACIPV][A-Z0-9<]{4}[A-Z0-9<]{9}[0-9<][A-Z0-9<]*/)?.[0];
280
+ // Line 2: the OCR line (or blob slice) that looks like the date record:
281
+ // birth(6)+check+sex+expiry(6)+check+state(3). Allow letters in date spans
282
+ // for OCR slips; check-digit recovery resolves them.
283
+ const l2Line = ocrLines.find(l => /^[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z<]{2,}/.test(l));
284
+ const l2m = l2Line ?? flat.match(/[0-9A-Z]{6}[0-9<][MF<][0-9A-Z]{6}[0-9<][A-Z]{2,3}/)?.[0];
285
+ if (l1Source) {
286
+ let l1 = pad(fixDocStart(l1Source), 30);
287
+ // The issuing-state field (TD1 line 1, positions 2–5) is structurally
288
+ // fillers/letters only — never a personal name — so a "K" there flanked by
289
+ // a filler is an unambiguous "<" misread and safe to normalise. This is
290
+ // position-scoped so it can NEVER touch the name field (positions 5+).
291
+ l1 = l1.slice(0, 2) + l1.slice(2, 5).replace(/K(?=<)|(?<=<)K|(?<=[A-Z])K$/g, '<') + l1.slice(5);
292
+ let l2;
293
+ if (l2m) {
294
+ // Use the matched date record, padded to 30.
295
+ l2 = pad(l2m, 30);
296
+ } else {
297
+ const after = flat.indexOf(l1Source) + l1Source.length;
298
+ l2 = pad(flat.slice(after, after + 30), 30);
299
+ }
300
+ // Line 3 (name): the longest letter+filler OCR line that is NOT the doc or
301
+ // date line — exclude obvious front-of-card title words by requiring fillers.
302
+ const nameRuns = ocrLines.filter(l => l !== l1Source && l !== l2Line && /^[A-Z<]+$/.test(l) && /</.test(l) && l.length >= 5);
303
+ const l3 = pad(nameRuns.sort((a, b) => b.length - a.length)[0] ?? '', 30);
304
+ candidates.push([l1, l2, l3]);
305
+ }
306
+ }
307
+ return candidates;
308
+ };
166
309
  const AMBIGUOUS_CHAR_MAP = {
167
310
  '0': ['O', 'Q', 'D'],
168
311
  'O': ['0', 'Q', 'D'],
@@ -192,19 +335,28 @@ const AMBIGUOUS_CHAR_MAP = {
192
335
  */
193
336
  const OCRB_SPECIFIC_MAP = {
194
337
  // Glyph confusion in OCR-B (low contrast scanning)
195
- Ø: '0',
338
+ 'Ø': '0',
196
339
  // Slashed zero sometimes appears as capital O with slash
197
- ø: '0',
340
+ 'ø': '0',
198
341
  // Lowercase variant
199
- œ: 'O',
342
+ 'œ': 'O',
200
343
  // Ligature
201
344
 
345
+ // The "<" filler chevron is frequently OCR'd as a guillemet/angle-quote glyph,
346
+ // especially in the trailing filler run. Map these to "<" so they KEEP their
347
+ // position (rather than being stripped, which would shift the line).
348
+ '«': '<',
349
+ '»': '<',
350
+ '‹': '<',
351
+ '›': '<',
352
+ '《': '<',
353
+ '》': '<',
202
354
  // Common in monospace OCR
203
- Ι: 'I',
355
+ 'Ι': 'I',
204
356
  // Greek capital iota confused with I
205
- ι: 'i',
357
+ 'ι': 'i',
206
358
  // Greek lowercase iota
207
- l: 'I' // Lowercase L as I (common with serif OCR-B variants)
359
+ 'l': 'I' // Lowercase L as I (common with serif OCR-B variants)
208
360
  };
209
361
 
210
362
  /**
@@ -311,6 +463,341 @@ const generateAmbiguousVariants = (text, maxChanges = 2, maxVariants = 64) => {
311
463
  return entries.map(e => e.text);
312
464
  };
313
465
 
466
+ /**
467
+ * Maps a failing check-digit field (as reported by the `mrz` package) to the
468
+ * [line, start, endExclusive] span of the DATA it protects, per the ICAO 9303
469
+ * fixed layout for each format. Spans are 0-based, relative to fixed-width lines.
470
+ */
471
+ const CHECK_DIGIT_FIELD_DATA_SPANS = {
472
+ // TD1: line0 docNumber[5..14]; line1 birth[0..6], expiry[8..14]
473
+ TD1: {
474
+ documentNumberCheckDigit: [0, 5, 14],
475
+ birthDateCheckDigit: [1, 0, 6],
476
+ expirationDateCheckDigit: [1, 8, 14]
477
+ },
478
+ // TD2: line1 docNumber[0..9], birth[13..19], expiry[21..27]
479
+ TD2: {
480
+ documentNumberCheckDigit: [1, 0, 9],
481
+ birthDateCheckDigit: [1, 13, 19],
482
+ expirationDateCheckDigit: [1, 21, 27]
483
+ },
484
+ // TD3 (passport): line1 docNumber[0..9], birth[13..19], expiry[21..27]
485
+ TD3: {
486
+ documentNumberCheckDigit: [1, 0, 9],
487
+ birthDateCheckDigit: [1, 13, 19],
488
+ expirationDateCheckDigit: [1, 21, 27]
489
+ }
490
+ };
491
+
492
+ /**
493
+ * Exhaustively tries every ambiguous-character permutation (0↔O, 5↔S, A↔4, …)
494
+ * WITHIN the data spans of the check-digit fields that are currently failing,
495
+ * re-parsing after each candidate, until the FULL MRZ validates (all check
496
+ * digits, including the composite).
497
+ *
498
+ * Because the search is scoped to the small failing fields, it is genuinely
499
+ * exhaustive — every permutation is tried — without the combinatorial blow-up of
500
+ * permuting the entire MRZ. This is what allows a misread document number
501
+ * (e.g. O→0, A→4, S→5) to be corrected before any downstream screen.
502
+ *
503
+ * @returns the parse result if a fully-valid MRZ is found, otherwise null.
504
+ */
505
+ /** ICAO 9303 7-3-1 weighted check digit. */
506
+ const icaoCheckDigit = str => {
507
+ const weights = [7, 3, 1];
508
+ let sum = 0;
509
+ for (let i = 0; i < str.length; i++) {
510
+ const c = str[i];
511
+ const v = c === '<' ? 0 : c >= '0' && c <= '9' ? c.charCodeAt(0) - 48 : c.charCodeAt(0) - 55;
512
+ sum = (sum + weights[i % 3] * v) % 10;
513
+ }
514
+ return String(sum);
515
+ };
516
+
517
+ /**
518
+ * When a TD1 MRZ fails ONLY on its composite check digit (every per-field check
519
+ * digit is valid), the composite is deterministically derivable from the other
520
+ * fields — OCR often just drops the trailing digit. Recompute and set it.
521
+ * Returns the corrected parse result, or null if not applicable.
522
+ */
523
+ const fixTD1Composite = lines => {
524
+ if (lines.length < 3 || lines[0].length !== 30 || lines[1].length !== 30) {
525
+ return null;
526
+ }
527
+ const r = parse(lines);
528
+ const bad = (r.details ?? []).filter(d => !d.valid);
529
+ if (bad.length !== 1 || bad[0].field !== 'compositeCheckDigit') return null;
530
+
531
+ // TD1 composite covers: line1[5..30) + line2[0..7) + line2[8..15) + line2[18..29)
532
+ const l1 = lines[0];
533
+ const l2 = lines[1];
534
+ const composite = l1.slice(5, 30) + l2.slice(0, 7) + l2.slice(8, 15) + l2.slice(18, 29);
535
+ const fixedL2 = l2.slice(0, 29) + icaoCheckDigit(composite);
536
+ const fixed = parse([l1, fixedL2, lines[2]]);
537
+ return fixed.valid ? fixed : null;
538
+ };
539
+
540
+ /**
541
+ * Recovers a TD1 MRZ when OCR INSERTED or DROPPED a character inside a numeric
542
+ * field — a real failure mode on glossy cards (e.g. expiry "360118"+check"7"
543
+ * read as "36011187", which shifts the nationality and overflows the line).
544
+ *
545
+ * Pure character substitution can't fix a length/alignment error, so this tries
546
+ * single-character edits in the relevant region and re-validates by check digit:
547
+ * - line 2 (date record): delete each char in the birth..expiry-check window
548
+ * [0..15) (then right-pad to 30) — undoes a spurious inserted digit;
549
+ * - line 1 (doc record): delete each char in the doc-number..check window
550
+ * [5..15) — undoes an inserted char in the serial.
551
+ * Each candidate is re-padded to 30, the composite is recomputed, and only a
552
+ * fully check-digit-valid parse is accepted, so a wrong edit can never pass.
553
+ */
554
+ const recoverTD1ByIndel = lines => {
555
+ if (lines.length < 3) return null;
556
+ const pad30 = s => s.length >= 30 ? s.slice(0, 30) : s.padEnd(30, '<');
557
+
558
+ // Which line/window to try edits in, based on which check digit is failing.
559
+ let base;
560
+ try {
561
+ base = parse(lines.map(pad30));
562
+ } catch {
563
+ return null;
564
+ }
565
+ if (base.format !== 'TD1') return null;
566
+ const failing = new Set((base.details ?? []).filter(d => !d.valid).map(d => d.field));
567
+
568
+ // (lineIndex, editStart, editEndExclusive) regions to attempt deletions in,
569
+ // chosen by the failing check digit. Order: date line first (most common).
570
+ const regions = [];
571
+ if (failing.has('expirationDateCheckDigit') || failing.has('birthDateCheckDigit') || failing.has('compositeCheckDigit')) {
572
+ regions.push([1, 0, 15]); // birth..expiry-check on the date record
573
+ }
574
+ if (failing.has('documentNumberCheckDigit') || failing.has('compositeCheckDigit')) {
575
+ regions.push([0, 5, 15]); // doc-number..its check on the doc record
576
+ }
577
+ if (regions.length === 0) return null;
578
+
579
+ // Build all single-deletion candidates up front.
580
+ const candidates = [];
581
+ for (const [li, from, to] of regions) {
582
+ const original = pad30(lines[li] ?? '');
583
+ for (let i = from; i < to && i < original.length; i++) {
584
+ const edited = pad30(original.slice(0, i) + original.slice(i + 1));
585
+ const candidate = lines.map(pad30);
586
+ candidate[li] = edited;
587
+ candidates.push(candidate);
588
+ }
589
+ }
590
+
591
+ // Cheap pass first: a plain parse or a composite recompute resolves the common
592
+ // case (a dropped/duplicated digit) in microseconds — try ALL deletions this
593
+ // way before paying for any substitution search.
594
+ for (const candidate of candidates) {
595
+ let r;
596
+ try {
597
+ r = parse(candidate);
598
+ } catch {
599
+ continue;
600
+ }
601
+ if (r.valid) return r;
602
+ const composite = fixTD1Composite(candidate);
603
+ if (composite?.valid) return composite;
604
+ }
605
+
606
+ // Expensive pass only if the cheap pass found nothing: a deletion may align the
607
+ // structure but leave a residual ambiguous char (e.g. B→8 in the TC number).
608
+ for (const candidate of candidates) {
609
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
610
+ const subbed = recoverByFailingFields(candidate, false);
611
+ if (subbed?.valid) return subbed;
612
+ }
613
+ return null;
614
+ };
615
+ const recoverByFailingFields = (lines, tryIndel = true) => {
616
+ // `parse` THROWS (not returns invalid) on a wrong line count; a caller passing a
617
+ // noisy/fragmented line set must get null, not an exception that aborts the flow.
618
+ let first;
619
+ try {
620
+ first = parse(lines);
621
+ } catch {
622
+ return null;
623
+ }
624
+ if (first.valid) return first;
625
+
626
+ // If only the composite check digit is off (common when OCR drops the trailing
627
+ // digit), recompute it deterministically before the search.
628
+ const compositeFixed = fixTD1Composite(lines);
629
+ if (compositeFixed) return compositeFixed;
630
+ const spans = CHECK_DIGIT_FIELD_DATA_SPANS[first.format ?? ''];
631
+ if (!spans) return null;
632
+ const isDigit = c => c >= '0' && c <= '9';
633
+
634
+ // A "change cost" for replacing `orig` with `repl` at a position that, per the
635
+ // MRZ field layout, is expected to hold a digit (`expectDigit`). Lower = more
636
+ // likely. The dominant real-world OCR error is letter↔digit confusion in
637
+ // numeric fields (O→0, S→5, A→4, B→8, I→1), so:
638
+ // - turning a misread letter into the expected digit is cheap (0)
639
+ // - keeping/introducing a non-digit where a digit is expected is expensive
640
+ const changeCost = (orig, repl, expectDigit) => {
641
+ if (repl === orig) return 0; // no change always cheapest
642
+ const origDigit = isDigit(orig);
643
+ const replDigit = isDigit(repl);
644
+ // OCR overwhelmingly confuses a LETTER for a digit in numeric MRZ fields
645
+ // (O→0, S→5, A→4, B→8, I→1), rarely the reverse. So:
646
+ // - letter → digit : very cheap (the common real correction) => 1
647
+ // - letter → letter : plausible only in alpha positions => 3
648
+ // - digit → letter : OCR almost never turns a real digit into a letter => 8
649
+ // - digit → digit : possible but unusual => 4
650
+ if (!origDigit && replDigit) return expectDigit ? 1 : 2;
651
+ if (!origDigit && !replDigit) return expectDigit ? 6 : 3;
652
+ if (origDigit && !replDigit) return 8;
653
+ return 4; // digit -> digit
654
+ };
655
+
656
+ // Per-format map of which data positions are expected to be digits. Document
657
+ // numbers can be alphanumeric, but Turkish-style IDs use letter-then-digits,
658
+ // and dates/personal numbers are always digits. We treat a position as
659
+ // "expectDigit" when its current best guess across candidates is numeric;
660
+ // dates are always numeric.
661
+ const expectsDigitAt = (field, indexWithinField) => {
662
+ if (field === 'birthDateCheckDigit' || field === 'expirationDateCheckDigit') {
663
+ return true; // dates are all digits
664
+ }
665
+ if (field === 'documentNumberCheckDigit') {
666
+ // Common ID layout: position 0 is a letter, the rest digits.
667
+ return indexWithinField > 0;
668
+ }
669
+ return false;
670
+ };
671
+ const positions = [];
672
+ for (const d of first.details ?? []) {
673
+ if (d.valid || !spans[d.field]) continue;
674
+ const [ln, start, end] = spans[d.field];
675
+ const line = lines[ln];
676
+ if (line == null) continue;
677
+ for (let i = start; i < end; i++) {
678
+ const orig = line[i];
679
+ const alts = AMBIGUOUS_CHAR_MAP[orig];
680
+ if (alts && alts.length) {
681
+ const expectDigit = expectsDigitAt(d.field, i - start);
682
+ const options = [orig, ...alts].map(ch => ({
683
+ ch,
684
+ cost: changeCost(orig, ch, expectDigit)
685
+ })).sort((a, b) => a.cost - b.cost);
686
+ positions.push({
687
+ line: ln,
688
+ index: i,
689
+ options
690
+ });
691
+ }
692
+ }
693
+ }
694
+ if (positions.length === 0) return null;
695
+ const total = positions.reduce((acc, p) => acc * p.options.length, 1);
696
+ // The legitimate search space for a genuine OCR misread is small — a handful of
697
+ // ambiguous characters in the failing check-digit fields. A huge `total` means
698
+ // the frame is garbage (many ambiguous chars, no real MRZ); exhaustively
699
+ // parsing tens of thousands of permutations there would block the JS thread for
700
+ // ~1s per frame and freeze the UI. Cap hard so a noisy frame fails fast.
701
+ const MAX_PERMUTATIONS = 4096;
702
+ if (total > MAX_PERMUTATIONS) return null;
703
+
704
+ // Decode candidate index `n` into a per-position option choice, and compute its
705
+ // total change cost (sum of per-option costs). We then try candidates in
706
+ // ascending total cost so the most plausible OCR correction is accepted first.
707
+ const decode = n => {
708
+ let k = n;
709
+ let cost = 0;
710
+ const indices = positions.map(p => {
711
+ const idx = k % p.options.length;
712
+ k = Math.floor(k / p.options.length);
713
+ cost += p.options[idx].cost;
714
+ return idx;
715
+ });
716
+ return {
717
+ indices,
718
+ cost
719
+ };
720
+ };
721
+ const order = Array.from({
722
+ length: total
723
+ }, (_, n) => n);
724
+ const costCache = new Map();
725
+ const costOf = n => {
726
+ let c = costCache.get(n);
727
+ if (c === undefined) {
728
+ c = decode(n).cost;
729
+ costCache.set(n, c);
730
+ }
731
+ return c;
732
+ };
733
+ order.sort((a, b) => costOf(a) - costOf(b) || a - b);
734
+ for (const n of order) {
735
+ if (recoveryExpired()) return null; // bail before blocking the JS thread
736
+ const {
737
+ indices
738
+ } = decode(n);
739
+ const chars = {};
740
+ for (const p of positions) {
741
+ if (!chars[p.line]) chars[p.line] = lines[p.line].split('');
742
+ }
743
+ positions.forEach((p, pi) => {
744
+ chars[p.line][p.index] = p.options[indices[pi]].ch;
745
+ });
746
+ const candidate = lines.slice();
747
+ for (const lnStr of Object.keys(chars)) {
748
+ candidate[Number(lnStr)] = chars[Number(lnStr)].join('');
749
+ }
750
+ const r = parse(candidate);
751
+ if (r.valid) return r;
752
+ }
753
+
754
+ // Substitution alone couldn't fix it. If OCR inserted/dropped a character
755
+ // (a length/alignment error), try single-char edits and re-validate.
756
+ if (tryIndel) {
757
+ const indel = recoverTD1ByIndel(lines);
758
+ if (indel?.valid) return indel;
759
+ }
760
+ return null;
761
+ };
762
+
763
+ /**
764
+ * Rebuild the corrected fixed-width MRZ lines from a (valid) parse result.
765
+ * Every field's `ranges` carry the actual post-correction characters at known
766
+ * line/column spans, so laying each `raw` span into a per-line buffer yields the
767
+ * exact MRZ that satisfied the check digits — the genuinely fixed version to show
768
+ * the user, not the lightweight `fixMRZ` pre-clean.
769
+ */
770
+ const correctedMrzFromParse = result => {
771
+ const widths = {
772
+ TD1: 30,
773
+ TD2: 36,
774
+ TD3: 44
775
+ };
776
+ const width = widths[result.format ?? ''];
777
+ if (!width) return undefined;
778
+ const lineCount = result.format === 'TD1' ? 3 : 2;
779
+ const buffers = Array.from({
780
+ length: lineCount
781
+ }, () => new Array(width).fill('<'));
782
+ for (const detail of result.details ?? []) {
783
+ for (const range of detail.ranges ?? []) {
784
+ // `raw` (the actual characters at this span) exists at runtime but isn't in
785
+ // the `mrz` Range type.
786
+ const {
787
+ line,
788
+ start,
789
+ raw = ''
790
+ } = range;
791
+ const buf = buffers[line];
792
+ if (!buf) continue;
793
+ for (let i = 0; i < raw.length && start + i < width; i++) {
794
+ buf[start + i] = raw[i];
795
+ }
796
+ }
797
+ }
798
+ return buffers.map(b => b.join('')).join('\n');
799
+ };
800
+
314
801
  /**
315
802
  * Validates MRZ text using the mrz npm package
316
803
  * @param mrzText Raw or cleaned MRZ text
@@ -319,20 +806,85 @@ const generateAmbiguousVariants = (text, maxChanges = 2, maxVariants = 64) => {
319
806
  */
320
807
  const validateMRZ = (mrzText, autocorrect = true) => {
321
808
  try {
809
+ // Arm the recovery wall-clock budget for this call so the search below can't
810
+ // block the JS thread on a garbage frame.
811
+ recoveryDeadline = Date.now() + RECOVERY_BUDGET_MS;
322
812
  const fixedText = fixMRZ(mrzText);
323
- let result = parse(fixedText, {
324
- autocorrect
325
- });
813
+ // `parse` THROWS on a wrong MRZ-line count (e.g. a noisy frame with a title
814
+ // line + fragments). That must NOT short-circuit the recovery/reconstruction
815
+ // path below — treat a throw here as "no valid parse yet" and keep going.
816
+ let result = null;
817
+ try {
818
+ result = parse(fixedText, {
819
+ autocorrect
820
+ });
821
+ } catch {
822
+ result = null;
823
+ }
824
+
825
+ // Primary recovery: exhaustive, CHECK-DIGIT-DRIVEN correction scoped to the
826
+ // fields whose check digit actually fails. It tries every OCR-ambiguous
827
+ // permutation within those fields — ordered by how likely the OCR error is
828
+ // (letter→digit in numeric fields is cheapest) — and only accepts a candidate
829
+ // when the WHOLE MRZ validates (document-number, date and composite check
830
+ // digits all pass). This both (a) fixes a misread document number before the
831
+ // caller advances to the NFC/next screen, and (b) prefers the genuinely
832
+ // correct correction over an arbitrary check-digit-satisfying one.
833
+ if (!result || !result.valid) {
834
+ const fixedLines = fixedText.split('\n').filter(l => l.trim());
835
+ if (fixedLines.length >= 2) {
836
+ const recovered = recoverByFailingFields(fixedLines);
837
+ if (recovered && recovered.valid) {
838
+ result = recovered;
839
+ }
840
+ }
841
+ }
842
+
843
+ // Last-resort fallback: the older whole-string ambiguous sweep, only for
844
+ // inputs the field-scoped recovery can't address (e.g. an unrecognised
845
+ // format with no check-digit span map). Still requires a fully-valid parse.
326
846
  if (!result || !result.valid) {
327
847
  const variants = generateAmbiguousVariants(fixedText);
328
848
  for (const variant of variants) {
849
+ if (recoveryExpired()) break; // bail before blocking the JS thread
329
850
  if (variant === fixedText) continue;
330
- const candidate = parse(variant, {
331
- autocorrect
332
- });
333
- if (candidate && candidate.valid) {
334
- result = candidate;
335
- break;
851
+ try {
852
+ const candidate = parse(variant, {
853
+ autocorrect
854
+ });
855
+ if (candidate && candidate.valid) {
856
+ result = candidate;
857
+ break;
858
+ }
859
+ } catch {
860
+ // Malformed variant — try the next.
861
+ }
862
+ }
863
+ }
864
+
865
+ // Last resort: the standard line-splitter couldn't assemble a parseable MRZ
866
+ // (e.g. a noisy frame where OCR split the band, mixed in front-of-card text,
867
+ // or broke a field with spaces). Reconstruct fixed-width line-sets for every
868
+ // supported format (TD1/TD2/TD3) and validate each WITH CHECK DIGITS, keeping
869
+ // only one that passes — a wrong reconstruction can never leak through.
870
+ if (!result || !result.valid) {
871
+ for (const reLines of reconstructMRZCandidates(mrzText)) {
872
+ // A reconstructed candidate for the wrong format (e.g. a 2-line TD2 guess
873
+ // built from a TD1 frame) makes the `mrz` parser THROW on line count —
874
+ // that must not abort the loop before a good candidate is tried.
875
+ try {
876
+ const direct = parse(reLines);
877
+ if (direct && direct.valid) {
878
+ result = direct;
879
+ break;
880
+ }
881
+ const recovered = recoverByFailingFields(reLines);
882
+ if (recovered && recovered.valid) {
883
+ result = recovered;
884
+ break;
885
+ }
886
+ } catch {
887
+ // Skip this malformed candidate and try the next.
336
888
  }
337
889
  }
338
890
  }
@@ -371,7 +923,8 @@ const validateMRZ = (mrzText, autocorrect = true) => {
371
923
  return {
372
924
  valid: true,
373
925
  format,
374
- fields
926
+ fields,
927
+ correctedMrz: correctedMrzFromParse(result)
375
928
  };
376
929
  } catch (error) {
377
930
  return {
@@ -472,6 +1025,7 @@ export default {
472
1025
  fixMRZ,
473
1026
  validateMRZ,
474
1027
  validateMRZWithCorrections,
1028
+ reconstructMRZCandidates,
475
1029
  calculateMRZQualityScore,
476
1030
  assessMRZQuality,
477
1031
  isValidOCRBPattern,