veryfi-lens-wasm 3.5.4 → 3.5.6

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.
package/README.md CHANGED
@@ -115,6 +115,11 @@ VeryfiLens.onFailure((error) => { /* error occurred */ });
115
115
  | `enableFullScreen` | `boolean` | `false` | Enable fullscreen mode |
116
116
  | `debug_mode` | `boolean` | `false` | Enable console logging |
117
117
  | `useDevApi` | `boolean` | `false` | Route API requests to `lens-dev.veryfi.com` instead of production |
118
+ | `originalImageMaxSizeInMB` | `number` | — | Maximum size in MB for produced images (valid range `0.2`–`2.5`). Quality, then dimensions, are reduced until the JPEG fits. Unset or `0` means no size limit. Does not apply to recorded video |
119
+ | `autoTagSource` | `boolean` | `false` | Tag the submitted document with its source (`LFB`) |
120
+ | `autoTagDeviceId` | `boolean` | `false` | Tag the submitted document with the device ID (UUID) |
121
+ | `autoTagLensVersion` | `boolean` | `false` | Tag the submitted document with the Lens version |
122
+ | `autoTagPlatform` | `boolean` | `false` | Tag the submitted document with the platform (`Web`, or `Web-<browser>` when the browser is known) |
118
123
 
119
124
  ### UI Controls
120
125
 
@@ -139,6 +144,7 @@ VeryfiLens.onFailure((error) => { /* error occurred */ });
139
144
  | `isBlurModal` | `boolean` | `true` | Show modal when blur detected |
140
145
  | `isDocumentModal` | `boolean` | `true` | Show modal when no document detected |
141
146
  | `isLcdModal` | `boolean` | `true` | Show modal when LCD/screen capture detected |
147
+ | `isDesktopModeModal` | `boolean` | `true` | Show the modal asking mobile users to leave "Desktop site" mode |
142
148
  | `enforceDocumentDetection` | `boolean` | `false` | Block submission if no document detected |
143
149
  | `enforceBlurDetection` | `boolean` | `false` | Block submission if image is blurry |
144
150
  | `enforceLcdDetection` | `boolean` | `false` | Block submission if screen capture detected |
@@ -229,6 +235,9 @@ When `multiSubmission` is set or `maxDocuments` is not `1`, `init()` asks the ba
229
235
  | `anydocMaxPages` | `number\|null` | `null` | _Deprecated:_ alias for `maxPagesPerDocument` |
230
236
  | `anydocAddPageText` | `string` | `"Add Page"` | _Deprecated:_ alias for `reviewAddPageText` |
231
237
  | `anydocSubmitText` | `string` | `"Submit"` | _Deprecated:_ alias for `reviewSubmitText` |
238
+ | `anydocShowFlipMessage` | `boolean` | `false` | After the first page of a two-page capture, show "flip the document" and go straight to capturing the second side (skips the gallery until both pages exist). Only runs when `maxPagesPerDocument` is `2`; if this is on and no page cap is set, the cap is set to `2` |
239
+ | `anydocFlipMessageText` | `string` | `"Please flip the document and capture the other side"` | Flip-prompt message |
240
+ | `anydocFlipContinueText` | `string` | `"Continue"` | Flip-prompt continue button |
232
241
  | `anydocShowGuide` | `boolean` | `false` | Show a dismissible on-screen text guide explaining how to capture. Auto-hides after each page capture and reappears when the camera restarts for the next page |
233
242
  | `anydocGuideText` | `string` | `"Position the document within the frame..."` | Guide text shown for anydocs capture. Separate steps with a blank line (`\n\n`) — each becomes a numbered step |
234
243
  | `anydocGuideTitle` | `string` | `"Steps to Capture"` | Heading of the anydocs capture guide panel |
@@ -0,0 +1,22 @@
1
+ import { createModal } from './modalBase.js';
2
+
3
+ export const createAnydocFlipModal = (container, croppedImage, onContinue, options = {}) => {
4
+ const defaults = {
5
+ message: 'Please flip the document and capture the other side',
6
+ continueText: 'Continue',
7
+ };
8
+ const o = { ...defaults, ...options };
9
+
10
+ return createModal(container, {
11
+ id: 'veryfi-anydoc-flip-modal',
12
+ cssPrefix: 'anydoc-flip-modal',
13
+ message: o.message,
14
+ primaryButtonText: o.continueText,
15
+ primaryButtonId: 'veryfi-anydoc-flip-continue',
16
+ onPrimaryClick: onContinue,
17
+ croppedImage,
18
+ useBackdrop: true,
19
+ primaryClearsCanvas: false,
20
+ showCropBorder: false,
21
+ });
22
+ };
@@ -1,4 +1,5 @@
1
1
  import { createOverlayBase, createCenteredElement, createLoadingSpinner } from './overlayBase.js';
2
+ import { canvasToJpegBase64 } from '../core/image-encode.js';
2
3
 
