@idmission/websdk-core 0.2.0-rc.2 → 0.5.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 (209) hide show
  1. package/README.md +27 -1
  2. package/dist/attestation/clientAttestation.d.ts +5 -0
  3. package/dist/attestation/clientAttestation.d.ts.map +1 -1
  4. package/dist/attestation/clientAttestation.js +4 -4
  5. package/dist/attestation/collectClientAttestation.d.ts +3 -1
  6. package/dist/attestation/collectClientAttestation.d.ts.map +1 -1
  7. package/dist/attestation/collectClientAttestation.js +4 -3
  8. package/dist/camera/acquireCamera.d.ts +5 -0
  9. package/dist/camera/acquireCamera.d.ts.map +1 -1
  10. package/dist/camera/acquireCamera.js +25 -5
  11. package/dist/captureProgress/actor.d.ts +30 -0
  12. package/dist/captureProgress/actor.d.ts.map +1 -0
  13. package/dist/captureProgress/actor.js +754 -0
  14. package/dist/captureProgress/encoder.d.ts +7 -0
  15. package/dist/captureProgress/encoder.d.ts.map +1 -0
  16. package/dist/captureProgress/encoder.js +195 -0
  17. package/dist/captureProgress/index.d.ts +4 -0
  18. package/dist/captureProgress/index.d.ts.map +1 -0
  19. package/dist/captureProgress/index.js +45 -0
  20. package/dist/captureProgress/internal.d.ts +3 -0
  21. package/dist/captureProgress/internal.d.ts.map +1 -0
  22. package/dist/captureProgress/internal.js +1 -0
  23. package/dist/captureProgress/protocol.d.ts +224 -0
  24. package/dist/captureProgress/protocol.d.ts.map +1 -0
  25. package/dist/captureProgress/protocol.js +106 -0
  26. package/dist/captureProgress/recorder.d.ts +32 -0
  27. package/dist/captureProgress/recorder.d.ts.map +1 -0
  28. package/dist/captureProgress/recorder.js +554 -0
  29. package/dist/captureProgress/transport.d.ts +33 -0
  30. package/dist/captureProgress/transport.d.ts.map +1 -0
  31. package/dist/captureProgress/transport.js +109 -0
  32. package/dist/captureProgress/types.d.ts +35 -0
  33. package/dist/captureProgress/types.d.ts.map +1 -0
  34. package/dist/captureProgress/types.js +27 -0
  35. package/dist/client/IdmissionClient.d.ts +8 -1
  36. package/dist/client/IdmissionClient.d.ts.map +1 -1
  37. package/dist/client/IdmissionClient.js +96 -27
  38. package/dist/client/approval.d.ts +15 -0
  39. package/dist/client/approval.d.ts.map +1 -0
  40. package/dist/client/approval.js +19 -0
  41. package/dist/client/artifacts.d.ts +2 -0
  42. package/dist/client/artifacts.d.ts.map +1 -1
  43. package/dist/client/documentFileMetadata.d.ts +13 -0
  44. package/dist/client/documentFileMetadata.d.ts.map +1 -0
  45. package/dist/client/documentFileMetadata.js +51 -0
  46. package/dist/client/index.d.ts +3 -0
  47. package/dist/client/index.d.ts.map +1 -1
  48. package/dist/client/index.js +2 -0
  49. package/dist/client/payload.d.ts +3 -0
  50. package/dist/client/payload.d.ts.map +1 -1
  51. package/dist/client/payload.js +3 -1
  52. package/dist/client/submissionMetadata.d.ts +4 -1
  53. package/dist/client/submissionMetadata.d.ts.map +1 -1
  54. package/dist/client/submissionMetadata.js +13 -8
  55. package/dist/client/types.d.ts +8 -0
  56. package/dist/client/types.d.ts.map +1 -1
  57. package/dist/client/validateSession.d.ts +2 -0
  58. package/dist/client/validateSession.d.ts.map +1 -1
  59. package/dist/client/validateSession.js +53 -24
  60. package/dist/documentCapture/autoCaptureEngine.d.ts +106 -0
  61. package/dist/documentCapture/autoCaptureEngine.d.ts.map +1 -0
  62. package/dist/documentCapture/autoCaptureEngine.js +475 -0
  63. package/dist/documentCapture/autoCaptureGeometry.d.ts +514 -0
  64. package/dist/documentCapture/autoCaptureGeometry.d.ts.map +1 -0
  65. package/dist/documentCapture/autoCaptureGeometry.js +475 -0
  66. package/dist/documentCapture/autoCaptureGuidance.d.ts +61 -0
  67. package/dist/documentCapture/autoCaptureGuidance.d.ts.map +1 -0
  68. package/dist/documentCapture/autoCaptureGuidance.js +73 -0
  69. package/dist/documentCapture/autoCaptureMetadata.d.ts +193 -0
  70. package/dist/documentCapture/autoCaptureMetadata.d.ts.map +1 -0
  71. package/dist/documentCapture/autoCaptureMetadata.js +200 -0
  72. package/dist/documentCapture/autoCaptureOptions.d.ts +211 -0
  73. package/dist/documentCapture/autoCaptureOptions.d.ts.map +1 -0
  74. package/dist/documentCapture/autoCaptureOptions.js +177 -0
  75. package/dist/documentCapture/autoCaptureShutter.d.ts +162 -0
  76. package/dist/documentCapture/autoCaptureShutter.d.ts.map +1 -0
  77. package/dist/documentCapture/autoCaptureShutter.js +183 -0
  78. package/dist/documentCapture/controller.d.ts +38 -1
  79. package/dist/documentCapture/controller.d.ts.map +1 -1
  80. package/dist/documentCapture/controller.js +620 -40
  81. package/dist/documentCapture/index.d.ts +8 -2
  82. package/dist/documentCapture/index.d.ts.map +1 -1
  83. package/dist/documentCapture/index.js +6 -0
  84. package/dist/documentCapture/reducer.d.ts +26 -1
  85. package/dist/documentCapture/reducer.d.ts.map +1 -1
  86. package/dist/documentCapture/reducer.js +43 -0
  87. package/dist/documentCapture/state.d.ts +118 -0
  88. package/dist/documentCapture/state.d.ts.map +1 -1
  89. package/dist/documentCapture/state.js +24 -0
  90. package/dist/idCapture/controller.d.ts +24 -1
  91. package/dist/idCapture/controller.d.ts.map +1 -1
  92. package/dist/idCapture/controller.js +111 -13
  93. package/dist/idCapture/index.d.ts +1 -1
  94. package/dist/idCapture/index.d.ts.map +1 -1
  95. package/dist/idCapture/index.js +12 -1
  96. package/dist/idCapture/pipeline.d.ts +30 -0
  97. package/dist/idCapture/pipeline.d.ts.map +1 -1
  98. package/dist/idCapture/pipeline.js +33 -10
  99. package/dist/idCapture/state.d.ts +1 -3
  100. package/dist/idCapture/state.d.ts.map +1 -1
  101. package/dist/idCapture/submit.d.ts.map +1 -1
  102. package/dist/idCapture/submit.js +35 -1
  103. package/dist/idCapture/types.d.ts +2 -0
  104. package/dist/idCapture/types.d.ts.map +1 -1
  105. package/dist/index.d.ts +2 -0
  106. package/dist/index.d.ts.map +1 -1
  107. package/dist/index.js +1 -0
  108. package/dist/liveness/challengeGeometry.d.ts +48 -17
  109. package/dist/liveness/challengeGeometry.d.ts.map +1 -1
  110. package/dist/liveness/challengeGeometry.js +101 -54
  111. package/dist/models/DocumentDetection.d.ts +29 -1
  112. package/dist/models/DocumentDetection.d.ts.map +1 -1
  113. package/dist/models/DocumentDetection.js +75 -7
  114. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts +2 -2
  115. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts.map +1 -1
  116. package/dist/models/defaults/DocumentDetectorLiteRT.js +27 -2
  117. package/dist/models/defaults/HandLandmarkLiteRT.d.ts +3 -0
  118. package/dist/models/defaults/HandLandmarkLiteRT.d.ts.map +1 -0
  119. package/dist/models/defaults/HandLandmarkLiteRT.js +5 -0
  120. package/dist/models/defaults/IrisLandmarkLiteRT.d.ts +3 -0
  121. package/dist/models/defaults/IrisLandmarkLiteRT.d.ts.map +1 -0
  122. package/dist/models/defaults/IrisLandmarkLiteRT.js +5 -0
  123. package/dist/models/defaults/PalmDetectionLiteRT.d.ts +3 -0
  124. package/dist/models/defaults/PalmDetectionLiteRT.d.ts.map +1 -0
  125. package/dist/models/defaults/PalmDetectionLiteRT.js +5 -0
  126. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts +3 -0
  127. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts.map +1 -0
  128. package/dist/models/defaults/PoaDocumentDetectorLiteRT.js +19 -0
  129. package/dist/models/defaults/index.d.ts +13 -1
  130. package/dist/models/defaults/index.d.ts.map +1 -1
  131. package/dist/models/defaults/index.js +16 -0
  132. package/dist/models/preloadModels.d.ts +24 -16
  133. package/dist/models/preloadModels.d.ts.map +1 -1
  134. package/dist/models/preloadModels.js +33 -3
  135. package/dist/models/providers/litert/FaceLandmarker.d.ts +8 -1
  136. package/dist/models/providers/litert/FaceLandmarker.d.ts.map +1 -1
  137. package/dist/models/providers/litert/FaceLandmarker.js +95 -3
  138. package/dist/models/providers/litert/HandOverFaceDetector.d.ts +27 -0
  139. package/dist/models/providers/litert/HandOverFaceDetector.d.ts.map +1 -0
  140. package/dist/models/providers/litert/HandOverFaceDetector.js +162 -0
  141. package/dist/models/providers/litert/blazeFacePrePost.js +4 -2
  142. package/dist/models/providers/litert/docDetectPrePost.d.ts.map +1 -1
  143. package/dist/models/providers/litert/docDetectPrePost.js +20 -3
  144. package/dist/models/providers/litert/handLandmarkPrePost.d.ts +20 -0
  145. package/dist/models/providers/litert/handLandmarkPrePost.d.ts.map +1 -0
  146. package/dist/models/providers/litert/handLandmarkPrePost.js +72 -0
  147. package/dist/models/providers/litert/handOverFace.d.ts +44 -0
  148. package/dist/models/providers/litert/handOverFace.d.ts.map +1 -0
  149. package/dist/models/providers/litert/handOverFace.js +139 -0
  150. package/dist/models/providers/litert/irisPrePost.d.ts +38 -0
  151. package/dist/models/providers/litert/irisPrePost.d.ts.map +1 -0
  152. package/dist/models/providers/litert/irisPrePost.js +101 -0
  153. package/dist/models/providers/litert/palmPrePost.d.ts +55 -0
  154. package/dist/models/providers/litert/palmPrePost.d.ts.map +1 -0
  155. package/dist/models/providers/litert/palmPrePost.js +151 -0
  156. package/dist/sdkVersions.d.ts +18 -0
  157. package/dist/sdkVersions.d.ts.map +1 -0
  158. package/dist/sdkVersions.js +8 -0
  159. package/dist/selfieCapture/captureQuality.d.ts +43 -0
  160. package/dist/selfieCapture/captureQuality.d.ts.map +1 -0
  161. package/dist/selfieCapture/captureQuality.js +87 -0
  162. package/dist/selfieCapture/challengeRunner.d.ts +9 -2
  163. package/dist/selfieCapture/challengeRunner.d.ts.map +1 -1
  164. package/dist/selfieCapture/challengeRunner.js +2 -5
  165. package/dist/selfieCapture/controller.d.ts +62 -1
  166. package/dist/selfieCapture/controller.d.ts.map +1 -1
  167. package/dist/selfieCapture/controller.js +470 -105
  168. package/dist/selfieCapture/faceTracking.d.ts +69 -1
  169. package/dist/selfieCapture/faceTracking.d.ts.map +1 -1
  170. package/dist/selfieCapture/faceTracking.js +134 -6
  171. package/dist/selfieCapture/guidance.d.ts +64 -0
  172. package/dist/selfieCapture/guidance.d.ts.map +1 -1
  173. package/dist/selfieCapture/guidance.js +74 -0
  174. package/dist/selfieCapture/index.d.ts +4 -3
  175. package/dist/selfieCapture/index.d.ts.map +1 -1
  176. package/dist/selfieCapture/index.js +2 -2
  177. package/dist/selfieCapture/livenessMachine.d.ts +2 -0
  178. package/dist/selfieCapture/livenessMachine.d.ts.map +1 -1
  179. package/dist/selfieCapture/livenessMachine.js +8 -0
  180. package/dist/selfieCapture/pipeline.d.ts +8 -0
  181. package/dist/selfieCapture/pipeline.d.ts.map +1 -1
  182. package/dist/selfieCapture/pipeline.js +2 -2
  183. package/dist/selfieCapture/reducer.d.ts +7 -0
  184. package/dist/selfieCapture/reducer.d.ts.map +1 -1
  185. package/dist/selfieCapture/reducer.js +45 -4
  186. package/dist/selfieCapture/state.d.ts +6 -0
  187. package/dist/selfieCapture/state.d.ts.map +1 -1
  188. package/dist/selfieCapture/state.js +1 -0
  189. package/dist/signature/frameDecode.d.ts.map +1 -1
  190. package/dist/signature/frameDecode.js +29 -0
  191. package/dist/signature/metadata.d.ts +10 -1
  192. package/dist/signature/metadata.d.ts.map +1 -1
  193. package/dist/signature/quality.d.ts +14 -6
  194. package/dist/signature/quality.d.ts.map +1 -1
  195. package/dist/signature/quality.js +13 -4
  196. package/dist/signatureCapture/controller.d.ts +2 -1
  197. package/dist/signatureCapture/controller.d.ts.map +1 -1
  198. package/dist/signatureCapture/controller.js +118 -23
  199. package/dist/signatureCapture/pipeline.d.ts +14 -2
  200. package/dist/signatureCapture/pipeline.d.ts.map +1 -1
  201. package/dist/signatureCapture/pipeline.js +36 -8
  202. package/dist/signatureCapture/state.d.ts +15 -0
  203. package/dist/signatureCapture/state.d.ts.map +1 -1
  204. package/dist/version.d.ts +1 -1
  205. package/dist/version.d.ts.map +1 -1
  206. package/dist/version.js +1 -1
  207. package/dist/videoIdCapture/controller.d.ts.map +1 -1
  208. package/dist/videoIdCapture/controller.js +64 -3
  209. package/package.json +10 -2
@@ -18,17 +18,60 @@ import { createStore } from 'zustand/vanilla';
18
18
  import { acquireCamera, } from '../camera/acquireCamera';
19
19
  import { CaptureAttachError } from '../idCapture/errors';
20
20
  import { error, warn } from '../utils/logger';
21
+ import { createAutoCaptureEngine, } from './autoCaptureEngine';
22
+ import { advanceAutoCaptureShutter, createAutoCaptureShutterState, openManualBurst, retryAutoCaptureShutter, } from './autoCaptureShutter';
23
+ import { resolveAutoCapture } from './autoCaptureOptions';
24
+ import { accumulateFrame, buildAttemptMetadata, createAttemptAccumulator, retryAttempt, toFileMetadata, } from './autoCaptureMetadata';
21
25
  import { reduceDocumentCapture } from './reducer';
22
26
  import { buildEntries, createInitialDocumentCaptureState, toCapturedDocument, } from './state';
23
- /** Default frame grab: draw the current video frame and encode it as a JPEG. */
24
- function defaultCaptureFrame(video) {
27
+ /**
28
+ * The focus score of a frame nothing could rank.
29
+ *
30
+ * Below every real reading, including a genuine 0.0, so an unranked frame
31
+ * always loses to a measured one. It can still win when nothing is banked —
32
+ * an unranked frame beats no frame at all.
33
+ */
34
+ const UNRANKED_FOCUS = -1;
35
+ /**
36
+ * Default frame grab: the WHOLE camera frame, encoded as a JPEG.
37
+ *
38
+ * Saved uncropped because the checks run on the whole frame, and a sheet is
39
+ * only guaranteed complete within the rectangle they looked at. #385 cropped to
40
+ * the guide rect — the box the applicant is asked to fill — on the reasoning
41
+ * that "what you framed is what you submit" only holds while the two agree. It
42
+ * did the opposite on a portrait phone: the guide spans the camera's full width
43
+ * but leaves ~196px of frame above and below it, so a sheet spilling past the
44
+ * guide's top was seen whole by the detector, passed every gate, and was then
45
+ * cut by the crop. Product testing caught one.
46
+ *
47
+ * Uncropped, only the camera itself can cut the page, and that is the one edge
48
+ * auto-capture already refuses to fire on (`touchesFrameEdge`). A manual tap
49
+ * is not checked — it is the applicant's call, and saves whatever was in
50
+ * frame. The guide rect still decides framing — `fill` is measured against it,
51
+ * and it is what the applicant is shown — it just no longer decides which
52
+ * pixels are thrown away.
53
+ *
54
+ * Takes no `aspectRatio`, though the controller passes one: that argument
55
+ * exists for a custom `io.captureFrame`, and the whole frame is the answer
56
+ * here whatever the guide's shape.
57
+ *
58
+ * The cost is background around the page: a band of desk above and below on a
59
+ * phone, and on a 16:9 webcam the desk either side of a page column. That is
60
+ * the image every document got before `autoCapture` existed, so it is not new
61
+ * to any backend.
62
+ *
63
+ * The `drawImage` is SYNCHRONOUS and must stay that way — `captureSource` can
64
+ * hand over the auto-capture engine's live frame canvas, which the next frame
65
+ * overwrites. Everything before the `toBlob` runs in the caller's own tick.
66
+ */
67
+ function defaultCaptureFrame(source) {
25
68
  const canvas = document.createElement('canvas');
26
- canvas.width = video.videoWidth;
27
- canvas.height = video.videoHeight;
69
+ canvas.width = source.width;
70
+ canvas.height = source.height;
28
71
  const ctx = canvas.getContext('2d');
29
72
  if (!ctx)
30
73
  return Promise.resolve(null);
31
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
74
+ ctx.drawImage(source.image, 0, 0, source.width, source.height);
32
75
  return new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.95));