3
4
  export const createBottleCapOverlay = (container, options = {}) => {
4
5
  const circleRadius = options.circleRadius !== undefined ? options.circleRadius : 0.7;
@@ -62,7 +63,7 @@ export const createBottleCapOverlay = (container, options = {}) => {
62
63
  if (typeof cropImgRef.setSquareDisplay === 'function') {
63
64
  cropImgRef.setSquareDisplay();
64
65
  }
65
- return cropImgRef.toDataURL('image/jpeg', 0.97).split(',')[1];
66
+ return canvasToJpegBase64(cropImgRef);
66
67
  },
67
68
  });
68
69
 
@@ -1,4 +1,5 @@
1
1
  import { createOverlayBase } from './overlayBase.js';
2
+ import { canvasToJpegBase64 } from '../core/image-encode.js';
2
3
 
3
4
  export const createCheckOverlay = (container, options = {}) => {
4
5
  const cropLayoutAspectRatio = options.cropLayoutAspectRatio !== undefined ? options.cropLayoutAspectRatio : 0.0;
@@ -236,7 +237,7 @@ export const createCheckOverlay = (container, options = {}) => {
236
237
  0, 0, finalCropWidth, finalCropHeight
237
238
  );
238
239
 
239
- return cropImgRef.toDataURL('image/jpeg', 0.97).split(',')[1];
240
+ return canvasToJpegBase64(cropImgRef);
240
241
  },
241
242
  });
242
243
 
@@ -1,4 +1,5 @@
1
1
  import { createOverlayBase, createCenteredElement, createLoadingSpinner } from './overlayBase.js';
2
+ import { canvasToJpegBase64 } from '../core/image-encode.js';
2
3
 
3
4
  export const createCodeStripsOverlay = (container, options = {}) => {
4
5
  const rectWidth = options.rectWidth !== undefined ? options.rectWidth : 0.8;
@@ -72,7 +73,7 @@ export const createCodeStripsOverlay = (container, options = {}) => {
72
73
  if (typeof cropImgRef.setRectangleDisplay === 'function') {
73
74
  cropImgRef.setRectangleDisplay();
74
75
  }
75
- return cropImgRef.toDataURL('image/jpeg', 0.97).split(',')[1];
76
+ return canvasToJpegBase64(cropImgRef);
76
77
  },
77
78
  });
78
79
 
@@ -46,6 +46,7 @@ export const createModal = (container, {
46
46
  useBackdrop = false,
47
47
  primaryClearsCanvas = true,
48
48
  secondaryHidesBorder = true,
49
+ showCropBorder = true,
49
50
  messageElementId,
50
51
  styles,
51
52
  }) => {
@@ -234,7 +235,11 @@ export const createModal = (container, {
234
235
  messageElement.innerHTML = context.message.replace(/</g, '&lt;').replace(/>/g, '&gt;');
235
236
  }
236
237
  modal.style.display = 'flex';
237
- showBorder();
238
+ if (showCropBorder) {
239
+ showBorder();
240
+ } else {
241
+ hideBorder();
242
+ }
238
243
  },
239
244
  hide: () => {
240
245
  modal.style.display = 'none';
@@ -9,6 +9,7 @@ import {
9
9
  hideFieldDetectionOverlay,
10
10
  } from './fieldDetectionOverlay.js';
11
11
  import { getPreviewLayoutRect } from './previewLayout.js';
12
+ import { canvasToJpegBase64 } from '../core/image-encode.js';
12
13
 
13
14
  const MOBILE_BREAKPOINT = 768;
14
15
  const DESKTOP_GALLERY_MAX_WIDTH = 500;
@@ -481,7 +482,7 @@ export const createReviewGallery = (container, callbacks = {}, options = {}) =>
481
482
  ctx.translate(canvas.width / 2, canvas.height / 2);
482
483
  ctx.rotate(Math.PI / 2);
483
484
  ctx.drawImage(image, -image.naturalWidth / 2, -image.naturalHeight / 2);
484
- resolve(canvas.toDataURL('image/jpeg', o.imageQuality).split(',')[1]);
485
+ resolve(canvasToJpegBase64(canvas, o.imageQuality));
485
486
  };
486
487
  image.onerror = reject;
487
488
  image.src = `data:image/jpeg;base64,${base64}`;
@@ -703,7 +704,7 @@ export const createReviewGallery = (container, callbacks = {}, options = {}) =>
703
704
  canvas.height = sh;
704
705
  const ctx = canvas.getContext('2d');
705
706
  ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
706
- const data = canvas.toDataURL('image/jpeg', o.imageQuality).split(',')[1];
707
+ const data = canvasToJpegBase64(canvas, o.imageQuality);
707
708
  cleanup();
708
709
  onDone(data);
709
710
  });
@@ -53,6 +53,8 @@ export const createSpinner = (container, message) => {
53
53
  spinnerOverlay.appendChild(messageElement);
54
54
  container.appendChild(spinnerOverlay);
55
55
 
56
+ let removed = false;
57
+
56
58
  return {
57
59
  show: () => {
58
60
  spinnerOverlay.style.display = 'flex';
@@ -61,7 +63,9 @@ export const createSpinner = (container, message) => {
61
63
  spinnerOverlay.style.display = 'none';
62
64
  },
63
65
  remove: () => {
64
- container.removeChild(spinnerOverlay);
66
+ if (removed) return;
67
+ removed = true;
68
+ spinnerOverlay.remove();
65
69
  releaseSpinKeyframes();
66
70
  },
67
71
  updateMessage: (newMessage) => {
package/core/api.js CHANGED
@@ -70,6 +70,21 @@ export const getMetaData = () => {
70
70
  };
71
71
  };
72
72
 
73
+ // Auto tags appended to the /api/document payload when the partner opts in.
74
+ // Each flag contributes one tag; the values mirror what the metadata already
75
+ // reports (source, device UUID, SDK version, platform + browser).
76
+ export const buildAutoTags = () => {
77
+ const tags = [];
78
+ if (state.autoTagSource) tags.push('LFB');
79
+ if (state.autoTagDeviceId && state.uuidv4) tags.push(state.uuidv4);
80
+ if (state.autoTagLensVersion) tags.push(state.sdkVersion);
81
+ if (state.autoTagPlatform) {
82
+ const browserName = parseUA()?.browser?.name;
83
+ tags.push(browserName ? `Web-${browserName}` : 'Web');
84
+ }
85
+ return tags;
86
+ };
87
+
73
88
  export const buildJsonData = async () => {
74
89
  const browserData = await getBrowserData();
75
90
  const UAData = flattenObject(parseUA());
@@ -302,6 +317,12 @@ export const handleSubmit = async (image, { fieldDetection } = {}) => {
302
317
  const lastJsonData = state.packageScans?.[state.packageScans.length - 1]?.jsonData;
303
318
  const documentFieldsToDetect = state.documentFieldsToDetect?.slice() ?? [];
304
319
  const successHandler = state.successHandler;
320
+ // Auto tags are merged with any tags the partner set through customData so
321
+ // neither source is lost; duplicates are collapsed.
322
+ const tags = [...new Set([
323
+ ...buildAutoTags(),
324
+ ...(Array.isArray(customData?.tags) ? customData.tags : []),
325
+ ])];
305
326
  const resolvedFieldDetection = fieldDetection ?? state.fieldDetectionResult;
306
327
  const localFieldDetection = resolvedFieldDetection
307
328
  ? structuredClone(resolvedFieldDetection)
@@ -342,6 +363,7 @@ export const handleSubmit = async (image, { fieldDetection } = {}) => {
342
363
  : { image: image }),
343
364
  ...((lensFlavor === 'anydocs' || lensFlavor === 'prescription_label') && selectedBlueprint ? { blueprint_name: selectedBlueprint } : {}),
344
365
  ...customData,
366
+ ...(tags.length ? { tags } : {}),
345
367
  };
346
368
 
347
369
  const qrSessionId = getQrSessionId();
@@ -448,11 +470,16 @@ export const finishBatch = async () => {
448
470
  };
449
471
 
450
472
  export const fetchBlueprints = async () => {
473
+ const clientId = state.clientId;
474
+ const sessionId = state.clientData?.session;
475
+ const qrSessionId = getQrSessionId();
451
476
  const requestOptions = {
452
477
  method: 'POST',
453
478
  headers: {
454
479
  'Content-Type': 'application/json',
455
- 'CLIENT-ID': state.clientId,
480
+ 'CLIENT-ID': clientId,
481
+ ...(sessionId ? { 'SESSION-ID': sessionId } : {}),
482
+ ...(qrSessionId ? { 'QR-SESSION-ID': qrSessionId } : {}),
456
483
  },
457
484
  body: JSON.stringify({
458
485
  client_name: state.clientData.client_name
@@ -4,7 +4,7 @@ import { checkIfDocumentOnCapture, checkIfBlurOnCapture, checkIfLcdOnCapture } f
4
4
  import { hideVideoOverlay } from '../overlay-controls.js';
5
5
  import { stopLens, startStitching, stopStitching } from '../lifecycle.js';
6
6
  import { generateDeviceIDifNeeded } from '../device.js';
7
- import { DEFAULTS } from '../constants.js';
7
+ import { canvasToJpegBase64 } from '../image-encode.js';
8
8
  import * as store from '../capture-store.js';
9
9
 
10
10
  export const captureUploaded = async (imageFile) => {
@@ -28,7 +28,7 @@ export const captureUploaded = async (imageFile) => {
28
28
  const croppedImageData = new ImageData(data, outputWidth, outputHeight);
29
29
  croppedCtx.putImageData(croppedImageData, 0, 0);
30
30
 
31
- const croppedBase64 = croppedCanvas.toDataURL('image/jpeg', DEFAULTS.IMAGE_QUALITY).split(',')[1];
31
+ const croppedBase64 = canvasToJpegBase64(croppedCanvas);
32
32
  resolve(croppedBase64);
33
33
  state.resultSetter?.(croppedBase64);
34
34
  } else {
@@ -38,7 +38,7 @@ export const captureUploaded = async (imageFile) => {
38
38
  canvas.height = img.height;
39
39
  const ctx = canvas.getContext('2d');
40
40
  ctx.drawImage(img, 0, 0);
41
- const originalBase64 = canvas.toDataURL('image/jpeg', DEFAULTS.IMAGE_QUALITY).split(',')[1];
41
+ const originalBase64 = canvasToJpegBase64(canvas);
42
42
  resolve(originalBase64);
43
43
  state.resultSetter?.(originalBase64);
44
44
  }
@@ -1,7 +1,7 @@
1
1
  import { state } from '../state.js';
2
2
  import { hideVideoOverlay, showVideoOverlay } from '../overlay-controls.js';
3
3
  import { newStartLens } from '../lifecycle.js';
4
- import { DEFAULTS } from '../constants.js';
4
+ import { canvasToJpegBase64 } from '../image-encode.js';
5
5
  import { CAPTURE_BUTTON_BACKGROUND } from '../../components/captureButton.js';
6
6
 
7
7
  let previewRecorder = null;
@@ -436,7 +436,7 @@ const capturePrescriptionImage = async () => {
436
436
  0, 0, cropImgRef.width, cropImgRef.height
437
437
  );
438
438
 
439
- state.finalImage = cropImgRef.toDataURL('image/jpeg', DEFAULTS.IMAGE_QUALITY).split(',')[1];
439
+ state.finalImage = canvasToJpegBase64(cropImgRef);
440
440
  if (!state.finalImage) {
441
441
  throw new Error('Failed to capture prescription label image');
442
442
  }
package/core/constants.js CHANGED
@@ -39,13 +39,15 @@ export const setApiBaseUrl = (base) => {
39
39
  };
40
40
 
41
41
  export const DEFAULTS = {
42
- SDK_VERSION: '3.5.4',
42
+ SDK_VERSION: '3.5.6',
43
43
  BLUR_THRESHOLD: 0.7,
44
44
  LCD_THRESHOLD: 0.5,
45
45
  BOX_COLOR: 'rgba(84, 192, 139, 0.6)',
46
46
  CHECK_ASPECT_RATIO: 2.61,
47
47
  CROP_LAYOUT_BORDER_COLOR: '#54C08B',
48
48
  IMAGE_QUALITY: 0.97,
49
+ ORIGINAL_IMAGE_MAX_SIZE_MB: 2.5,
50
+ ORIGINAL_IMAGE_MIN_SIZE_MB: 0.2,
49
51
  SUBMIT_BUTTON_COLOR: '#00AA00',
50
52
  SUBMIT_BUTTON_TEXT_COLOR: '#FFFFFF',
51
53
  FINGERPRINT_TIMEOUT: 20000,
@@ -0,0 +1,58 @@
1
+ import { state } from './state.js';
2
+ import { DEFAULTS } from './constants.js';
3
+
4
+ // Quality ladder walked down when the encoded image exceeds the configured cap.
5
+ const QUALITY_STEPS = [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3];
6
+ // Once the lowest quality still overshoots, shrink the pixel dimensions.
7
+ const SCALE_STEP = 0.8;
8
+ const MAX_SCALE_ATTEMPTS = 6;
9
+
10
+ const base64Bytes = (base64) => Math.floor((base64.length * 3) / 4);
11
+
12
+ const encode = (canvas, quality) =>
13
+ canvas.toDataURL('image/jpeg', quality).split(',')[1];
14
+
15
+ const scaleCanvas = (source, scale) => {
16
+ const width = Math.max(1, Math.round(source.width * scale));
17
+ const height = Math.max(1, Math.round(source.height * scale));
18
+ const scaled = document.createElement('canvas');
19
+ scaled.width = width;
20
+ scaled.height = height;
21
+ scaled.getContext('2d').drawImage(source, 0, 0, width, height);
22
+ return scaled;
23
+ };
24
+
25
+ /**
26
+ * Encode a canvas as a base64 JPEG (no data URL prefix). When
27
+ * originalImageMaxSizeInMB is configured the result is kept within that budget:
28
+ * quality is reduced first, then the image is scaled down if the lowest quality
29
+ * still overshoots. Unset (the default) means the image is left uncompressed.
30
+ * Applies to still images only — recorded video is never re-encoded.
31
+ */
32
+ export const canvasToJpegBase64 = (canvas, quality = DEFAULTS.IMAGE_QUALITY) => {
33
+ let base64 = encode(canvas, quality);
34
+
35
+ const maxSizeInMB = state.originalImageMaxSizeInMB;
36
+ if (!maxSizeInMB) return base64;
37
+
38
+ const maxBytes = maxSizeInMB * 1024 * 1024;
39
+ if (base64Bytes(base64) <= maxBytes) return base64;
40
+
41
+ for (const step of QUALITY_STEPS) {
42
+ if (step >= quality) continue;
43
+ base64 = encode(canvas, step);
44
+ if (base64Bytes(base64) <= maxBytes) return base64;
45
+ }
46
+
47
+ let working = canvas;
48
+ for (let attempt = 0; attempt < MAX_SCALE_ATTEMPTS; attempt += 1) {
49
+ working = scaleCanvas(working, SCALE_STEP);
50
+ base64 = encode(working, QUALITY_STEPS[QUALITY_STEPS.length - 1]);
51
+ if (base64Bytes(base64) <= maxBytes) return base64;
52
+ }
53
+
54
+ state.debug_mode && console.log(
55
+ `[ImageEncode] Could not fit image under ${maxSizeInMB}MB; returning smallest produced (${(base64Bytes(base64) / (1024 * 1024)).toFixed(2)}MB)`
56
+ );
57
+ return base64;
58
+ };
package/core/lifecycle.js CHANGED
@@ -22,7 +22,9 @@ import { clearTheme } from './theme.js';
22
22
 
23
23
  export const newStartLens = async () => {
24
24
  state.started = true;
25
- installDesktopModeWatchdog();
25
+ if (state.isDesktopModeModal) {
26
+ installDesktopModeWatchdog();
27
+ }
26
28
  if (!state.lensFlavor) {
27
29
  throw new Error("Lens flavor is required");
28
30
  }
@@ -96,9 +96,24 @@ const applyChecksSubmitGate = () => {
96
96
  }
97
97
  };
98
98
 
99
+ // Two-page anydocs (insurance cards, etc.): Submit stays disabled until the
100
+ // second side exists, same as checks with enforceBothSides.
101
+ const isAnydocTwoPageFlip = () =>
102
+ state.lensFlavor === 'anydocs'
103
+ && !!state.anydocShowFlipMessage
104
+ && state.maxPagesPerDocument === 2;
105
+
106
+ const applyAnydocFlipSubmitGate = () => {
107
+ if (!isAnydocTwoPageFlip()) return;
108
+ if ((store.getActiveDoc()?.pages?.length || 0) < 2) {
109
+ state.reviewGalleryRef?.setSubmitting(true);
110
+ }
111
+ };
112
+
99
113
  const refreshGallery = () => {
100
114
  state.reviewGalleryRef?.render(galleryPayload());
101
115
  applyChecksSubmitGate();
116
+ applyAnydocFlipSubmitGate();
102
117
  };
103
118
 
104
119
  // enforceAndSkipBothSides: once the front is accepted, skip the gallery and go
@@ -113,6 +128,30 @@ const shouldAutoAdvanceCheckBack = () => {
113
128
  return (doc?.pages?.length || 0) === 1;
114
129
  };
115
130
 
131
+ // Anydocs with anydocShowFlipMessage and a 2-page cap: after the first page,
132
+ // skip the gallery and prompt to flip, then reopen the camera for page 2.
133
+ const shouldAutoAdvanceAnydocBack = () => {
134
+ if (!isAnydocTwoPageFlip()) return false;
135
+ if (state.recaptureTarget) return false;
136
+ const doc = store.getActiveDoc();
137
+ return (doc?.pages?.length || 0) === 1;
138
+ };
139
+
140
+ const promptAnydocFlip = () => {
141
+ state.updateHandler?.({ status: 'anydoc_flip_prompted' });
142
+ if (state.anydocFlipModal) {
143
+ state.anydocFlipModal.show();
144
+ return;
145
+ }
146
+ goToCamera();
147
+ };
148
+
149
+ export const continueAnydocFlip = async () => {
150
+ state.anydocFlipModal?.hide();
151
+ state.updateHandler?.({ status: 'anydoc_flip_continued' });
152
+ await goToCamera();
153
+ };
154
+
116
155
  const closeReview = () => {
117
156
  if (typeof state.onClose === 'function') state.onClose(false);
118
157
  if (state.onCloseRedirectUrl) window.location.href = state.onCloseRedirectUrl;
@@ -135,6 +174,31 @@ const buildChecksExtra = (doc) => {
135
174
  };
136
175
  };
137
176
 
177
+ // Legacy /api/document takes a single `image` base64 field. One page stays a
178
+ // JPEG; multiple pages (or a video Blob) must be a zip, or only the last page
179
+ // would be processed. Filenames match the pre-gallery anydocs/checks submit.
180
+ const zipScansForLegacySubmit = async (scans, { flavor, lastPage }) => {
181
+ const { default: JSZip } = await import('jszip');
182
+ const zip = new JSZip();
183
+ scans.forEach((scan, index) => {
184
+ const isBlob = scan.data instanceof Blob;
185
+ let fileName;
186
+ if (isBlob) {
187
+ const type = scan.data.type || lastPage?.data?.type || '';
188
+ const ext = type.includes('mp4') ? 'mp4'
189
+ : type.includes('quicktime') ? 'mov'
190
+ : 'webm';
191
+ fileName = lastPage?.fileName || scan.fileName || `prescription_label.${ext}`;
192
+ } else if (flavor === 'checks') {
193
+ fileName = index === 0 ? 'front.jpg' : index === 1 ? 'back.jpg' : `page_${index + 1}.jpg`;
194
+ } else {
195
+ fileName = `page_${index + 1}.jpg`;
196
+ }
197
+ zip.file(fileName, scan.data, isBlob ? {} : { base64: true });
198
+ });
199
+ return zip.generateAsync({ type: 'base64' });
200
+ };
201
+
138
202
  const submitOneDocument = async (docIndex) => {
139
203
  const doc = state.capturedDocs[docIndex];
140
204
  const scans = store.buildPackageScans(docIndex);
@@ -147,17 +211,18 @@ const submitOneDocument = async (docIndex) => {
147
211
 
148
212
  // Legacy (packageMode:false) posts an inline image to /api/document. A video
149
213
  // Blob can't be JSON-serialized, so zip+base64 it (parity with the pre-store
150
- // prescription_label submitVideoBlob path). packageMode:true ignores `image`
151
- // (it sends package_path), so no conversion is needed there.
214
+ // prescription_label submitVideoBlob path). Multiple stills must also be
215
+ // zipped — otherwise only the last page is OCR'd. packageMode:true ignores
216
+ // `image` (it sends package_path), so no conversion is needed there.
152
217
  let image = originalData;
153
- if (!state.packageMode && lastPage.kind === 'video' && image instanceof Blob) {
154
- const ext = image.type.includes('mp4') ? 'mp4'
155
- : image.type.includes('quicktime') ? 'mov'
156
- : 'webm';
157
- const { default: JSZip } = await import('jszip');
158
- const zip = new JSZip();
159
- zip.file(lastPage.fileName || `prescription_label.${ext}`, image);
160
- image = await zip.generateAsync({ type: 'base64' });
218
+ const needsLegacyZip = !state.packageMode && (
219
+ scans.length > 1 || (lastPage.kind === 'video' && image instanceof Blob)
220
+ );
221
+ if (needsLegacyZip) {
222
+ image = await zipScansForLegacySubmit(scans, {
223
+ flavor: state.lensFlavor,
224
+ lastPage,
225
+ });
161
226
  }
162
227
 
163
228
  // Rebuild the per-document package buffer from the store so deletes/retakes
@@ -184,7 +249,7 @@ const submitOneDocument = async (docIndex) => {
184
249
  // handleChecksBackAccepted path).
185
250
  const isChecks = state.lensFlavor === 'checks';
186
251
  const checksExtra = isChecks ? buildChecksExtra(doc) : null;
187
- const setterImage = isChecks ? (doc.pages[0]?.data ?? null) : originalData;
252
+ const setterImage = isChecks ? (doc.pages[0]?.data ?? null) : image;
188
253
 
189
254
  if (isPartnerDriven()) {
190
255
  const packageInfo = await ensurePackageUploaded();
@@ -296,6 +361,7 @@ const openGallery = () => {
296
361
  const gallery = ensureReviewGallery(galleryCallbacks(), galleryOptions());
297
362
  gallery?.show(galleryPayload());
298
363
  applyChecksSubmitGate();
364
+ applyAnydocFlipSubmitGate();
299
365
  };
300
366
 
301
367
  export const handleCameraExit = () => {
@@ -346,6 +412,12 @@ export const commitCaptureToReview = async ({ kind = 'image', data, isBase64 = k
346
412
  return page;
347
413
  }
348
414
 
415
+ if (shouldAutoAdvanceAnydocBack()) {
416
+ state.recaptureTarget = null;
417
+ promptAnydocFlip();
418
+ return page;
419
+ }
420
+
349
421
  openGallery();
350
422
 
351
423
  // Field detection (documentFieldsToDetect) runs on this page's own image: the
package/core/state.js CHANGED
@@ -89,6 +89,7 @@ export const state = {
89
89
  isBlurModal: true,
90
90
  isDocumentModal: true,
91
91
  isLcdModal: true,
92
+ isDesktopModeModal: true,
92
93
  container: null,
93
94
  exitButton: false,
94
95
  showCameraPermissionDeniedMessage: true,
@@ -109,6 +110,15 @@ export const state = {
109
110
  enforceLcdDetection: false,
110
111
  usingOverlayContainer: false,
111
112
 
113
+ // Produced image size cap (MB), valid range 0.2 - 2.5. null = no cap.
114
+ originalImageMaxSizeInMB: null,
115
+
116
+ // Auto tags added to the submitted document
117
+ autoTagSource: false,
118
+ autoTagDeviceId: false,
119
+ autoTagLensVersion: false,
120
+ autoTagPlatform: false,
121
+
112
122
  // Detection thresholds
113
123
  blurThreshold: DEFAULTS.BLUR_THRESHOLD,
114
124
  lcdThreshold: DEFAULTS.LCD_THRESHOLD,
@@ -198,6 +208,7 @@ export const state = {
198
208
  blurModal: null,
199
209
  documentModal: null,
200
210
  lcdModal: null,
211
+ anydocFlipModal: null,
201
212
  torchButtonRef: null,
202
213
  mirrorButtonRef: null,
203
214
  switchCameraButtonRef: null,
@@ -363,6 +374,7 @@ export const resetState = () => {
363
374
  state.blurModal = null;
364
375
  state.documentModal = null;
365
376
  state.lcdModal = null;
377
+ state.anydocFlipModal = null;
366
378
  state.frameRef = null;
367
379
  state.cropImgRef = null;
368
380
  state.videoRef = null;
@@ -12,6 +12,7 @@ import { createVideoOverlay } from '../components/videoOverlay.js';
12
12
  import { createStitchingButton } from '../components/stitchingButton.js';
13
13
  import { createCreditCardComponent } from '../components/creditCard.js';
14
14
  import { createWrongSideModal } from '../components/wrongSideModal.js';
15
+ import { createAnydocFlipModal } from '../components/anydocFlipModal.js';
15
16
  import { createWatermark } from '../components/watermark.js';
16
17
  import { createCardDataButton } from '../components/cardDataButton.js';
17
18
  import { createBottleCapOverlay } from '../components/bottleCapOverlay.js';
@@ -294,6 +295,21 @@ export const renderModalsIfNeeded = () => {
294
295
  );
295
296
  state.debug_mode && console.log("Wrong side modal created:", !!state.wrongSideModal);
296
297
  }
298
+
299
+ if (state.anydocShowFlipMessage && state.lensFlavor === 'anydocs') {
300
+ state.anydocFlipModal = createAnydocFlipModal(
301
+ state.container,
302
+ state.croppedImage,
303
+ async () => {
304
+ const { continueAnydocFlip } = await import('./review-flow.js');
305
+ await continueAnydocFlip();
306
+ },
307
+ {
308
+ message: state.anydocFlipMessageText,
309
+ continueText: state.anydocFlipContinueText,
310
+ }
311
+ );
312
+ }
297
313
  };
298
314
 
299
315
  export const renderBottleCapOverlayIfNeeded = () => {
@@ -2,6 +2,7 @@ import { state, refs, actions } from './state.js';
2
2
  import { drawContours, expandCoordinatesWithMargin } from './drawing.js';
3
3
  import { releaseCanvas, setCoordinates, setHasCoordinates, setBlurStatus, isBlurryVariance } from './utils.js';
4
4
  import { DEFAULTS, WASM } from './constants.js';
5
+ import { canvasToJpegBase64 } from './image-encode.js';
5
6
  import { bootstrapTesseract } from './tesseract-ocr.js';
6
7
  import { shouldRunFieldDetection } from './field-detection-policy.js';
7
8
 
@@ -367,14 +368,14 @@ export const getLongImage = async () => {
367
368
  const ctx = cropImgCanvas.getContext("2d");
368
369
  const imageData = new ImageData(data, width, height);
369
370
  ctx.putImageData(imageData, 0, 0);
370
- const imgString = cropImgCanvas.toDataURL("image/jpeg", DEFAULTS.IMAGE_QUALITY);
371
+ const imgString = canvasToJpegBase64(cropImgCanvas);
371
372
  state.image = cropImgCanvas;
372
373
  state.isDocument = true;
373
374
 
374
375
  stopWasm();
375
376
  releaseCanvas(state.boxRef);
376
377
  state.coordinates = [];
377
- return imgString.split("data:image/jpeg;base64,")[1];
378
+ return imgString;
378
379
  };
379
380
 
380
381
  // Rotate an RGBA crop by the orientation classifier's prediction so the crop
@@ -427,7 +428,7 @@ const renderCropToBase64 = (cropOut) => {
427
428
  canvas.width = outputWidth;
428
429
  canvas.height = outputHeight;
429
430
  canvas.getContext("2d").putImageData(new ImageData(data, outputWidth, outputHeight), 0, 0);
430
- return canvas.toDataURL("image/jpeg", DEFAULTS.IMAGE_QUALITY).split("data:image/jpeg;base64,")[1];
431
+ return canvasToJpegBase64(canvas);
431
432
  };
432
433
 
433
434
  /**
@@ -566,11 +567,11 @@ export const cropWasm = async (calculateBlur = true) => {
566
567
  }
567
568
  stopWasm();
568
569
 
569
- const imgString = cropImgCanvas.toDataURL("image/jpeg", DEFAULTS.IMAGE_QUALITY);
570
+ const imgString = canvasToJpegBase64(cropImgCanvas);
570
571
  state.image = cropImgCanvas;
571
572
  releaseCanvas(state.boxRef);
572
573
  state.coordinates = [];
573
- return imgString.split("data:image/jpeg;base64,")[1];
574
+ return imgString;
574
575
  };
575
576
 
576
577
  export const cropFromAutoCapture = (calculateBlur = true) => {
@@ -591,9 +592,9 @@ export const cropFromAutoCapture = (calculateBlur = true) => {
591
592
  state.blurStatus = false;
592
593
  }
593
594
 
594
- const imgString = cropImgCanvas.toDataURL("image/jpeg", DEFAULTS.IMAGE_QUALITY);
595
+ const imgString = canvasToJpegBase64(cropImgCanvas);
595
596
  state.image = cropImgCanvas;
596
597
  releaseCanvas(state.boxRef);
597
598
  state.coordinates = [];
598
- return imgString.split("data:image/jpeg;base64,")[1];
599
+ return imgString;
599
600
  };
@@ -16,6 +16,11 @@ export const setup = async (state, refs, actions) => {
16
16
  // unless anydocMaxPages/maxPagesPerDocument caps it), single document unless
17
17
  // the partner enables multi-document capture via multiSubmission/maxDocuments.
18
18
  if (state.maxDocuments == null) state.maxDocuments = state.multiSubmission ? null : 1;
19
+ // Flip-then-capture-the-back is a two-page flow. When the partner turns it
20
+ // on without setting a page cap, lock the document at 2 pages.
21
+ if (state.anydocShowFlipMessage && state.maxPagesPerDocument == null) {
22
+ state.maxPagesPerDocument = 2;
23
+ }
19
24
  // Carry the anydoc-specific page controls labels onto the review gallery so
20
25
  // partners that customized anydocAddPageText/anydocSubmitText keep them.
21
26
  state.reviewAddPageText = state.anydocAddPageText;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "veryfi-lens-wasm",
3
- "version": "3.5.4",
3
+ "version": "3.5.6",
4
4
  "description": "Lens For Web SDK with WASM",
5
5
  "main": "veryfi-lens.js",
6
6
  "type": "module",
package/veryfi-lens.js CHANGED
@@ -37,6 +37,28 @@ const normalizeCaptureConfig = (config) => {
37
37
  }
38
38
  };
39
39
 
40
+ // Cap on the size of produced images (still images only, never recorded video).
41
+ // Unset means no cap; anything outside the supported range is rejected.
42
+ const normalizeOriginalImageMaxSizeConfig = (config) => {
43
+ if (config.originalImageMaxSizeInMB === undefined) return;
44
+ const value = config.originalImageMaxSizeInMB;
45
+ // null / 0 both mean "no cap" so a UI slider can express the disabled state.
46
+ if (value === null || value === 0) {
47
+ state.originalImageMaxSizeInMB = null;
48
+ return;
49
+ }
50
+ if (typeof value === 'number' &&
51
+ value >= DEFAULTS.ORIGINAL_IMAGE_MIN_SIZE_MB &&
52
+ value <= DEFAULTS.ORIGINAL_IMAGE_MAX_SIZE_MB) {
53
+ state.originalImageMaxSizeInMB = value;
54
+ return;
55
+ }
56
+ console.warn(
57
+ `originalImageMaxSizeInMB must be a number between ${DEFAULTS.ORIGINAL_IMAGE_MIN_SIZE_MB} and ${DEFAULTS.ORIGINAL_IMAGE_MAX_SIZE_MB}. Ignoring invalid value.`
58
+ );
59
+ state.originalImageMaxSizeInMB = null;
60
+ };
61
+
40
62
  const normalizeThemeConfig = (config) => {
41
63
  if (config.theme === undefined) return;
42
64
  if (isValidTheme(config.theme)) {
@@ -80,6 +102,7 @@ const VeryfiLens = {
80
102
  state.multiSessionActive = isMultiSession;
81
103
 
82
104
  normalizeCaptureConfig(config);
105
+ normalizeOriginalImageMaxSizeConfig(config);
83
106
  normalizeThemeConfig(config);
84
107
 
85
108
  if (config.lensFlavor !== "caps" && config.lensFlavor !== "code_strips" && config.lensFlavor !== "prescription_label") {
@@ -205,6 +228,10 @@ const VeryfiLens = {
205
228
 
206
229
  await flavorModule.render(state, refs, actions);
207
230
 
231
+ // Flavor render can tear the session down (e.g. anydocs blueprint
232
+ // cancel → removeOverlay()/resetState()). Don't keep initializing.
233
+ if (!state.hasInit) return;
234
+
208
235
  if (!state.started && state.lensFlavor !== 'caps' && state.lensFlavor !== 'code_strips' && state.lensFlavor !== 'prescription_label') {
209
236
  state.debug_mode && console.log("Starting lens");
210
237
  await newStartLens();
@@ -267,6 +294,7 @@ const VeryfiLens = {
267
294
  });
268
295
 
269
296
  normalizeCaptureConfig(config);
297
+ normalizeOriginalImageMaxSizeConfig(config);
270
298
  normalizeThemeConfig(config);
271
299
  if (state.container) {
272
300
  applyTheme(state.container, state.theme);