33
76
  }
34
77
  // `acquireCamera` rejects with a `CaptureAttachError` carrying the precise
@@ -60,6 +103,8 @@ export function createDocumentCaptureController(config) {
60
103
  const acquire = config.io?.acquireCamera ?? acquireCamera;
61
104
  const captureFrame = config.io?.captureFrame ?? defaultCaptureFrame;
62
105
  const createObjectUrl = config.io?.createObjectUrl ?? ((blob) => URL.createObjectURL(blob));
106
+ const makeAutoCaptureEngine = config.io?.createAutoCaptureEngine ?? createAutoCaptureEngine;
107
+ const createCanvas = config.io?.createCanvas ?? (() => document.createElement('canvas'));
63
108
  const store = createStore(() => createInitialDocumentCaptureState(buildEntries(config.documents ?? [], createObjectUrl)));
64
109
  const listeners = new Set();
65
110
  // Which document indices have already emitted each callback. Cleared for an
@@ -71,6 +116,94 @@ export function createDocumentCaptureController(config) {
71
116
  let attachedVideo = null;
72
117
  let camera = null;
73
118
  let disposed = false;
119
+ // One engine per opted-in document, created on first need and torn down when
120
+ // the loop should not be running. Documents without an `autoCapture` bag
121
+ // never construct one, so a manual-shutter flow downloads no models.
122
+ let engine = null;
123
+ let engineIndex = null;
124
+ /**
125
+ * The sharpest satisfied frame seen in the current burst window.
126
+ *
127
+ * ONE canvas, not a ring of them. Six full-resolution candidates would be
128
+ * ~50 MB at the 1079x1920 a phone hands us, and an oversized canvas backing
129
+ * store is exactly what got the tab killed under pinch zoom. Keeping only
130
+ * the best-so-far is O(1) and loses nothing: the loop only ever needs the
131
+ * maximum, never the history.
132
+ *
133
+ * Lazily allocated, so a flow that never opts into auto-capture pays
134
+ * nothing.
135
+ */
136
+ /**
137
+ * `manualBurstWindowMs` for the engine currently running, or 0 for none.
138
+ *
139
+ * Reset by `stopAutoCapture`, so a tap arriving after a teardown falls back
140
+ * to saving the live frame rather than opening a window against an engine
141
+ * that will never close it.
142
+ */
143
+ let manualBurstWindowForEngine = 0;
144
+ /**
145
+ * Wall-clock length of the burst window currently open, or 0 for none.
146
+ *
147
+ * Held rather than recomputed, so what the view sweeps cannot drift from
148
+ * what the shutter is actually counting: the frame count is fixed when the
149
+ * window opens, and the measured rate moves afterwards.
150
+ *
151
+ * One number rather than one per document, because only the current
152
+ * document can have a window open — `stopAutoCapture` clears it, and that
153
+ * runs on every index change.
154
+ */
155
+ let manualBurstMs = 0;
156
+ let bestFrameCanvas = null;
157
+ let bestFrameFocus = UNRANKED_FOCUS;
158
+ /**
159
+ * The diagnostics of the banked frame — ITS PAIR, not the latest reading.
160
+ *
161
+ * `boundingBox` and `framing` claim to describe the submitted artifact, and
162
+ * the burst window runs through unsatisfied frames on purpose, so the last
163
+ * frame the engine saw can be one the applicant never submitted. Banking the
164
+ * pixels and their measurements together is what keeps the two describing
165
+ * the same moment.
166
+ */
167
+ let bestFrameDiagnostics = null;
168
+ // Per document, because a second document is a fresh framing problem and
169
+ // therefore a fresh escape budget. Keyed rather than reset on advance so a
170
+ // granted escape survives `uploadCompleted` moving the index and back.
171
+ const shutterByIndex = new Map();
172
+ // Per document too. Created LAZILY on the first frame, so a document that
173
+ // never ran an engine has `null` here and reports its auto-capture fields
174
+ // absent rather than zeroed.
175
+ const accumulatorByIndex = new Map();
176
+ // The last torn-down engine's ring buffer, so the log outlives the capture
177
+ // that ended the loop. Replaced wholesale by the next engine's drain rather
178
+ // than appended to, so two sessions never interleave in one export.
179
+ let lastAutoCaptureLog = [];
180
+ const documentOpenedAt = new Map();
181
+ /**
182
+ * Stamp when a document first became the current one, for `operationTime`.
183
+ * Set on the first frame or the first capture, whichever comes first, so a
184
+ * manual-only document still reports one.
185
+ */
186
+ function markDocumentOpen(index) {
187
+ if (!documentOpenedAt.has(index)) {
188
+ documentOpenedAt.set(index, now().getTime());
189
+ }
190
+ }
191
+ function accumulatorFor(index) {
192
+ const existing = accumulatorByIndex.get(index);
193
+ if (existing)
194
+ return existing;
195
+ const fresh = createAttemptAccumulator();
196
+ accumulatorByIndex.set(index, fresh);
197
+ return fresh;
198
+ }
199
+ function shutterFor(index) {
200
+ const existing = shutterByIndex.get(index);
201
+ if (existing)
202
+ return existing;
203
+ const fresh = createAutoCaptureShutterState();
204
+ shutterByIndex.set(index, fresh);
205
+ return fresh;
206
+ }
74
207
  function publish() {
75
208
  const snapshot = store.getState();
76
209
  for (const listener of listeners) {
@@ -85,6 +218,442 @@ export function createDocumentCaptureController(config) {
85
218
  function dispatch(event) {
86
219
  store.setState((state) => reduceDocumentCapture(state, event), true);
87
220
  publish();
221
+ // The engine's own per-frame dispatches must not re-enter this — they
222
+ // cannot change whether the loop should run, and re-entering would rebuild
223
+ // the engine from inside its own callback.
224
+ if (event.type !== 'autoCaptureFrame' && event.type !== 'videoDimensions') {
225
+ syncAutoCapture();
226
+ }
227
+ }
228
+ function stopAutoCapture() {
229
+ // Drain the ring buffer BEFORE dropping the engine. #341 makes the log the
230
+ // actual deliverable of a tuning session, and an accepted capture is what
231
+ // tears the engine down — so without this, COPY/SAVE LOG returns an empty
232
+ // array at exactly the moment an operator reaches for it.
233
+ const drained = engine?.getDiagnosticsLog();
234
+ if (drained && drained.length > 0)
235
+ lastAutoCaptureLog = drained;
236
+ engine?.stop();
237
+ engine = null;
238
+ engineIndex = null;
239
+ // The banked frame belongs to the engine that produced it. Carrying it
240
+ // across a teardown would let a retry, or the next document, submit a
241
+ // picture taken before either began.
242
+ clearBestFrame();
243
+ // So does an open burst window. The window counts down on EVERY frame,
244
+ // satisfied or not — which is what makes it tolerate focus excursions —
245
+ // so one left open across a detach would resume counting against the next
246
+ // engine's frames and fire a capture on frames that satisfied nothing.
247
+ manualBurstWindowForEngine = 0;
248
+ manualBurstMs = 0;
249
+ for (const [index, shutter] of shutterByIndex) {
250
+ if (shutter.burstFramesRemaining === null &&
251
+ shutter.manualBurstFramesRemaining === null) {
252
+ continue;
253
+ }
254
+ shutterByIndex.set(index, {
255
+ ...shutter,
256
+ burstFramesRemaining: null,
257
+ manualBurstFramesRemaining: null,
258
+ });
259
+ }
260
+ }
261
+ /**
262
+ * Start, stop, or re-target the detection loop to match current state.
263
+ *
264
+ * Called from `dispatch` rather than from each transition site, because four
265
+ * unrelated events move the answer — the camera arriving, a capture landing
266
+ * (the preview is up, there is nothing to detect), a retry clearing it, and
267
+ * `uploadCompleted` advancing to a document with a different `autoCapture`
268
+ * bag. Deriving it in one place is what stops the loop surviving into a
269
+ * document that never opted in.
270
+ */
271
+ function syncAutoCapture() {
272
+ if (disposed || !attachedVideo) {
273
+ stopAutoCapture();
274
+ return;
275
+ }
276
+ const state = store.getState();
277
+ const index = state.currentIndex;
278
+ const entry = state.documents[index];
279
+ const wanted = state.camera.ready && entry && !entry.content
280
+ ? entry.item.autoCapture
281
+ : undefined;
282
+ if (!wanted) {
283
+ stopAutoCapture();
284
+ return;
285
+ }
286
+ if (engine && engineIndex === index)
287
+ return;
288
+ stopAutoCapture();
289
+ engineIndex = index;
290
+ // Resolved once per engine rather than once per frame: the bag is
291
+ // mount-time-only, so re-resolving 17 times a second only allocates.
292
+ const { manualFallbackAfterMs, burstWindowMs, manualBurstWindowMs } = resolveAutoCapture(wanted, undefined);
293
+ // The tap arrives outside the frame loop and needs the same resolved bag,
294
+ // so it is held rather than re-resolved from a document that may since
295
+ // have advanced.
296
+ manualBurstWindowForEngine = manualBurstWindowMs;
297
+ // Captured so a late frame from a torn-down engine can identify itself.
298
+ // `const` is fine despite the self-reference inside `onDiagnostics`: that
299
+ // closure cannot run until the engine exists, so the binding is always
300
+ // initialised by the time it is read.
301
+ const thisEngine = makeAutoCaptureEngine({
302
+ ...config.autoCaptureEngine,
303
+ autoCapture: wanted,
304
+ // The guide rect the gate measures `fill` against. The saved image is
305
+ // the whole frame regardless — see defaultCaptureFrame.
306
+ aspectRatio: entry.item.aspectRatio,
307
+ onModelsChanged: (models) => dispatch({ type: 'autoCaptureModelsChanged', models }),
308
+ onDiagnostics: (diagnostics) => {
309
+ // A frame already past `runFrame`'s own `stopped` checks can still land
310
+ // here after the engine has been torn down — by a capture landing, a
311
+ // detach, or the index advancing. Acting on it would spend the escape
312
+ // budget for a document that is no longer on screen and, worse, fire a
313
+ // SECOND capture over the one just accepted (`captureNow`'s own guards
314
+ // clear the moment `capturing` goes false again).
315
+ if (engine !== thisEngine)
316
+ return;
317
+ dispatch({
318
+ type: 'videoDimensions',
319
+ videoWidth: diagnostics.videoWidth,
320
+ videoHeight: diagnostics.videoHeight,
321
+ });
322
+ dispatch({ type: 'autoCaptureFrame', diagnostics });
323
+ markDocumentOpen(index);
324
+ accumulatorByIndex.set(index, accumulateFrame(accumulatorFor(index), diagnostics));
325
+ // BEFORE the shutter: the frame that closes the burst window is itself
326
+ // a candidate, and banking after the decision would exclude it.
327
+ bankBestFrame(diagnostics, shutterFor(index).manualBurstFramesRemaining !== null);
328
+ runShutter(index, manualFallbackAfterMs, burstWindowMs, diagnostics);
329
+ },
330
+ });
331
+ engine = thisEngine;
332
+ engine.start(attachedVideo);
333
+ }
334
+ /**
335
+ * Bank this frame if it is the sharpest candidate so far.
336
+ *
337
+ * Copies out of the engine's live frame canvas, which the next frame
338
+ * overwrites — so this has to happen synchronously, on the same tick as the
339
+ * diagnostics that scored it.
340
+ *
341
+ * A frame with no focus reading (model absent, or the gates skipped the
342
+ * prediction) scores -1 and can only win if nothing else has: better to
343
+ * carry an unranked candidate than to carry none.
344
+ *
345
+ * `anyFrame` is the applicant's tap talking. Auto-capture may only ever
346
+ * submit a frame that passed every gate — that guarantee is the entire point
347
+ * of the workstream — but the tap is a human deciding this framing is good
348
+ * enough, and it usually arrives BECAUSE the gates are unhappy. Ranking only
349
+ * satisfied frames there would leave the bank empty on exactly the captures
350
+ * this is meant to sharpen.
351
+ */
352
+ function bankBestFrame(diagnostics, anyFrame) {
353
+ if (!anyFrame && !diagnostics.satisfied)
354
+ return;
355
+ const graded = engine?.getGradedFrame();
356
+ if (!graded || graded.width <= 0 || graded.height <= 0)
357
+ return;
358
+ const focus = diagnostics.focus ? diagnostics.focus.score : UNRANKED_FOCUS;
359
+ // Tests for banked CONTENT rather than for the element. `clearBestFrame`
360
+ // keeps the canvas and zeroes it, so checking the element alone would let
361
+ // the first frame after every retry be rejected — and this is the same
362
+ // condition `captureSource` reads, so the two cannot disagree.
363
+ const hasBanked = !!bestFrameCanvas && bestFrameCanvas.width > 0;
364
+ if (hasBanked) {
365
+ // AMONG UNRANKED FRAMES, THE LATEST WINS. Everywhere else a candidate
366
+ // has to strictly beat the bank.
367
+ //
368
+ // Unranked means the whole window scored -1: the focus model failed to
369
+ // load, or no frame in it had a detected box to crop a prediction from.
370
+ // One of them still has to win, and later is the better default, because
371
+ // the tap that opened the window is also what shook the phone — keeping
372
+ // the first would hand back the jostle itself.
373
+ //
374
+ // Ranked ties keep the bank, which is not a detail: a burst of equal
375
+ // scores would otherwise redraw a full-resolution canvas on every frame
376
+ // to arrive at the same picture.
377
+ const beatsBank = focus === UNRANKED_FOCUS
378
+ ? bestFrameFocus === UNRANKED_FOCUS
379
+ : focus > bestFrameFocus;
380
+ if (!beatsBank)
381
+ return;
382
+ }
383
+ if (!bestFrameCanvas)
384
+ bestFrameCanvas = createCanvas();
385
+ if (bestFrameCanvas.width !== graded.width ||
386
+ bestFrameCanvas.height !== graded.height) {
387
+ bestFrameCanvas.width = graded.width;
388
+ bestFrameCanvas.height = graded.height;
389
+ }
390
+ const ctx = bestFrameCanvas.getContext('2d');
391
+ if (!ctx)
392
+ return;
393
+ ctx.drawImage(graded, 0, 0);
394
+ bestFrameFocus = focus;
395
+ // Same assignment, same tick: the pair is what makes the metadata honest.
396
+ bestFrameDiagnostics = diagnostics;
397
+ }
398
+ /**
399
+ * Open the applicant's burst window, or report that there is none to open.
400
+ *
401
+ * False means "capture right now", which covers every case the window
402
+ * cannot serve: no engine, no measured frame rate to convert the window
403
+ * with, `manualBurstWindowMs: 0`, or a capture already in flight.
404
+ */
405
+ function openManualBurstFor(index) {
406
+ if (!engine || engineIndex !== index)
407
+ return false;
408
+ const state = store.getState();
409
+ if (state.capturing || !state.camera.ready)
410
+ return false;
411
+ const shutter = shutterFor(index);
412
+ // A second tap must not restart the wait it is impatient with.
413
+ if (shutter.manualBurstFramesRemaining !== null)
414
+ return true;
415
+ const frameRate = state.autoCapture?.frameRate ?? 0;
416
+ const next = openManualBurst(shutter, frameRate, manualBurstWindowForEngine);
417
+ if (next.manualBurstFramesRemaining === null)
418
+ return false;
419
+ // What the view sweeps. Derived from the FRAME COUNT, not from the setting
420
+ // it was converted out of, so the ring finishes when the shutter fires
421
+ // rather than a rounding error before it.
422
+ manualBurstMs = (next.manualBurstFramesRemaining / frameRate) * 1000;
423
+ shutterByIndex.set(index, next);
424
+ // Focus normally runs only on frames that already passed every other gate,
425
+ // which is the loop's biggest saving and is exactly wrong here: a tap
426
+ // arrives BECAUSE the gates are unhappy, so without this every frame in
427
+ // the window scores `null` and the ranking has nothing to rank. It stays
428
+ // on for the length of the window and no longer.
429
+ engine.setMeasureFocusEveryFrame(true);
430
+ publishShutter(index);
431
+ // Whatever the auto path banked belongs to the moment BEFORE the tap. The
432
+ // window is allowed to rank unsatisfied frames precisely because they are
433
+ // the applicant's own; letting a pre-tap satisfied frame win would submit
434
+ // a photo they did not take, and would do it while calling it 'Manual'.
435
+ clearBestFrame();
436
+ return true;
437
+ }
438
+ /** Drop the banked frame and release its backing store. */
439
+ function clearBestFrame() {
440
+ bestFrameFocus = UNRANKED_FOCUS;
441
+ bestFrameDiagnostics = null;
442
+ if (!bestFrameCanvas)
443
+ return;
444
+ // Zeroing frees the pixels; keeping the element avoids re-allocating one
445
+ // per attempt.
446
+ bestFrameCanvas.width = 0;
447
+ bestFrameCanvas.height = 0;
448
+ }
449
+ /**
450
+ * Advance the shutter for `index` and act on its decision.
451
+ *
452
+ * Runs AFTER the frame has been dispatched, so a consumer watching state sees
453
+ * the reading that fired the capture rather than the one before it.
454
+ */
455
+ function runShutter(index, manualFallbackAfterMs, burstWindowMs, diagnostics) {
456
+ const decision = advanceAutoCaptureShutter(shutterFor(index), {
457
+ satisfied: diagnostics.satisfied,
458
+ timeRunning: diagnostics.timeRunning,
459
+ frameRate: diagnostics.frameRate,
460
+ }, manualFallbackAfterMs, burstWindowMs);
461
+ shutterByIndex.set(index, decision.state);
462
+ if (decision.revealManualShutter)
463
+ publishShutter(index);
464
+ // The window closing is a state change the view renders: it holds the
465
+ // shutter pressed for as long as one is open.
466
+ if (decision.captureManual) {
467
+ engine?.setMeasureFocusEveryFrame(false);
468
+ manualBurstMs = 0;
469
+ publishShutter(index);
470
+ }
471
+ // `capture()` re-guards on `capturing` and on the camera, so a shutter that
472
+ // fires twice before the first frame grab resolves is a no-op, not a race.
473
+ if (decision.capture)
474
+ void captureNow('Auto', true);
475
+ // The applicant's own window closing. Still `'Manual'` — the tap is what
476
+ // took this photo, and the window only chose which of its frames to keep.
477
+ if (decision.captureManual)
478
+ void captureNow('Manual', true);
479
+ }
480
+ /** Mirror the shutter's public half onto state for the view to render. */
481
+ function publishShutter(index) {
482
+ const shutter = shutterByIndex.get(index);
483
+ if (!shutter)
484
+ return;
485
+ dispatch({
486
+ type: 'autoCaptureShutterChanged',
487
+ shutter: {
488
+ manualShutterAvailable: shutter.manualShutterAvailable,
489
+ manualBurstMs: shutter.manualBurstFramesRemaining !== null ? manualBurstMs : null,
490
+ },
491
+ });
492
+ }
493
+ /**
494
+ * Grab a frame and record HOW it was triggered.
495
+ *
496
+ * `'Auto'` vs `'Manual'` is the first honest use of that distinction in this
497
+ * SDK — `selfieCapture/controller.ts` stamps 'Y' even on its manual button —
498
+ * and it is what makes "auto-capture gave up" countable.
499
+ */
500
+ /**
501
+ * Which pixels this capture saves.
502
+ *
503
+ * An AUTO capture saves the frame the gates were measured on, not the live
504
+ * video. The loop draws a frame, then awaits detection and focus before the
505
+ * shutter sees its verdict — so by the time `captureNow` runs, the video
506
+ * element is an inference round-trip ahead of the image that was certified
507
+ * sharp and stable. At the 15-35 fps this model runs at that is 60-120 ms of
508
+ * hand motion between "in focus" and the shutter, and it is the difference
509
+ * between a focus gate that means something and one that grades a photo
510
+ * nobody submits.
511
+ *
512
+ * A MANUAL capture with no window keeps the live video: the tap is the
513
+ * applicant's intent, expressed at a moment of their choosing, and handing
514
+ * them a frame from before the tap would be the same bug pointed the other
515
+ * way. With `manualBurstWindowMs` set it reads the bank too — but that bank
516
+ * only ever holds frames from AFTER the tap, so the property survives.
517
+ *
518
+ * The engine's canvas is live and the next frame overwrites it, so this is
519
+ * only sound because the whole path from `onDiagnostics` to the `drawImage`
520
+ * inside `captureFrame` is synchronous — no `await` runs in between, so the
521
+ * loop cannot have advanced. `controller.test.ts` pins that.
522
+ */
523
+ /**
524
+ * The pixels this capture saves, WITH the diagnostics that describe them.
525
+ *
526
+ * Returned as one value on purpose. `boundingBox` and `framing` claim to
527
+ * describe the submitted artifact, and both the burst window and the JPEG
528
+ * encode let the loop advance between choosing a frame and finishing with
529
+ * it — so anything that re-reads "the latest frame" later is describing a
530
+ * different moment. Resolved together, synchronously, before either.
531
+ */
532
+ function captureSource(graded) {
533
+ const video = attachedVideo;
534
+ if (!video)
535
+ return null;
536
+ if (graded) {
537
+ // The sharpest frame of the burst window, when there is one. Firing on
538
+ // the frame that happened to close the window would be back to sampling
539
+ // focus at an arbitrary moment.
540
+ const banked = bestFrameCanvas;
541
+ if (banked && banked.width > 0 && banked.height > 0) {
542
+ return {
543
+ source: { image: banked, width: banked.width, height: banked.height },
544
+ acceptedFrame: bestFrameDiagnostics,
545
+ };
546
+ }
547
+ const graded = engine?.getGradedFrame();
548
+ if (graded) {
549
+ return {
550
+ source: { image: graded, width: graded.width, height: graded.height },
551
+ // Not banked, so the frame the engine last reported IS this one.
552
+ acceptedFrame: store.getState().autoCapture ?? null,
553
+ };
554
+ }
555
+ }
556
+ return {
557
+ source: { image: video, width: video.videoWidth, height: video.videoHeight },
558
+ acceptedFrame: null,
559
+ };
560
+ }
561
+ /**
562
+ * `graded` chooses the PIXELS: the frame the models measured, or the live
563
+ * video element.
564
+ *
565
+ * A separate argument from `mode` because the two stopped being the same
566
+ * question once the applicant's tap grew a window of its own. `mode` records
567
+ * who pressed the shutter and reaches the backend as `autoCapture` Y/N;
568
+ * `graded` records which pixels won, and a tap that waited out its window is
569
+ * `'Manual'` on graded pixels.
570
+ */
571
+ async function captureNow(mode, graded) {
572
+ if (disposed || !attachedVideo)
573
+ return;
574
+ const index = store.getState().currentIndex;
575
+ markDocumentOpen(index);
576
+ // A capture with no camera grabs an empty frame and reports a spurious
577
+ // CAPTURE_FAILED; a re-entrant one races two frames into one slot. The
578
+ // view guards both, but the controller is public API and a custom UI can
579
+ // call straight in — as, now, can the auto shutter.
580
+ const current = store.getState();
581
+ if (current.capturing || !current.camera.ready)
582
+ return;
583
+ // BEFORE the dispatch, which can re-enter `syncAutoCapture` and drop the
584
+ // engine whose canvas this is.
585
+ const chosen = captureSource(graded);
586
+ if (!chosen)
587
+ return;
588
+ const { source, acceptedFrame } = chosen;
589
+ dispatch({ type: 'captureRequested' });
590
+ try {
591
+ // The default saves the whole frame for every document — see
592
+ // defaultCaptureFrame — which keeps spec §3.1 by construction: a 2.x
593
+ // integrator who passes `aspectRatio` and no `autoCapture` gets the same
594
+ // bytes they have received since 2.4, because nobody gets a crop.
595
+ //
596
+ // The guide aspect is still passed, opted-in documents only, because
597
+ // `io.captureFrame` is public and custom grabs were written against it.
598
+ const item = store.getState().documents[index]?.item;
599
+ const content = await captureFrame(source, item?.autoCapture ? item.aspectRatio : undefined);
600
+ // Detached mid-capture: dispatching now would mutate a dead controller's
601
+ // store and leak the object URL.
602
+ if (disposed)
603
+ return;
604
+ if (!content) {
605
+ dispatch({
606
+ type: 'captureFailed',
607
+ message: 'The camera returned no frame.',
608
+ });
609
+ return;
610
+ }
611
+ dispatch({
612
+ type: 'captureCompleted',
613
+ content,
614
+ contentUrl: createObjectUrl(content),
615
+ captureMode: mode,
616
+ captureMetadata: buildCaptureMetadata(index, mode, acceptedFrame),
617
+ });
618
+ emitLifecycle();
619
+ }
620
+ catch (error) {
621
+ dispatch({
622
+ type: 'captureFailed',
623
+ message: error instanceof Error ? error.message : String(error),
624
+ });
625
+ }
626
+ }
627
+ /**
628
+ * Why auto-capture was, or was not, the thing that fired (#377).
629
+ *
630
+ * The SDK can only report the reasons it can see. `disabled:flag`,
631
+ * `disabled:param` and `disabled:lateFlag` are host-side facts — the host
632
+ * simply does not bind `autoCapture` — so from here they are all
633
+ * `disabled:unconfigured`, and the host distinguishes them on channel B
634
+ * before aggregating. `disabled:lateFlag` is additionally warned about at
635
+ * the flow layer, where the change is actually observable.
636
+ */
637
+ function autoCaptureStatus(mode) {
638
+ const state = store.getState();
639
+ const entry = state.documents[state.currentIndex];
640
+ if (!entry?.item.autoCapture)
641
+ return 'disabled:unconfigured';
642
+ if (state.models.state === 'error')
643
+ return 'disabled:modelLoadFailed';
644
+ if (mode === 'Manual' && state.autoCaptureShutter?.manualShutterAvailable) {
645
+ return 'timedOutToManual';
646
+ }
647
+ return 'engaged';
648
+ }
649
+ function buildCaptureMetadata(index, mode, acceptedFrame) {
650
+ const openedAt = documentOpenedAt.get(index);
651
+ return buildAttemptMetadata(accumulatorByIndex.get(index) ?? null, {
652
+ captureMode: mode,
653
+ autoCaptureStatus: autoCaptureStatus(mode),
654
+ operationTime: openedAt === undefined ? null : Math.round(now().getTime() - openedAt),
655
+ acceptedFrame,
656
+ });
88
657
  }
89
658
  function currentEntry() {
90
659
  const state = store.getState();
@@ -155,9 +724,13 @@ export function createDocumentCaptureController(config) {
155
724
  // A pre-supplied blob is already "captured" as far as consumers are
156
725
  // concerned, so its callback fires as soon as the controller is live.
157
726
  emitLifecycle();
727
+ // Re-attach revives a detached controller whose camera is still live, so
728
+ // no `cameraReady` dispatch follows to start the loop for us.
729
+ syncAutoCapture();
158
730
  },
159
731
  detach() {
160
732
  disposed = true;
733
+ stopAutoCapture();
161
734
  camera?.release();
162
735
  camera = null;
163
736
  attachedVideo = null;
@@ -168,6 +741,12 @@ export function createDocumentCaptureController(config) {
168
741
  // detaches.
169
742
  },
170
743
  getState: () => store.getState(),
744
+ getAutoCaptureLog: () => {
745
+ // A running engine is always the fresher of the two; the retained copy
746
+ // only answers once the loop has stopped.
747
+ const live = engine?.getDiagnosticsLog();
748
+ return live && live.length > 0 ? live : lastAutoCaptureLog;
749
+ },
171
750
  subscribe(cb) {
172
751
  listeners.add(cb);
173
752
  return () => {
@@ -182,43 +761,22 @@ export function createDocumentCaptureController(config) {
182
761
  collectArtifacts: () => ({}),
183
762
  actions: {
184
763
  requestCamera,
185
- async capture() {
186
- if (disposed || !attachedVideo)
764
+ /**
765
+ * The applicant tapped.
766
+ *
767
+ * Pressing the screen moves the phone, so the frame the tap lands on is
768
+ * among the worst available. When an engine is running, the tap opens a
769
+ * short window and the sharpest frame in it is what gets saved — see
770
+ * `DEFAULT_MANUAL_BURST_WINDOW_MS`. Without an engine there is nothing
771
+ * to rank frames with, and this is the plain shutter it has always been.
772
+ */
773
+ capture: async () => {
774
+ if (disposed)
187
775
  return;
188
- // A capture with no camera grabs an empty frame and reports a spurious
189
- // CAPTURE_FAILED; a re-entrant one races two frames into one slot. The
190
- // view guards both, but the controller is public API and a custom UI
191
- // can call straight in.
192
- const current = store.getState();
193
- if (current.capturing || !current.camera.ready)
776
+ const index = store.getState().currentIndex;
777
+ if (openManualBurstFor(index))
194
778
  return;
195
- dispatch({ type: 'captureRequested' });
196
- try {
197
- const content = await captureFrame(attachedVideo);
198
- // Detached mid-capture: dispatching now would mutate a dead
199
- // controller's store and leak the object URL.
200
- if (disposed)
201
- return;
202
- if (!content) {
203
- dispatch({
204
- type: 'captureFailed',
205
- message: 'The camera returned no frame.',
206
- });
207
- return;
208
- }
209
- dispatch({
210
- type: 'captureCompleted',
211
- content,
212
- contentUrl: createObjectUrl(content),
213
- });
214
- emitLifecycle();
215
- }
216
- catch (error) {
217
- dispatch({
218
- type: 'captureFailed',
219
- message: error instanceof Error ? error.message : String(error),
220
- });
221
- }
779
+ await captureNow('Manual', false);
222
780
  },
223
781
  retry() {
224
782
  if (disposed)
@@ -228,7 +786,22 @@ export function createDocumentCaptureController(config) {
228
786
  uploadedFired.delete(index);
229
787
  // The "all uploaded" guarantee no longer holds once an entry reverts.
230
788
  allUploadedFired = false;
789
+ // Re-arms auto-capture and resets the escape budget, but leaves a
790
+ // granted escape granted — see retryAutoCaptureShutter.
791
+ const shutter = shutterByIndex.get(index);
792
+ if (shutter)
793
+ shutterByIndex.set(index, retryAutoCaptureShutter(shutter));
794
+ // `attemptCount` must survive the retry, or the upload channel reports
795
+ // every capture as first-try — which looks like a valid measurement.
796
+ const accumulator = accumulatorByIndex.get(index);
797
+ if (accumulator) {
798
+ accumulatorByIndex.set(index, retryAttempt(accumulator));
799
+ }
800
+ // The rejected attempt's best frame is exactly what the applicant is
801
+ // retrying to get away from.
802
+ clearBestFrame();
231
803
  dispatch({ type: 'retryCapture' });
804
+ publishShutter(index);
232
805
  },
233
806
  async upload() {
234
807
  if (disposed)
@@ -247,6 +820,13 @@ export function createDocumentCaptureController(config) {
247
820
  metadata.jobid = config.jobID;
248
821
  if (config.taskID)
249
822
  metadata.taskid = config.taskID;
823
+ // Channel A. A proven field — the backend signature-video trimmer
824
+ // already reads it on another document type — and a bounded one: see
825
+ // `toFileMetadata` on the 2 KB tusd/S3 cap and the non-ASCII mangling
826
+ // that make a scalar spine the only safe payload.
827
+ if (entry.captureMetadata) {
828
+ metadata.filemetadata = toFileMetadata(entry.captureMetadata);
829
+ }
250
830
  try {
251
831
  const documentId = await config.client.uploadDocument(entry.content, metadata);
252
832
  // Detached mid-upload (session drop, view unmount): advancing the