@sekyro/web 0.1.0-rc.3 → 0.1.0-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +44 -0
- package/dist/{capture-session-v3-CvIfcwST.d.ts → capture-session-v3-Okq0EQHG.d.ts} +38 -2
- package/dist/{capture-session-v3-COIO_F2w.d.cts → capture-session-v3-UQU_WjO2.d.cts} +38 -2
- package/dist/{chunk-FIXX2AXC.js → chunk-SGDXLAXR.js} +309 -10
- package/dist/chunk-SGDXLAXR.js.map +1 -0
- package/dist/{chunk-7TC6TOZ4.js → chunk-TG5IE552.js} +37 -4
- package/dist/chunk-TG5IE552.js.map +1 -0
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/core/index.cjs +36 -3
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/{create-verification-CswF2As-.d.ts → create-verification-CA-3szPI.d.cts} +108 -8
- package/dist/{create-verification-CP18eq1Q.d.cts → create-verification-c98uAxbl.d.ts} +108 -8
- package/dist/{hosted-client-BpvBqu9f.d.cts → hosted-client-DWzCRYJK.d.cts} +14 -1
- package/dist/{hosted-client-BpvBqu9f.d.ts → hosted-client-DWzCRYJK.d.ts} +14 -1
- package/dist/index.cjs +384 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -3
- package/dist/index.d.ts +25 -3
- package/dist/index.js +61 -4
- package/dist/index.js.map +1 -1
- package/dist/internal/index.cjs +261 -11
- package/dist/internal/index.cjs.map +1 -1
- package/dist/internal/index.d.cts +4 -4
- package/dist/internal/index.d.ts +4 -4
- package/dist/internal/index.js +12 -2
- package/dist/internal/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7TC6TOZ4.js.map +0 -1
- package/dist/chunk-FIXX2AXC.js.map +0 -1
|
@@ -554,7 +554,8 @@ var FaceGateV3 = class {
|
|
|
554
554
|
p: this.p,
|
|
555
555
|
factors,
|
|
556
556
|
guidanceKey: this.guidanceOf(factors, quality, q),
|
|
557
|
-
ready
|
|
557
|
+
ready,
|
|
558
|
+
accepted: q >= this.t.Q_GOOD
|
|
558
559
|
};
|
|
559
560
|
}
|
|
560
561
|
geometryOf(observation, input) {
|
|
@@ -672,6 +673,11 @@ var CaptureSessionV3 = class {
|
|
|
672
673
|
this.profiler = null;
|
|
673
674
|
this.lastGuidanceKey = null;
|
|
674
675
|
this.positioningStartedAt = 0;
|
|
676
|
+
// Face-capture timing marks of the CURRENT attempt (engine clock; reset per run).
|
|
677
|
+
this.cameraRequestedAt = null;
|
|
678
|
+
this.cameraReadyAt = null;
|
|
679
|
+
this.faceAcquiredAt = null;
|
|
680
|
+
this.captureCompleteAt = null;
|
|
675
681
|
this.fired = false;
|
|
676
682
|
this.carriedDegrade = 0;
|
|
677
683
|
this.carriedMeans = [];
|
|
@@ -698,10 +704,15 @@ var CaptureSessionV3 = class {
|
|
|
698
704
|
handler(payload);
|
|
699
705
|
}
|
|
700
706
|
}
|
|
701
|
-
async start() {
|
|
707
|
+
async start(options = {}) {
|
|
708
|
+
if (options.facingMode !== void 0) this.facing = options.facingMode;
|
|
702
709
|
this.attempt += 1;
|
|
703
710
|
await this.run(this.attempt);
|
|
704
711
|
}
|
|
712
|
+
/** The camera the current/next attempt requests (start option, switchCamera toggles). */
|
|
713
|
+
get facingMode() {
|
|
714
|
+
return this.facing;
|
|
715
|
+
}
|
|
705
716
|
/** Full reset + camera restart — the documented recovery path (v1 parity). */
|
|
706
717
|
retry() {
|
|
707
718
|
this.teardownAttempt();
|
|
@@ -726,6 +737,10 @@ var CaptureSessionV3 = class {
|
|
|
726
737
|
this.lastGuidanceKey = null;
|
|
727
738
|
this.carriedDegrade = 0;
|
|
728
739
|
this.carriedMeans = [];
|
|
740
|
+
this.cameraRequestedAt = null;
|
|
741
|
+
this.cameraReadyAt = null;
|
|
742
|
+
this.faceAcquiredAt = null;
|
|
743
|
+
this.captureCompleteAt = null;
|
|
729
744
|
this.setState("preflight");
|
|
730
745
|
const preflight = cameraPreflight();
|
|
731
746
|
if (preflight !== "OK") {
|
|
@@ -735,6 +750,7 @@ var CaptureSessionV3 = class {
|
|
|
735
750
|
this.setState("acquiring");
|
|
736
751
|
const getUserMedia = options.getUserMedia ?? ((constraints) => navigator.mediaDevices.getUserMedia(constraints));
|
|
737
752
|
let stream;
|
|
753
|
+
this.cameraRequestedAt = this.now();
|
|
738
754
|
try {
|
|
739
755
|
stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));
|
|
740
756
|
} catch (err) {
|
|
@@ -750,6 +766,7 @@ var CaptureSessionV3 = class {
|
|
|
750
766
|
options.video.srcObject = stream;
|
|
751
767
|
await options.video.play().catch(() => void 0);
|
|
752
768
|
if (attempt !== this.attempt) return;
|
|
769
|
+
this.cameraReadyAt = this.now();
|
|
753
770
|
if (this.detector === null) {
|
|
754
771
|
const ladderOptions = {
|
|
755
772
|
...options.v3AssetBaseUrl !== void 0 ? { v3AssetBaseUrl: options.v3AssetBaseUrl } : {}
|
|
@@ -849,6 +866,7 @@ var CaptureSessionV3 = class {
|
|
|
849
866
|
frameWidth: video.videoWidth,
|
|
850
867
|
frameHeight: video.videoHeight
|
|
851
868
|
});
|
|
869
|
+
if (tick.accepted && this.faceAcquiredAt === null) this.faceAcquiredAt = tick.at;
|
|
852
870
|
this.emit("checks", {
|
|
853
871
|
engine: "v3",
|
|
854
872
|
progress: tick.p,
|
|
@@ -862,6 +880,7 @@ var CaptureSessionV3 = class {
|
|
|
862
880
|
}
|
|
863
881
|
if (tick.ready && this.stateValue === "positioning") {
|
|
864
882
|
this.fired = true;
|
|
883
|
+
this.captureCompleteAt = tick.at;
|
|
865
884
|
void this.fire(attempt);
|
|
866
885
|
}
|
|
867
886
|
}
|
|
@@ -956,7 +975,21 @@ var CaptureSessionV3 = class {
|
|
|
956
975
|
finishCapture(artifacts) {
|
|
957
976
|
this.stopTracks();
|
|
958
977
|
this.setState("captured");
|
|
959
|
-
this.
|
|
978
|
+
const timing = this.captureTiming();
|
|
979
|
+
this.emit("artifacts", timing === void 0 ? artifacts : { ...artifacts, timing });
|
|
980
|
+
}
|
|
981
|
+
/** The attempt's capture-phase timing (whole ms, ≥ 0); undefined when no mark landed. */
|
|
982
|
+
captureTiming() {
|
|
983
|
+
const span = (from, to) => from !== null && to !== null ? Math.max(0, Math.round(to - from)) : void 0;
|
|
984
|
+
const cameraReadyMs = span(this.cameraRequestedAt, this.cameraReadyAt);
|
|
985
|
+
const faceAcquireMs = span(this.cameraReadyAt, this.faceAcquiredAt);
|
|
986
|
+
const captureMs = span(this.faceAcquiredAt, this.captureCompleteAt);
|
|
987
|
+
const timing = {
|
|
988
|
+
...cameraReadyMs !== void 0 ? { cameraReadyMs } : {},
|
|
989
|
+
...faceAcquireMs !== void 0 ? { faceAcquireMs } : {},
|
|
990
|
+
...captureMs !== void 0 ? { captureMs } : {}
|
|
991
|
+
};
|
|
992
|
+
return Object.keys(timing).length > 0 ? timing : void 0;
|
|
960
993
|
}
|
|
961
994
|
// ── defaults for the canvas-bound seams ────────────────────────────────────
|
|
962
995
|
async defaultKeyframe(video) {
|
|
@@ -1092,4 +1125,4 @@ export {
|
|
|
1092
1125
|
KEYFRAME_WINDOW_MS,
|
|
1093
1126
|
CaptureSessionV3
|
|
1094
1127
|
};
|
|
1095
|
-
//# sourceMappingURL=chunk-
|
|
1128
|
+
//# sourceMappingURL=chunk-TG5IE552.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/capture-constraints.ts","../src/core/media.ts","../src/core/clip-recorder.ts","../src/core/keyframe.ts","../src/core/v3/device-profile.ts","../src/core/v3/detect-scheduler.ts","../src/core/v3/face-gate-v3.ts","../src/core/v3/capture-session-v3.ts"],"sourcesContent":["// Shared capture helpers — used by BOTH the (now sole) v3 engine and the\n// hosted gate-debug overlay. Extracted from the former v1 capture-session.ts\n// when the v1 engine was removed: the camera constraint tier + the mobile\n// heuristic are engine-agnostic, and the gate-geometry factors feed the\n// hosted debug overlay's tolerance rings. Zero React, calibration-pinned.\n\n/** getUserMedia constraint tier — 720p-class on every device since 2026-07-06.\n * The v2 FAS-CLIP liveness head loses its texture cues below ~720p: the SAME\n * genuine clip scores heads 0.0001 at 720x1280 vs 0.355 at the old 480x360\n * mobile tier, which pushed real users into review (first observed live on\n * staging 2026-07-06; falsified on corpus clips the same day). Dimensions are\n * sensor-relative (landscape); mobile browsers deliver portrait via rotation\n * metadata, which the liveness service's decoder applies (cv2\n * ORIENTATION_AUTO). `isMobile` is kept for call-site compat and future\n * divergence — both tiers are 720p today. Bitrate pairs with VIDEO_BPS in\n * clip-recorder.ts (2.5 Mbps). */\nexport function buildCaptureConstraints(\n isMobile: boolean,\n facingMode: \"user\" | \"environment\",\n): MediaStreamConstraints {\n void isMobile;\n return {\n video: {\n width: { ideal: 1280, max: 1280 },\n height: { ideal: 720, max: 720 },\n facingMode: facingMode,\n frameRate: { ideal: 24, max: 30 },\n },\n audio: false,\n };\n}\n\n/** v1 mobile heuristic (FaceCaptureV2.tsx L216-224). */\nexport function detectIsMobile(): boolean {\n if (typeof window === \"undefined\" || typeof navigator === \"undefined\") return false;\n return (\n window.innerWidth <= 768 ||\n /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n String(navigator.userAgent ?? \"\"),\n )\n );\n}\n\n// ── gate geometry factors ─────────────────────────────────────────────────────\n// The calibration-pinned gate math the hosted `?debug=gate` overlay derives its\n// tolerance rings from (lib/gate-geometry-constants.ts). Kept exported here after\n// the v1 FaceGate was removed so the overlay never restates them as literals.\n\n/** Gate radius as a fraction of the guidance circle (v1 L501: circleSize × 0.45). */\nexport const CIRCLE_RADIUS_FACTOR = 0.45;\n/** `inCircle` tolerance as a fraction of the gate radius (v1 L508: r × 0.9). */\nexport const IN_CIRCLE_FACTOR = 0.9;\n/** `centered` tolerance as a fraction of the gate radius (v1 L509: r × 0.4). */\nexport const CENTERED_FACTOR = 0.4;\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/media.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Pure, framework-free helpers for FaceCaptureV2. No React, minimal DOM.\n\n/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.\n * WebM/VP9→VP8 only as the Firefox/older-Chromium fallback. */\nexport const MIME_CANDIDATES = [\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4;codecs=avc1.42E01E\",\n \"video/mp4\",\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n] as const;\n\nexport type CameraErrorKind =\n | \"permission\"\n | \"notfound\"\n | \"inuse\"\n | \"overconstrained\"\n | \"insecure\"\n | \"unsupported\"\n | \"generic\";\n\n/** First supported candidate, or \"\" to let the browser pick its own default. */\nexport function pickMimeType(): string {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: (t: string) => boolean } })\n .MediaRecorder;\n if (!MR || typeof MR.isTypeSupported !== \"function\") return \"\";\n return MIME_CANDIDATES.find((t) => MR.isTypeSupported!(t)) ?? \"\";\n}\n\n/** Default clip container when pickMimeType() === \"\" — NEVER .bin/octet-stream (REVIEW FIX 5).\n * Prefer the first webm in the ladder the browser most likely defaults to. */\nexport const DEFAULT_CLIP_MIME = \"video/webm\";\n\n/** Branch on err.name (never the message). TypeError ⇒ navigator.mediaDevices was undefined\n * (insecure/unsupported context) — surfaced as \"insecure\". */\nexport function mapGetUserMediaError(err: unknown): CameraErrorKind {\n if (err instanceof TypeError) return \"insecure\";\n const name = (err as { name?: string })?.name ?? \"\";\n switch (name) {\n case \"NotAllowedError\":\n case \"PermissionDeniedError\":\n return \"permission\";\n case \"NotFoundError\":\n case \"DevicesNotFoundError\":\n return \"notfound\";\n case \"NotReadableError\":\n case \"TrackStartError\":\n return \"inuse\";\n case \"OverconstrainedError\":\n case \"ConstraintNotSatisfiedError\":\n return \"overconstrained\";\n default:\n return \"generic\";\n }\n}\n\nexport function cameraPreflight(): \"INSECURE_CONTEXT\" | \"UNSUPPORTED\" | \"OK\" {\n const w = globalThis as unknown as { window?: { isSecureContext?: boolean }; navigator?: Navigator };\n if (typeof w.window !== \"undefined\" && w.window.isSecureContext === false)\n return \"INSECURE_CONTEXT\";\n const md = (w.navigator as Navigator | undefined)?.mediaDevices as\n | { getUserMedia?: unknown }\n | undefined;\n if (!md || typeof md.getUserMedia !== \"function\") return \"UNSUPPORTED\";\n return \"OK\";\n}\n\n/** iOS Safari (and any browser) may lack MediaRecorder entirely — detect BEFORE prompting\n * for the camera so we can fall back to the v1 single-photo path (REVIEW FIX 1). */\nexport function isMediaRecorderSupported(): boolean {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: unknown } }).MediaRecorder;\n return typeof MR !== \"undefined\" && typeof (MR as { isTypeSupported?: unknown }).isTypeSupported === \"function\";\n}\n\nexport const MAX_CLIP_BYTES = 8 * 1024 * 1024; // 8 MB hard cap (shared with the /api/liveness/v2 contract)\nexport function isClipTooLarge(blob: Blob): boolean {\n return blob.size > MAX_CLIP_BYTES;\n}\n\nexport function extForMime(mime: string): string {\n const m = (mime || \"\").toLowerCase();\n if (m.startsWith(\"image/jpeg\")) return \"jpg\";\n if (m.startsWith(\"video/mp4\")) return \"mp4\";\n if (m.startsWith(\"video/webm\")) return \"webm\";\n // Never .bin — default to the clip container we actually record (REVIEW FIX 5).\n return \"webm\";\n}\n\n/** Build the exact multipart body /api/liveness/v2 expects: fields `token`, files `clip` + `keyframe`.\n * Caller must NOT set Content-Type — the browser adds the boundary. */\nexport function buildLivenessV2FormData(args: {\n token: string;\n clip: Blob;\n keyframe: Blob;\n ts?: number;\n}): FormData {\n const { token, clip, keyframe } = args;\n const ts = args.ts ?? Date.now();\n const clipType = clip.type || DEFAULT_CLIP_MIME;\n const kfType = keyframe.type || \"image/jpeg\";\n const fd = new FormData();\n fd.append(\"token\", token);\n fd.append(\"clip\", new File([clip], `liveness-${ts}.${extForMime(clipType)}`, { type: clipType }));\n fd.append(\"keyframe\", new File([keyframe], `keyframe-${ts}.${extForMime(kfType)}`, { type: kfType }));\n return fd;\n}\n","// De-hooked port of kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Framework-free class: useRef → private fields,\n// useCallback(start) → record(), stopAndCleanup + the unmount useEffect → stop().\n// Behavior is the v1 hook's, VERBATIM (iOS workarounds included). Source line references\n// (kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts):\n// - constants CLIP_MS / TIMESLICE_MS / STOP_GRACE_MS / VIDEO_BPS ............ L10-13\n// - ClipError(kind, msg?) .................................................. L15-21\n// - guarded double MediaRecorder construction (REVIEW FIX 1) ............... L47-63\n// - single-settle guard + timer clearing ................................... L66-71\n// - finalize: Blob(type = recorder.mimeType || picked || DEFAULT_CLIP_MIME)\n// + post-hoc size-cap check .............................................. L73-82\n// - incremental 8MB cap enforcement on dataavailable (REVIEW FIX 7) ........ L84-100\n// - onstop → finalize, onerror → generic, guarded start(TIMESLICE_MS) ...... L101-109\n// - hard stop at CLIP_MS + iOS stop-grace finalize (REVIEW FIX 3) .......... L111-124\n// - teardown: clear timers, stop recorder, stop ALL tracks (REVIEW FIX 8) .. L128-145\n// V2 additions on top of the verbatim behavior (both zero-impact on clip bytes, both\n// required because a class instance outlives one recording where v1's hook state was\n// remounted fresh): a re-entrancy guard in record(), and clearing stale timers when a\n// new recording starts. See the record() JSDoc.\n// Do NOT edit without a calibration re-validation.\nimport {\n pickMimeType,\n isClipTooLarge,\n MAX_CLIP_BYTES,\n DEFAULT_CLIP_MIME,\n type CameraErrorKind,\n} from \"./media\";\n\nexport const CLIP_MS = 2500; // 2.5s, within the 2.0–3.0s target window\nexport const TIMESLICE_MS = 1000; // periodic dataavailable — iOS reliability workaround\nexport const STOP_GRACE_MS = 1500; // iOS: if onstop never fires, finalize from chunks\n// 2.5 Mbps pairs with the 720p capture tier (capture-session.ts): 1.5 Mbps at\n// 720p over-compresses exactly the texture the FAS-CLIP head needs. ~0.8MB per\n// 2.5s clip — well under the 8MB client cap / 15MB server caps.\nexport const VIDEO_BPS = 2_500_000;\n\nexport type ClipErrorKind = CameraErrorKind | \"cliptoolarge\";\n\nexport class ClipError extends Error {\n kind: ClipErrorKind;\n constructor(kind: ClipErrorKind, msg?: string) {\n super(msg ?? kind);\n this.kind = kind;\n }\n}\n\nexport interface ClipResult {\n blob: Blob;\n /** Container mime the clip was finalized with (recorder.mimeType || picked || DEFAULT_CLIP_MIME). */\n mimeType: string;\n}\n\nexport class ClipRecorder {\n private recorder: MediaRecorder | null = null;\n private stream: MediaStream | null = null; // own field so teardown can stop tracks (REVIEW FIX 8)\n private chunks: Blob[] = [];\n private bytes = 0;\n private hardStopTimer: ReturnType<typeof setTimeout> | null = null;\n private graceTimer: ReturnType<typeof setTimeout> | null = null;\n private settled = false;\n\n private clearTimers(): void {\n if (this.hardStopTimer) clearTimeout(this.hardStopTimer);\n if (this.graceTimer) clearTimeout(this.graceTimer);\n this.hardStopTimer = null;\n this.graceTimer = null;\n }\n\n /** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;\n * rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim\n * (iOS workarounds included).\n *\n * ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a\n * second record() while one is in flight rejects ClipError(\"generic\") instead of\n * corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning\n * component; a class API invites reuse. Zero impact on clip bytes.)\n *\n * `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window\n * elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to\n * STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze\n * the display on the already-captured keyframe the instant recording ends,\n * instead of waiting for the blob. PURE NOTIFICATION — it does not touch\n * timers, chunks, or the finalize path, so it is calibration-neutral (no\n * effect on clip bytes). Never fires on a rejected capture (error /\n * cliptoolarge settle before the hard-stop and clear the timer). */\n record(stream: MediaStream, onStopped?: () => void): Promise<ClipResult> {\n if (this.recorder && !this.settled) {\n return Promise.reject(\n new ClipError(\n \"generic\",\n \"record() called while a recording is in flight — ClipRecorder handles one recording at a time\",\n ),\n );\n }\n this.recorder = null; // so a failed construction below never blocks a retry\n // De-hooking correction (zero impact on clip bytes): v1 got fresh refs per hook\n // mount, so a previous recording's post-settle grace timer (the hard-stop callback\n // arms it AFTER settle cleared timers — v1-verbatim) could never leak into a new\n // one. On a reused instance it would fire mid-flight, settle the fresh state, and\n // clear the new hard-stop timer — so drop stale timers before starting.\n this.clearTimers();\n this.chunks = [];\n this.bytes = 0;\n this.settled = false;\n this.stream = stream;\n const picked = pickMimeType();\n\n return new Promise<ClipResult>((resolve, reject) => {\n // Guarded construction — iOS Safari may lack MediaRecorder entirely (REVIEW FIX 1).\n let recorder: MediaRecorder;\n try {\n recorder = new MediaRecorder(\n stream,\n picked\n ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS }\n : { videoBitsPerSecond: VIDEO_BPS },\n );\n } catch {\n try {\n recorder = new MediaRecorder(stream); // last resort: browser defaults\n } catch {\n reject(new ClipError(\"unsupported\"));\n return;\n }\n }\n this.recorder = recorder;\n\n const settle = (fn: () => void) => {\n if (this.settled) return;\n this.settled = true;\n this.clearTimers();\n fn();\n };\n\n const finalize = () =>\n settle(() => {\n const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;\n const blob = new Blob(this.chunks, { type });\n if (isClipTooLarge(blob)) {\n reject(new ClipError(\"cliptoolarge\"));\n return;\n }\n resolve({ blob, mimeType: type });\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size) {\n this.chunks.push(e.data);\n this.bytes += e.data.size;\n // Enforce the 8MB cap INCREMENTALLY — stop + reject as soon as exceeded (REVIEW FIX 7).\n if (this.bytes > MAX_CLIP_BYTES) {\n settle(() => {\n try {\n if (recorder.state !== \"inactive\") recorder.stop();\n } catch {\n /* noop */\n }\n reject(new ClipError(\"cliptoolarge\"));\n });\n }\n }\n };\n recorder.onstop = finalize;\n recorder.onerror = () => settle(() => reject(new ClipError(\"generic\")));\n\n try {\n recorder.start(TIMESLICE_MS);\n } catch {\n settle(() => reject(new ClipError(\"generic\")));\n return;\n }\n\n // Hard stop at CLIP_MS; gate on state, not on frame count.\n this.hardStopTimer = setTimeout(() => {\n // Recording window elapsed — the clip is DONE. Notify BEFORE finalize\n // (which may lag on iOS) so the host can freeze on the keyframe now.\n // Guarded by `settled`: an error/cliptoolarge before the hard-stop has\n // already cleared this timer, so this only runs for a real stop.\n if (!this.settled) onStopped?.();\n if (recorder.state !== \"inactive\") {\n try {\n recorder.stop();\n } catch {\n finalize();\n }\n // iOS safety-net: onstop may never fire — finalize from chunks (REVIEW FIX 3).\n this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);\n } else {\n finalize();\n }\n }, CLIP_MS);\n });\n }\n\n /** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount\n * effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.\n *\n * MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in\n * flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()\n * fires onstop → finalize from whatever chunks arrived so far), or — because this\n * method clears the hard-stop/grace timers — never settle it at all if onstop never\n * fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution\n * arriving after stop() as a full CLIP_MS clip, and must not await a record()\n * promise past stop() without their own timeout. (Task 4's CaptureSession owns\n * sequencing on top of this contract.) */\n stop(stream?: MediaStream | null): void {\n this.clearTimers();\n const rec = this.recorder;\n if (rec && rec.state !== \"inactive\") {\n try {\n rec.stop();\n } catch {\n /* noop */\n }\n }\n this.recorder = null;\n const s = stream ?? this.stream;\n s?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n }\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/keyframe.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Grab ONE mirrored frontal keyframe from the live <video> into a JPEG Blob (a file part,\n// not a dataURL). Mirror matches the selfie preview (front camera), same as FaceCapture v1.\nexport function captureMirroredKeyframe(\n video: HTMLVideoElement,\n canvas: HTMLCanvasElement,\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const w = video.videoWidth;\n const h = video.videoHeight;\n if (!w || !h) {\n reject(new Error(\"video-not-ready\"));\n return;\n }\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"no-2d-context\"));\n return;\n }\n canvas.width = w;\n canvas.height = h;\n ctx.scale(-1, 1);\n ctx.drawImage(video, -w, 0);\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(\"empty-keyframe\"))),\n \"image/jpeg\",\n quality,\n );\n });\n}\n","// Device profiles (Task 9) — LOW/MID/HIGH from a boot probe, refined by the\n// first measured detect times. Profiles adapt DETECTION cost only (cadence,\n// downscale input width, animation richness): clip constraints are NOT here —\n// the 720p/2.5Mbps floor is global (locked decision 1) and lives in the v1\n// constraint builder both engines share.\n\nexport type DeviceClass = \"LOW\" | \"MID\" | \"HIGH\";\n\nexport interface DeviceProfile {\n /** Detection cadence — the scheduler's pace. */\n cadenceHz: number;\n /** Downscaled snapshot width handed to the detector. */\n inputWidth: number;\n /** Chrome hint: 'reduced' tones down ticks/breathe on LOW even without\n * prefers-reduced-motion. */\n animations: \"full\" | \"reduced\";\n}\n\nexport const DEVICE_PROFILES: Readonly<Record<DeviceClass, Readonly<DeviceProfile>>> =\n Object.freeze({\n LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: \"reduced\" as const }),\n MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: \"full\" as const }),\n HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: \"full\" as const }),\n });\n\nexport interface DeviceProbe {\n cores: number;\n /** null where the UA hides it — iOS Safari NEVER exposes deviceMemory\n * (field lesson: a 2GB default classified every iPhone LOW). Unknown is\n * treated as NEUTRAL (4GB): never demotes to LOW on its own, never\n * promotes to HIGH; the dynamic profiler corrects truly slow devices. */\n memGB: number | null;\n /** WebAssembly SIMD available (informs wasm-tier expectations/telemetry). */\n simd: boolean;\n}\n\n/** Canonical WASM SIMD feature-test module (validates only where SIMD is\n * supported) — the standard wasm-feature-detect bytes. */\nconst SIMD_TEST_BYTES = new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253,\n 15, 253, 98, 11,\n]);\n\nexport function probeDevice(): DeviceProbe {\n const nav = typeof navigator === \"undefined\" ? undefined : navigator;\n let simd = false;\n try {\n simd = typeof WebAssembly !== \"undefined\" && WebAssembly.validate(SIMD_TEST_BYTES);\n } catch {\n simd = false;\n }\n return {\n cores: nav?.hardwareConcurrency ?? 2,\n memGB: (nav as { deviceMemory?: number } | undefined)?.deviceMemory ?? null,\n simd,\n };\n}\n\n/** Static class: LOW (<4 cores or <3GB), HIGH (≥8 cores AND ≥6GB), else MID.\n * Unknown memory counts as a neutral 4GB (see DeviceProbe.memGB). */\nexport function classifyDevice(probe: DeviceProbe): DeviceClass {\n const memGB = probe.memGB ?? 4;\n if (probe.cores < 4 || memGB < 3) return \"LOW\";\n if (probe.cores >= 8 && memGB >= 6) return \"HIGH\";\n return \"MID\";\n}\n\nconst ORDER: DeviceClass[] = [\"LOW\", \"MID\", \"HIGH\"];\n\n/** Dynamic refinement: after the FIRST 10 measured detect ticks, a mean over\n * 70ms demotes straight to LOW; under 25ms promotes ONE class — at most one\n * adjustment ever (no oscillation). */\nexport class DeviceProfiler {\n private current: DeviceClass;\n private readonly samples: number[] = [];\n private adjusted = false;\n\n constructor(initial: DeviceClass) {\n this.current = initial;\n }\n\n get deviceClass(): DeviceClass {\n return this.current;\n }\n\n get profile(): DeviceProfile {\n return DEVICE_PROFILES[this.current];\n }\n\n record(detectMs: number): DeviceClass {\n if (this.adjusted || this.samples.length >= 10) return this.current;\n this.samples.push(detectMs);\n if (this.samples.length < 10) return this.current;\n this.adjusted = true;\n const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;\n if (mean > 70) {\n this.current = \"LOW\";\n } else if (mean < 25) {\n const index = ORDER.indexOf(this.current);\n this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;\n }\n return this.current;\n }\n}\n","// Detect scheduler (Task 9) — paces the detection pass at the profile's\n// cadence, preferring requestVideoFrameCallback (runs only when a REAL camera\n// frame arrived) with a plain interval fallback. A tick whose predecessor is\n// still in flight is SKIPPED — never queued (no backlog on a slow device) —\n// and counted as a degrade for telemetry.\n\nexport interface DetectSchedulerOptions {\n /** Ticks per second (profile cadenceHz). */\n cadenceHz: number;\n /** One detection pass — the scheduler awaits it and measures wall time. */\n run: () => Promise<void>;\n /** When provided AND it exposes requestVideoFrameCallback, ticks ride real\n * camera frames (throttled to the cadence) instead of a timer. */\n video?: HTMLVideoElement;\n /** Injectable clock (tests) — defaults to performance.now. */\n now?: () => number;\n}\n\ninterface VideoFrameCallbackTarget {\n requestVideoFrameCallback?: (callback: () => void) => number;\n cancelVideoFrameCallback?: (id: number) => void;\n}\n\n/** Rolling window for meanDetectMs. */\nconst STATS_WINDOW = 20;\n\nexport class DetectScheduler {\n private readonly options: DetectSchedulerOptions;\n private readonly periodMs: number;\n private timer: ReturnType<typeof setInterval> | null = null;\n private frameCallbackId: number | null = null;\n private running = false;\n private busy = false;\n private lastRunAt = Number.NEGATIVE_INFINITY;\n private degradeCount = 0;\n private readonly durations: number[] = [];\n\n constructor(options: DetectSchedulerOptions) {\n this.options = options;\n this.periodMs = 1000 / options.cadenceHz;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n const video = this.options.video as VideoFrameCallbackTarget | undefined;\n if (typeof video?.requestVideoFrameCallback === \"function\") {\n const loop = () => {\n if (!this.running) return;\n this.frameCallbackId = video.requestVideoFrameCallback?.(() => {\n this.frameCallbackId = null;\n // Throttle: camera frames arrive faster than the cadence.\n if (this.now() - this.lastRunAt >= this.periodMs) this.tick();\n loop();\n }) as number;\n };\n loop();\n return;\n }\n this.timer = setInterval(() => this.tick(), this.periodMs);\n }\n\n stop(): void {\n this.running = false;\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.frameCallbackId !== null) {\n (this.options.video as VideoFrameCallbackTarget | undefined)?.cancelVideoFrameCallback?.(\n this.frameCallbackId,\n );\n this.frameCallbackId = null;\n }\n }\n\n stats(): { degradeCount: number; meanDetectMs: number } {\n const meanDetectMs =\n this.durations.length === 0\n ? 0\n : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;\n return { degradeCount: this.degradeCount, meanDetectMs };\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n\n private tick(): void {\n if (!this.running) return;\n if (this.busy) {\n // Skip-when-busy: no queue growth on slow devices; telemetry counts it.\n this.degradeCount += 1;\n return;\n }\n this.busy = true;\n this.lastRunAt = this.now();\n const startedAt = this.now();\n this.options\n .run()\n .catch(() => undefined) // a failed pass must never kill the loop\n .finally(() => {\n this.busy = false;\n this.durations.push(this.now() - startedAt);\n if (this.durations.length > STATS_WINDOW) this.durations.shift();\n });\n }\n}\n","// FaceGateV3 (Task 8) — the v3 gate: scale-invariant, landmark-aware,\n// continuous-quality, gentle-drain. PARALLEL to the calibration-pinned v1\n// FaceGate (face-gate.ts) — nothing here feeds or alters v1's math.\n//\n// Design deltas vs v1 (the two field complaints this kills):\n// - the gate point is the EYE MIDPOINT when the tier provides eyes (humans\n// center their EYES, detectors center their BBOX — v1's bbox-center gate\n// read a centered face as \"high\"); box-only tiers get a documented\n// 0.12×height upward shift instead;\n// - progress is a CONTINUOUS integrator (rise 0.9/s on good quality, fall\n// 0.25/s on bad) instead of v1's ±counters — a wobble dips the progress\n// slightly instead of resetting the attempt.\n//\n// q AGGREGATION = MIN over factors (operator ruling 2026-07-12, replacing\n// the original 7-factor PRODUCT). Field finding: with a product, seven\n// factors each at a decent 0.85 gave q≈0.32 — progress DRAINED while every\n// factor sat above its guidance threshold, so the chrome said \"hold still\"\n// and the only discoverable escape was leaning unnaturally close (size,\n// centering falloff (∝IOD) and crop sharpness all improve together with\n// proximity). min() makes q the same quantity guidance reasons about — the\n// worst factor — so \"no complaint\" ⇔ \"progress rises\" by construction, one\n// genuinely bad factor still blocks (non-compensatory), and many mediocre\n// factors (the low-end-device reality: noisy sensor, dim room, wide FOV)\n// are no longer multiplied into failure.\n//\n// 100% deterministic: the clock is a tick INPUT (timestampMs); nothing here\n// reads Date.now or performance.now.\nimport type { FaceObservation } from \"./detector\";\nimport { EXPOSURE_BAND } from \"./frame-quality\";\n\nexport interface V3GateThresholds {\n /** q at/above which progress rises; below it progress falls. */\n Q_GOOD: number;\n /** Integrator slopes, per second. */\n RISE_PER_S: number;\n FALL_PER_S: number;\n /** Centering falloff radius = this × IOD (scale-invariant). The plan's\n * formula is 0.45 × IOD × 3 — the 0.45 echoes v1's CIRCLE_RADIUS_FACTOR\n * heritage — folded here to 1.35 × IOD. */\n CENTER_FALLOFF_IOD_MULTIPLE: number;\n /** Box-only tiers: gate point = bbox center shifted UP by this × height\n * (the documented bbox-vs-eyes offset heuristic). */\n BOX_EYE_OFFSET_FACTOR: number;\n /** Box-only IOD proxy = this × box width. */\n IOD_BOX_PROXY_FACTOR: number;\n /** IOD / frame short side: ideal band + hard limits. */\n SIZE_IDEAL_MIN: number;\n SIZE_IDEAL_MAX: number;\n SIZE_HARD_MIN: number;\n SIZE_HARD_MAX: number;\n /** Eye-line roll (deg) that zeroes the pose factor. */\n ROLL_MAX_DEG: number;\n /** Center velocity that zeroes the motion factor, in IOD-per-second. */\n MOTION_VELOCITY_IOD_PER_S: number;\n /** Velocity-EMA time constant (seconds) — the EMA weight is derived per\n * tick as 1−exp(−dt/τ), so the smoothing HORIZON is cadence-invariant:\n * a LOW device detecting at 5 Hz gets the same effective smoothing as a\n * HIGH device at 10 Hz (a fixed per-sample alpha under-smoothed exactly\n * the jittery low-cadence ticks that needed it most). */\n MOTION_TAU_S: number;\n /** Velocities at/below this (IOD/s) count as stillness — absorbs detector\n * box jitter (largest on LOW's 128px input) before it reaches the EMA. */\n MOTION_DEADBAND_IOD_PER_S: number;\n /** ready = p ≥ 1 AND no bad tick (q < Q_GOOD) left in this window after\n * TRIMMING: with ≥3 samples the single worst is dropped, so one flaky tick\n * (5 Hz LOW cadence = only 2–3 samples per window) cannot veto an\n * otherwise-ready user, while a SECOND bad tick (a real sustained wobble)\n * still blocks. The readiness bar is Q_GOOD itself — the level the\n * integrator rises on — so any input that fills the ring also fires it. */\n READY_WINDOW_MS: number;\n /** Per-factor guidance trigger levels (lowest failing factor speaks). */\n GUIDE_SIZE: number;\n GUIDE_CENTERING: number;\n GUIDE_POSE: number;\n GUIDE_EXPOSURE: number;\n GUIDE_SHARPNESS: number;\n GUIDE_MOTION: number;\n}\n\n/** Defaults — retuned 2026-07-12 (operator ruling superseding the 2026-07\n * freeze; the capture Task-15 refit set must be split at this boundary):\n * Q_GOOD 0.55→0.6 so it aligns with the 0.6 guidance thresholds under\n * min-q (\"no complaint\" ⇔ \"progress rises\"); SIZE_IDEAL_MIN 0.16→0.12 —\n * wide-FOV front cameras (common low-end) put an arm's-length face below\n * 0.16, silently forcing lean-in; the 720p clip floor keeps a 0.12-IOD\n * face fully resolvable server-side. */\nexport const V3_GATE_DEFAULTS: Readonly<V3GateThresholds> = Object.freeze({\n Q_GOOD: 0.6,\n RISE_PER_S: 0.9,\n FALL_PER_S: 0.25,\n CENTER_FALLOFF_IOD_MULTIPLE: 1.35,\n BOX_EYE_OFFSET_FACTOR: 0.12,\n IOD_BOX_PROXY_FACTOR: 0.42,\n SIZE_IDEAL_MIN: 0.12,\n SIZE_IDEAL_MAX: 0.3,\n SIZE_HARD_MIN: 0.08,\n SIZE_HARD_MAX: 0.45,\n ROLL_MAX_DEG: 25,\n MOTION_VELOCITY_IOD_PER_S: 0.5,\n MOTION_TAU_S: 0.4,\n MOTION_DEADBAND_IOD_PER_S: 0.1,\n READY_WINDOW_MS: 500,\n // (READY_MEAN_Q, the former 0.75 window MEAN, is gone — 2026-10-17 field\n // bug: a steady q anywhere in [Q_GOOD, 0.75) saturated p at 1, passed every\n // guide (\"hold still\") and could never reach the mean, so the ring sat full\n // and green with nothing recording. Readiness now checks the window against\n // Q_GOOD, which keeps the one-flaky-tick forgiveness and the second-bad-tick\n // block without a dead band above the rise threshold.)\n GUIDE_SIZE: 0.6,\n GUIDE_CENTERING: 0.6,\n GUIDE_POSE: 0.6,\n GUIDE_EXPOSURE: 0.6,\n GUIDE_SHARPNESS: 0.35,\n GUIDE_MOTION: 0.5,\n});\n\nexport interface V3GateQuality {\n /** From frame-quality.sharpness on the face crop. */\n sharpness: number;\n /** From frame-quality.exposure on the face crop. */\n exposure: number;\n /** Mean crop luma — picks more_light vs too_bright guidance. */\n meanLuma: number;\n}\n\nexport interface V3GateTickInput {\n timestampMs: number;\n observation: FaceObservation | null;\n quality: V3GateQuality;\n frameWidth: number;\n frameHeight: number;\n}\n\nexport type V3GateFactor =\n | \"presence\"\n | \"centering\"\n | \"size\"\n | \"pose\"\n | \"sharpness\"\n | \"exposure\"\n | \"motion\";\n\n/** Per-tick output — the telemetry + chrome contract. */\nexport interface V3GateTick {\n at: number;\n /** Instantaneous quality 0..1 (MIN over the factors — the worst factor). */\n q: number;\n /** Integrated progress 0..1. */\n p: number;\n factors: Record<V3GateFactor, number>;\n /** fcv3.* message key for the lowest failing factor (host translates). */\n guidanceKey: string;\n /** Fire signal: p ≥ 1 AND no second bad tick (q < Q_GOOD) in READY_WINDOW_MS. */\n ready: boolean;\n /** The face on THIS tick is ACCEPTED by the gate — present and every factor\n * (size, centering, pose, sharpness, exposure, motion) good enough that the\n * integrator RISES (q ≥ Q_GOOD). The engine's \"first accepted face\" mark. */\n accepted: boolean;\n}\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\nexport class FaceGateV3 {\n private readonly t: V3GateThresholds;\n private p = 0;\n private lastTickAt: number | null = null;\n private lastCenter: { x: number; y: number; at: number } | null = null;\n private velocityEma = 0;\n private qWindow: Array<{ at: number; q: number }> = [];\n\n constructor(overrides: Partial<V3GateThresholds> = {}) {\n this.t = { ...V3_GATE_DEFAULTS, ...overrides };\n }\n\n reset(): void {\n this.p = 0;\n this.lastTickAt = null;\n this.lastCenter = null;\n this.velocityEma = 0;\n this.qWindow = [];\n this.lastSizeDirection = \"ideal\";\n }\n\n tick(input: V3GateTickInput): V3GateTick {\n const { observation, quality, timestampMs } = input;\n const dtSeconds =\n this.lastTickAt === null\n ? 0\n : Math.max(0, (timestampMs - this.lastTickAt) / 1000);\n this.lastTickAt = timestampMs;\n\n const factors: Record<V3GateFactor, number> = {\n presence: 0,\n centering: 0,\n size: 0,\n pose: 0,\n sharpness: clamp01(quality.sharpness),\n exposure: clamp01(quality.exposure),\n motion: 1,\n };\n\n if (observation !== null) {\n factors.presence = 1;\n const geometry = this.geometryOf(observation, input);\n factors.centering = geometry.centering;\n factors.size = geometry.size;\n factors.pose = geometry.pose;\n factors.motion = this.motionOf(\n geometry.center,\n geometry.iod,\n timestampMs,\n );\n } else {\n // No face: the motion history must not survive to the next sighting\n // (a re-acquired face \"jumping\" from its old position is not motion,\n // and a stale pre-loss velocity EMA must not penalize re-acquisition).\n this.lastCenter = null;\n this.velocityEma = 0;\n }\n\n // Worst factor IS the quality (see header) — presence 0 zeroes it exactly\n // as the old product did; the compensatory many-mediocre penalty is gone.\n const q = Math.min(\n factors.presence,\n factors.centering,\n factors.size,\n factors.pose,\n factors.sharpness,\n factors.exposure,\n factors.motion,\n );\n\n // Integrator: gentle drain — bad ticks pull p down at FALL×(1−q), never\n // reset it (the v1 counter-reset feel this replaces).\n this.p = clamp01(\n this.p +\n (q >= this.t.Q_GOOD\n ? this.t.RISE_PER_S * q\n : -this.t.FALL_PER_S * (1 - q)) *\n dtSeconds,\n );\n\n // Sustained-quality window (prevents luck-firing through a wobble).\n // TRIMMED: with ≥3 samples the single worst is dropped — at LOW's 5 Hz\n // cadence a window holds 2–3 ticks, and one jittery detection must not\n // veto a user who is otherwise steadily ready. Every remaining sample must\n // be a GOOD tick (q ≥ Q_GOOD, the integrator's own rise level): a second\n // bad tick blocks, and — by construction — any steady input that fills\n // the ring is ready the moment the window is clean (no dead band where\n // p = 1, guidance says hold_still and nothing fires; 2026-10-17).\n this.qWindow.push({ at: timestampMs, q });\n this.qWindow = this.qWindow.filter(\n (entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS,\n );\n let windowSamples = this.qWindow.map((entry) => entry.q);\n if (windowSamples.length >= 3) {\n const worst = Math.min(...windowSamples);\n const worstIndex = windowSamples.indexOf(worst);\n windowSamples = windowSamples.filter((_, index) => index !== worstIndex);\n }\n const ready =\n this.p >= 1 && windowSamples.every((sample) => sample >= this.t.Q_GOOD);\n\n return {\n at: timestampMs,\n q,\n p: this.p,\n factors,\n guidanceKey: this.guidanceOf(factors, quality, q),\n ready,\n accepted: q >= this.t.Q_GOOD,\n };\n }\n\n private geometryOf(\n observation: FaceObservation,\n input: V3GateTickInput,\n ): {\n center: { x: number; y: number };\n iod: number;\n centering: number;\n size: number;\n pose: number;\n } {\n const { box, eyes } = observation;\n const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };\n const shortSide = Math.min(input.frameWidth, input.frameHeight);\n\n // Gate point: eye midpoint, or the bbox center shifted UP so box-only\n // tiers behave like eye tiers (BOX_EYE_OFFSET heuristic).\n const center =\n eyes !== undefined\n ? {\n x: (eyes.left.x + eyes.right.x) / 2,\n y: (eyes.left.y + eyes.right.y) / 2,\n }\n : {\n x: box.x + box.width / 2,\n y:\n box.y +\n box.height / 2 -\n this.t.BOX_EYE_OFFSET_FACTOR * box.height,\n };\n const iod =\n eyes !== undefined\n ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y)\n : this.t.IOD_BOX_PROXY_FACTOR * box.width;\n\n // Smooth, SCALE-INVARIANT centering falloff: distance measured in IODs.\n const distance = Math.hypot(\n center.x - frameCenter.x,\n center.y - frameCenter.y,\n );\n const centering =\n iod <= 0\n ? 0\n : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));\n\n // Size factor from IOD relative to the frame short side.\n const ratio = shortSide > 0 ? iod / shortSide : 0;\n this.lastSizeDirection =\n ratio < this.t.SIZE_IDEAL_MIN\n ? \"far\"\n : ratio > this.t.SIZE_IDEAL_MAX\n ? \"close\"\n : \"ideal\";\n let size: number;\n if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {\n size = 0;\n } else if (ratio < this.t.SIZE_IDEAL_MIN) {\n size =\n (ratio - this.t.SIZE_HARD_MIN) /\n (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);\n } else if (ratio > this.t.SIZE_IDEAL_MAX) {\n size =\n (this.t.SIZE_HARD_MAX - ratio) /\n (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);\n } else {\n size = 1;\n }\n\n // Pose from the eye-line roll; box-only tiers stay neutral (no signal).\n let pose = 1;\n if (eyes !== undefined) {\n const rollDeg =\n (Math.abs(\n Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x),\n ) *\n 180) /\n Math.PI;\n pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);\n }\n\n return { center, iod, centering, size, pose };\n }\n\n private motionOf(\n center: { x: number; y: number },\n iod: number,\n at: number,\n ): number {\n const previous = this.lastCenter;\n this.lastCenter = { ...center, at };\n if (previous === null || iod <= 0) return 1;\n const dtSeconds = (at - previous.at) / 1000;\n if (dtSeconds <= 0) return 1;\n let velocityIodPerS =\n Math.hypot(center.x - previous.x, center.y - previous.y) /\n iod /\n dtSeconds;\n // Deadband: sub-jitter velocities are stillness. Detector boxes quantize\n // hardest on LOW's 128px input, where a ±1px wobble at 5 Hz reads as\n // ~0.25 IOD/s — half the zeroing velocity — despite a rock-steady user.\n if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)\n velocityIodPerS = 0;\n // Time-constant EMA: alpha derived from dt so the smoothing horizon is\n // the same at 5 Hz and 10 Hz (see MOTION_TAU_S).\n const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);\n this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;\n return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);\n }\n\n /** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):\n * presence → size → centering → pose → exposure → sharpness → hold.\n *\n * HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears\n * its guide threshold but q (= min factor) is still below Q_GOOD — i.e.\n * progress is DRAINING — \"hold still\" would be a lie (\"Perfect\" while\n * nothing advances; the field symptom was users discovering by accident\n * that only leaning in fires the gate). In that state the WORST factor\n * speaks even though it passed its guide level, so the user always hears\n * the change that actually unblocks recording. */\n private guidanceOf(\n factors: Record<V3GateFactor, number>,\n quality: V3GateQuality,\n q: number,\n ): string {\n if (factors.presence <= 0) return \"fcv3.no_face\";\n if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();\n if (factors.centering < this.t.GUIDE_CENTERING) return \"fcv3.center_face\";\n if (factors.pose < this.t.GUIDE_POSE) return \"fcv3.straighten\";\n if (factors.exposure < this.t.GUIDE_EXPOSURE)\n return this.exposureGuidance(quality);\n if (factors.sharpness < this.t.GUIDE_SHARPNESS) return \"fcv3.steady_camera\";\n if (factors.motion < this.t.GUIDE_MOTION) return \"fcv3.hold_still\";\n if (q < this.t.Q_GOOD) {\n // All guides pass but progress drains — coach the worst factor anyway.\n const coachable: Array<[V3GateFactor, string]> = [\n [\"size\", this.sizeGuidance()],\n [\"centering\", \"fcv3.center_face\"],\n [\"pose\", \"fcv3.straighten\"],\n [\"exposure\", this.exposureGuidance(quality)],\n [\"sharpness\", \"fcv3.steady_camera\"],\n [\"motion\", \"fcv3.hold_still\"],\n ];\n let worst = coachable[0] as [V3GateFactor, string];\n for (const entry of coachable) {\n if (factors[entry[0]] < factors[worst[0]]) worst = entry;\n }\n return worst[1];\n }\n return \"fcv3.hold_still\";\n }\n\n /** Direction from the size band set THIS tick (never inverted at the hard\n * limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */\n private sizeGuidance(): string {\n return this.lastSizeDirection === \"far\"\n ? \"fcv3.come_closer\"\n : \"fcv3.move_back\";\n }\n\n /** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */\n private exposureGuidance(quality: V3GateQuality): string {\n const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;\n return quality.meanLuma < bandMid ? \"fcv3.more_light\" : \"fcv3.too_bright\";\n }\n\n /** Which side of the ideal band the last size measurement fell on. */\n private lastSizeDirection: \"far\" | \"close\" | \"ideal\" = \"ideal\";\n}\n","// CaptureSessionV3 (Task 10) — the v3 engine behind the v1 event surface\n// (`statechange | guidance | checks | artifacts | error`), plus ONE v3-only\n// chrome event (`frozen`, fired at recording-stop so the host can freeze the\n// display on the keyframe before the clip finalizes), so hosts bind it with\n// minimal changes. PARALLEL module: it REUSES v1's building blocks AS\n// IMPORTS — ClipRecorder (the 720p/2.5Mbps clip floor lives in ONE place),\n// captureMirroredKeyframe, buildCaptureConstraints, the camera error taxonomy\n// — and touches no v1 file.\n//\n// v3 deltas: detector LADDER (native → blaze; the face-api floor was dropped\n// 2026-07-09) on an adaptive scheduler with device profiles; FaceGateV3\n// (eye-midpoint, continuous\n// integrator); keyframe BEST-OF-N (sharpest of up to 4 candidates in the\n// first 600ms of the capture window); `checks` carries a v3 payload\n// discriminated on `engine: 'v3'` (no v1 counters).\n//\n// Supersession: retry()/switchCamera()/destroy() bump the attempt token —\n// in-flight async continuations from an old attempt observe the bump and\n// stop (the v1 pattern, ported; see capture-session.ts header).\nimport { buildCaptureConstraints, detectIsMobile } from \"../capture-constraints\";\nimport { ClipRecorder, type ClipResult } from \"../clip-recorder\";\nimport { captureMirroredKeyframe } from \"../keyframe\";\nimport { cameraPreflight, isClipTooLarge, mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState, CaptureTiming } from \"../types\";\nimport {\n createDetector as createLadderDetector,\n type Detector,\n DetectorLadderError,\n intrinsicSize,\n} from \"./detector\";\nimport { WorkerDetectorProxy, type WorkerLike, workerOffloadSupported } from \"./detect-worker\";\nimport {\n classifyDevice,\n type DeviceClass,\n DeviceProfiler,\n probeDevice,\n} from \"./device-profile\";\nimport { DetectScheduler } from \"./detect-scheduler\";\nimport {\n FaceGateV3,\n type V3GateFactor,\n type V3GateQuality,\n type V3GateThresholds,\n} from \"./face-gate-v3\";\nimport { exposure, meanLuma, sharpness } from \"./frame-quality\";\n\n/** Best-of-N keyframe window: up to 4 candidates over the first 600ms. */\nexport const KEYFRAME_CANDIDATES = 4;\nexport const KEYFRAME_WINDOW_MS = 600;\n\nexport interface V3ChecksPayload {\n engine: \"v3\";\n /** Gate integrator 0..1 — the ring drives off this directly. */\n progress: number;\n /** Instantaneous quality 0..1. */\n q: number;\n factors: Record<V3GateFactor, number>;\n /** Attempt ordinal (bumps on retry/switchCamera). */\n attempt: number;\n}\n\nexport interface CaptureSessionV3Events {\n statechange: { state: CaptureState };\n checks: V3ChecksPayload;\n /** fcv3.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n artifacts: CaptureArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n /** v3-only, CHROME-only (no data flows here): fires the instant the clip\n * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up\n * to STOP_GRACE_MS). Carries the already-captured keyframe's JPEG data URL so\n * the host can freeze the display on the still immediately instead of leaving\n * the live feed running while the clip flushes. Clip mode only (photo mode\n * goes straight to `artifacts`). A host that ignores it is unaffected. */\n frozen: { previewDataUrl: string };\n}\n\nexport type V3TelemetryEvent =\n | { type: \"detector\"; tier: Detector[\"tier\"]; fallbackReason?: string }\n | { type: \"profile\"; staticClass: DeviceClass; activeClass: DeviceClass; simd: boolean }\n | { type: \"fired\"; timeToGateMs: number; degradeCount: number; meanDetectMs: number }\n | { type: \"error\"; kind: CaptureErrorKind; fallbackReason?: string };\n\ninterface KeyframeCandidate {\n blob: Blob;\n previewDataUrl: string;\n sharpness: number;\n}\n\n/** Challenge-clip artifact for the Phase 3 escalation path. */\nexport interface EscalationClipArtifact {\n clip: Blob;\n clipMimeType: string;\n}\n\n/** INERT Phase 3 seam (docs/superpowers/specs/2026-07-07-active-liveness-\n * escalation-spec.md): when the server settles a liveness verdict in the\n * REVIEW band it may mint ONE gesture challenge; the host then asks the\n * engine for a challenge clip through this hook. Typed and documented NOW so\n * capture-v3+ starts from a design — NEVER invoked anywhere in the current\n * flow (pinned by a test). */\nexport interface EscalationHook {\n onBorderline(challenge: \"blink\" | \"turn\"): Promise<EscalationClipArtifact>;\n}\n\nexport interface CaptureSessionV3Options {\n /** Host-owned <video playsInline muted> — same iOS contract as v1. */\n video: HTMLVideoElement;\n /** v3 assets base (tasks-vision wasm + tflite); default /models-v3. */\n v3AssetBaseUrl?: string;\n mode?: \"clip\" | \"photo\";\n /** FaceGateV3 threshold overrides (Phase 2 tuning). */\n thresholds?: Partial<V3GateThresholds>;\n telemetry?: (event: V3TelemetryEvent) => void;\n facingMode?: \"user\" | \"environment\";\n /** Static class override (tests / host pinning); default = boot probe. */\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (detector ladder) */\n createDetector?: () => Promise<Detector>;\n /** (fresh ClipRecorder per attempt) */\n createRecorder?: () => Pick<ClipRecorder, \"record\" | \"stop\">;\n /** (navigator.mediaDevices.getUserMedia) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (mirrored canvas keyframe + downscaled Laplacian sharpness) */\n captureKeyframe?: (video: HTMLVideoElement) => Promise<KeyframeCandidate>;\n /** (downscaled face-crop sharpness/exposure via canvas) */\n measureQuality?: (\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ) => V3GateQuality;\n /** (reused canvas at profile.inputWidth; falls back to the raw video where\n * canvas is unavailable) */\n makeSnapshot?: (video: HTMLVideoElement, targetWidth: number) => CanvasImageSource;\n /** Worker offload opt-in (Task 9): when provided AND the platform supports\n * it (OffscreenCanvas + createImageBitmap + Worker), detection runs\n * worker-side through WorkerDetectorProxy. Hosts own Worker construction\n * (bundler-specific `new Worker(new URL(...))`). */\n createWorker?: () => WorkerLike;\n /** INERT (Phase 3 escalation seam — see EscalationHook). Accepted and\n * retained, never called in Phases 1–2. */\n escalation?: EscalationHook;\n /** (performance.now) */\n now?: () => number;\n}\n\ntype Handler<K extends keyof CaptureSessionV3Events> = (\n payload: CaptureSessionV3Events[K],\n) => void;\n\nconst NEUTRAL_QUALITY: V3GateQuality = { sharpness: 1, exposure: 1, meanLuma: 128 };\n\n/** Per-start options (the public handle's `start({ facing })`). */\nexport interface CaptureSessionV3StartOptions {\n /** Camera for this attempt AND later retries; absent → keep the current one. */\n facingMode?: \"user\" | \"environment\";\n}\n\nexport class CaptureSessionV3 {\n private readonly options: CaptureSessionV3Options;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stateValue: CaptureState = \"idle\";\n private attempt = 0;\n private facing: \"user\" | \"environment\";\n private stream: MediaStream | null = null;\n private detector: Detector | null = null;\n private scheduler: DetectScheduler | null = null;\n private gate: FaceGateV3 | null = null;\n private profiler: DeviceProfiler | null = null;\n private lastGuidanceKey: string | null = null;\n private positioningStartedAt = 0;\n // Face-capture timing marks of the CURRENT attempt (engine clock; reset per run).\n private cameraRequestedAt: number | null = null;\n private cameraReadyAt: number | null = null;\n private faceAcquiredAt: number | null = null;\n private captureCompleteAt: number | null = null;\n private fired = false;\n private carriedDegrade = 0;\n private carriedMeans: number[] = [];\n\n constructor(options: CaptureSessionV3Options) {\n this.options = options;\n this.facing = options.facingMode ?? \"user\";\n }\n\n get state(): CaptureState {\n return this.stateValue;\n }\n\n on<K extends keyof CaptureSessionV3Events>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionV3Events>(\n event: K,\n payload: CaptureSessionV3Events[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(options: CaptureSessionV3StartOptions = {}): Promise<void> {\n if (options.facingMode !== undefined) this.facing = options.facingMode;\n this.attempt += 1;\n await this.run(this.attempt);\n }\n\n /** The camera the current/next attempt requests (start option, switchCamera toggles). */\n get facingMode(): \"user\" | \"environment\" {\n return this.facing;\n }\n\n /** Full reset + camera restart — the documented recovery path (v1 parity). */\n retry(): void {\n this.teardownAttempt();\n void this.start();\n }\n\n switchCamera(): void {\n this.facing = this.facing === \"user\" ? \"environment\" : \"user\";\n this.teardownAttempt();\n void this.start();\n }\n\n destroy(): void {\n this.attempt += 1; // supersede in-flight continuations\n this.teardownAttempt();\n this.detector?.destroy();\n this.detector = null;\n this.options.video.srcObject = null;\n }\n\n // ── attempt lifecycle ──────────────────────────────────────────────────────\n\n private async run(attempt: number): Promise<void> {\n const { options } = this;\n this.fired = false;\n this.lastGuidanceKey = null;\n this.carriedDegrade = 0;\n this.carriedMeans = [];\n this.cameraRequestedAt = null;\n this.cameraReadyAt = null;\n this.faceAcquiredAt = null;\n this.captureCompleteAt = null;\n this.setState(\"preflight\");\n const preflight = cameraPreflight();\n if (preflight !== \"OK\") {\n this.fail(preflight === \"INSECURE_CONTEXT\" ? \"insecure\" : \"unsupported\");\n return;\n }\n\n this.setState(\"acquiring\");\n const getUserMedia =\n options.getUserMedia ??\n ((constraints: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia(constraints));\n let stream: MediaStream;\n this.cameraRequestedAt = this.now();\n try {\n // The 720p/2.5Mbps floor: v1's constraint builder, imported — never forked.\n stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));\n } catch (err) {\n if (attempt !== this.attempt) return;\n this.fail(mapGetUserMediaError(err));\n return;\n }\n if (attempt !== this.attempt) {\n for (const track of stream.getTracks()) track.stop();\n return;\n }\n this.stream = stream;\n options.video.srcObject = stream;\n await options.video.play().catch(() => undefined);\n // play() awaited — a retry/destroy may have superseded this attempt while\n // it was suspended; continuing would overwrite the LIVE attempt's\n // profiler/gate/scheduler with stale ones (review S2-2).\n if (attempt !== this.attempt) return;\n // Camera ready: stream attached + preview playing (the detector may still\n // be loading — that wait is part of the capture phase, not the camera's).\n this.cameraReadyAt = this.now();\n\n if (this.detector === null) {\n const ladderOptions = {\n ...(options.v3AssetBaseUrl !== undefined\n ? { v3AssetBaseUrl: options.v3AssetBaseUrl }\n : {}),\n };\n const create =\n options.createDetector ??\n (options.createWorker !== undefined && workerOffloadSupported()\n ? async () => {\n // Worker offload (Task 9): the ladder runs WORKER-side; a\n // failed/hung init falls back to the in-thread ladder.\n try {\n return await WorkerDetectorProxy.create(\n (options.createWorker as () => WorkerLike)(),\n ladderOptions,\n );\n } catch {\n return createLadderDetector(ladderOptions);\n }\n }\n : () => createLadderDetector(ladderOptions));\n let created: Detector;\n try {\n created = await create();\n } catch (err) {\n // With the face-api floor gone, the ladder REJECTS once exhausted\n // (DetectorLadderError) — and any throwing seam is likewise a models\n // failure. Surface a retryable error{kind:'models'} (never a hang),\n // carrying the per-tier reasons for telemetry so a blaze init failure\n // stays observable in the field.\n if (attempt === this.attempt) {\n this.fail(\n \"models\",\n err instanceof DetectorLadderError ? err.fallbackReason : describeError(err),\n );\n }\n return;\n }\n // Resolve into a LOCAL first: assigning a detector into a superseded\n // (or destroyed) session would leak it — destroy() already nulled the\n // field, and a racing attempt may have created its own (review S2-3).\n if (attempt !== this.attempt) {\n created.destroy();\n return;\n }\n this.detector = created;\n this.options.telemetry?.({\n type: \"detector\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n });\n }\n\n const probe = probeDevice();\n const staticClass = options.deviceClass ?? classifyDevice(probe);\n this.profiler = new DeviceProfiler(staticClass);\n this.options.telemetry?.({\n type: \"profile\",\n staticClass,\n activeClass: this.profiler.deviceClass,\n simd: probe.simd,\n });\n\n this.gate = new FaceGateV3(options.thresholds ?? {});\n this.setState(\"positioning\");\n this.positioningStartedAt = this.now();\n this.startScheduler(attempt);\n }\n\n /** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */\n get animations(): \"full\" | \"reduced\" {\n return this.profiler?.profile.animations ?? \"full\";\n }\n\n private startScheduler(attempt: number): void {\n const profiler = this.profiler;\n if (profiler === null) return;\n if (this.scheduler !== null) {\n // A dynamic profile change replaces the scheduler — carry its stats so\n // the `fired` telemetry keeps the PRE-adjustment struggle visible.\n const stats = this.scheduler.stats();\n this.carriedDegrade += stats.degradeCount;\n if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);\n this.scheduler.stop();\n }\n const scheduler = new DetectScheduler({\n cadenceHz: profiler.profile.cadenceHz,\n video: this.options.video,\n ...(this.options.now !== undefined ? { now: this.options.now } : {}),\n run: () => this.detectTick(attempt),\n });\n this.scheduler = scheduler;\n scheduler.start();\n }\n\n private async detectTick(attempt: number): Promise<void> {\n const { detector, gate, profiler } = this;\n const video = this.options.video;\n if (attempt !== this.attempt || detector === null || gate === null || profiler === null)\n return;\n if (this.fired || video.videoWidth === 0) return;\n\n const before = profiler.deviceClass;\n const t0 = this.now();\n // Profile-adaptive DOWNSCALE: the detector sees an inputWidth-wide\n // snapshot, never the full 720p frame (the profile system's perf win);\n // stream-px normalization scales the observation back up.\n const source =\n this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ??\n this.defaultSnapshot(video, profiler.profile.inputWidth);\n let observation: Awaited<ReturnType<Detector[\"detect\"]>> = null;\n try {\n observation = await detector.detect(source, video.videoWidth, video.videoHeight);\n } catch {\n observation = null; // detectors never reject by contract; belt-and-braces\n }\n if (attempt !== this.attempt || this.fired) return;\n profiler.record(this.now() - t0);\n if (profiler.deviceClass !== before) this.startScheduler(attempt); // cadence follows the class\n\n const quality =\n observation === null\n ? NEUTRAL_QUALITY\n : (this.options.measureQuality?.(video, observation.box) ??\n this.defaultQuality(video, observation.box));\n\n const tick = gate.tick({\n timestampMs: this.now(),\n observation,\n quality,\n frameWidth: video.videoWidth,\n frameHeight: video.videoHeight,\n });\n // First face ACCEPTED by the gate (size / centering / quality all good —\n // the integrator rises), not merely detected. Set once; a later loss and\n // re-acquisition never moves it.\n if (tick.accepted && this.faceAcquiredAt === null) this.faceAcquiredAt = tick.at;\n this.emit(\"checks\", {\n engine: \"v3\",\n progress: tick.p,\n q: tick.q,\n factors: tick.factors,\n attempt,\n });\n if (tick.guidanceKey !== this.lastGuidanceKey) {\n this.lastGuidanceKey = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n if (tick.ready && this.stateValue === \"positioning\") {\n this.fired = true;\n this.captureCompleteAt = tick.at; // gate progress 100 % — capture complete\n void this.fire(attempt);\n }\n }\n\n private async fire(attempt: number): Promise<void> {\n const { options } = this;\n const scheduler = this.scheduler;\n scheduler?.stop();\n const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };\n const means = [...this.carriedMeans, ...(stats.meanDetectMs > 0 ? [stats.meanDetectMs] : [])];\n options.telemetry?.({\n type: \"fired\",\n timeToGateMs: this.now() - this.positioningStartedAt,\n degradeCount: this.carriedDegrade + stats.degradeCount,\n meanDetectMs:\n means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length,\n });\n\n const mode = options.mode ?? \"clip\";\n const bestOf = this.collectKeyframes(attempt);\n if (mode === \"photo\") {\n const best = await bestOf;\n if (attempt !== this.attempt) return;\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({ keyframe: best.blob, previewDataUrl: best.previewDataUrl });\n return;\n }\n\n this.setState(\"recording\");\n const recorder = options.createRecorder?.() ?? new ClipRecorder();\n const stream = this.stream;\n if (stream === null) {\n this.fail(\"generic\");\n return;\n }\n // The keyframe (the face_match selfie) resolves within the first 600ms —\n // well before the 2.5s clip ends. Latch it so the recording-STOP callback\n // below can emit `frozen` immediately, letting the host freeze the display\n // on the still without waiting for the clip blob to finalize (iOS lag).\n let frozenBest: KeyframeCandidate | null = null;\n void bestOf.then(\n (candidate) => {\n frozenBest = candidate;\n },\n () => {},\n );\n const onRecordingStopped = (): void => {\n if (attempt !== this.attempt) return; // superseded (retry/switch/destroy)\n if (frozenBest !== null) {\n this.emit(\"frozen\", { previewDataUrl: frozenBest.previewDataUrl });\n }\n };\n let clip: ClipResult;\n let best: KeyframeCandidate | null;\n try {\n [clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);\n } catch (err) {\n if (attempt !== this.attempt) return;\n const kind = (err as { kind?: CaptureErrorKind }).kind;\n this.fail(kind === \"cliptoolarge\" ? \"cliptoolarge\" : \"recorder\");\n return;\n }\n if (attempt !== this.attempt) return;\n if (isClipTooLarge(clip.blob)) {\n this.fail(\"cliptoolarge\");\n return;\n }\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({\n clip: clip.blob,\n clipMimeType: clip.mimeType,\n keyframe: best.blob,\n previewDataUrl: best.previewDataUrl,\n });\n }\n\n /** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —\n * sharpest wins (reuses frame-quality.sharpness via the capture seam). */\n private async collectKeyframes(attempt: number): Promise<KeyframeCandidate | null> {\n const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));\n const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);\n let best: KeyframeCandidate | null = null;\n for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {\n if (attempt !== this.attempt) return best;\n try {\n const candidate = await capture(this.options.video);\n if (best === null || candidate.sharpness > best.sharpness) best = candidate;\n } catch {\n // a failed candidate never sinks the capture — keep the best so far\n }\n if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);\n }\n return best;\n }\n\n private finishCapture(artifacts: CaptureArtifacts): void {\n this.stopTracks(); // privacy posture: camera off the moment we have artifacts\n this.setState(\"captured\");\n const timing = this.captureTiming();\n this.emit(\"artifacts\", timing === undefined ? artifacts : { ...artifacts, timing });\n }\n\n /** The attempt's capture-phase timing (whole ms, ≥ 0); undefined when no mark landed. */\n private captureTiming(): CaptureTiming | undefined {\n const span = (from: number | null, to: number | null): number | undefined =>\n from !== null && to !== null ? Math.max(0, Math.round(to - from)) : undefined;\n const cameraReadyMs = span(this.cameraRequestedAt, this.cameraReadyAt);\n const faceAcquireMs = span(this.cameraReadyAt, this.faceAcquiredAt);\n // Product definition: from the FIRST accepted face (a later loss /\n // re-acquisition never moves the start) until the gate reached 100 %.\n const captureMs = span(this.faceAcquiredAt, this.captureCompleteAt);\n const timing: CaptureTiming = {\n ...(cameraReadyMs !== undefined ? { cameraReadyMs } : {}),\n ...(faceAcquireMs !== undefined ? { faceAcquireMs } : {}),\n ...(captureMs !== undefined ? { captureMs } : {}),\n };\n return Object.keys(timing).length > 0 ? timing : undefined;\n }\n\n // ── defaults for the canvas-bound seams ────────────────────────────────────\n\n private async defaultKeyframe(video: HTMLVideoElement): Promise<KeyframeCandidate> {\n const canvas = document.createElement(\"canvas\");\n const blob = await captureMirroredKeyframe(video, canvas);\n const previewDataUrl = canvas.toDataURL(\"image/jpeg\", 0.92);\n return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };\n }\n\n /** Reused downscale canvas — falls back to the raw video where canvas 2D\n * is unavailable (jsdom) so tests and exotic hosts keep detecting. */\n private snapshotCanvas: HTMLCanvasElement | null = null;\n private defaultSnapshot(video: HTMLVideoElement, targetWidth: number): CanvasImageSource {\n try {\n const canvas = this.snapshotCanvas ?? document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, video.videoWidth);\n const width = Math.max(1, Math.round(video.videoWidth * scale));\n const height = Math.max(1, Math.round(video.videoHeight * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return video;\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n ctx.drawImage(video, 0, 0, width, height);\n this.snapshotCanvas = canvas;\n return canvas;\n } catch {\n return video;\n }\n }\n\n private defaultQuality(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ): V3GateQuality {\n const crop = cropImageData(video, box, 96);\n if (crop === null) return NEUTRAL_QUALITY;\n return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };\n }\n\n private centerSharpness(video: HTMLVideoElement): number {\n const size = intrinsicSize(video);\n const crop = cropImageData(\n video,\n { x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },\n 96,\n );\n return crop === null ? 0 : sharpness(crop);\n }\n\n // ── teardown ──────────────────────────────────────────────────────────────\n\n private teardownAttempt(): void {\n // No token bump here: retry()/switchCamera() call start() synchronously\n // right after, and START's own bump supersedes; destroy() bumps itself.\n this.scheduler?.stop();\n this.scheduler = null;\n this.gate = null;\n this.stopTracks();\n }\n\n private stopTracks(): void {\n if (this.stream === null) return;\n for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n }\n\n private fail(kind: CaptureErrorKind, fallbackReason?: string): void {\n this.scheduler?.stop();\n this.stopTracks();\n this.setState(\"error\");\n this.options.telemetry?.({\n type: \"error\",\n kind,\n ...(fallbackReason !== undefined ? { fallbackReason } : {}),\n });\n // v1 canRetry semantics (capture-session.ts L424).\n this.emit(\"error\", { kind, retryable: kind !== \"insecure\" && kind !== \"unsupported\" });\n }\n\n private setState(state: CaptureState): void {\n this.stateValue = state;\n this.emit(\"statechange\", { state });\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Downscaled face-crop ImageData for the quality measures; null where canvas\n * is unavailable (jsdom) — callers fall back to neutral quality. */\nfunction cropImageData(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n targetWidth: number,\n): ImageData | null {\n try {\n const canvas = document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, box.width);\n canvas.width = Math.max(1, Math.round(box.width * scale));\n canvas.height = Math.max(1, Math.round(box.height * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return null;\n ctx.drawImage(\n video,\n box.x,\n box.y,\n box.width,\n box.height,\n 0,\n 0,\n canvas.width,\n canvas.height,\n );\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBO,SAAS,wBACd,UACA,YACwB;AACxB,OAAK;AACL,SAAO;AAAA,IACL,OAAO;AAAA,MACL,OAAO,EAAE,OAAO,MAAM,KAAK,KAAK;AAAA,MAChC,QAAQ,EAAE,OAAO,KAAK,KAAK,IAAI;AAAA,MAC/B;AAAA,MACA,WAAW,EAAE,OAAO,IAAI,KAAK,GAAG;AAAA,IAClC;AAAA,IACA,OAAO;AAAA,EACT;AACF;AAGO,SAAS,iBAA0B;AACxC,MAAI,OAAO,WAAW,eAAe,OAAO,cAAc,YAAa,QAAO;AAC9E,SACE,OAAO,cAAc,OACrB,2DAA2D;AAAA,IACzD,OAAO,UAAU,aAAa,EAAE;AAAA,EAClC;AAEJ;AAQO,IAAM,uBAAuB;AAE7B,IAAM,mBAAmB;AAEzB,IAAM,kBAAkB;;;AC9CxB,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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AM,CAAC;AAAA,EACpC;AAAA,EAEQ,MAAc;AACpB,WAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,IAAI;AAAA,EACjD;AACF;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,cAAc,KAAsB;AAC3C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AAIA,SAAS,cACP,OACA,KACA,aACkB;AAClB,MAAI;AACF,UAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,UAAM,QAAQ,cAAc,KAAK,IAAI,GAAG,IAAI,KAAK;AACjD,WAAO,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,QAAQ,KAAK,CAAC;AACxD,WAAO,SAAS,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,SAAS,KAAK,CAAC;AAC1D,UAAM,MAAM,OAAO,WAAW,IAAI;AAClC,QAAI,QAAQ,KAAM,QAAO;AACzB,QAAI;AAAA,MACF;AAAA,MACA,IAAI;AAAA,MACJ,IAAI;AAAA,MACJ,IAAI;AAAA,MACJ,IAAI;AAAA,MACJ;AAAA,MACA;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AACA,WAAO,IAAI,aAAa,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;AAAA,EAC3D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["best"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/index.ts","../../src/client/errors.ts","../../src/client/hosted-client.ts"],"sourcesContent":["// @sekyro/web/client — typed API client for the hosted\n// session-token surface (Plan 6 Task 5). Framework-free browser code.\nexport {\n HostedClient,\n stripMimeParams,\n type HostedClientOptions,\n type MediaCheckType,\n type SubmitOptions,\n type UploadMedia,\n} from \"./hosted-client\";\nexport { HostedApiError, KNOWN_CODES, isKnownCode, type KnownCode } from \"./errors\";\nexport type {\n AttestationInput,\n CheckInputByType,\n CheckReason,\n CheckState,\n CheckType,\n CompleteMediaResult,\n ConsentLocale,\n DocOcrInput,\n DocReason,\n DocSide,\n FaceMatchInput,\n FaceMatchReason,\n HostedOtpView,\n HostedSessionView,\n HostedStepView,\n LivenessInput,\n LivenessReason,\n MediaKind,\n PhoneOtpInput,\n PhoneOtpReason,\n PopulationInput,\n PopulationReason,\n PresignRequest,\n PresignUploadResult,\n RecordConsentResult,\n SessionOutcome,\n SessionStatus,\n SessionStepView,\n SessionView,\n SubmitCheckBody,\n} from \"./types\";\n","// Public error map for the session-token surface (Plan 6 Task 5).\n//\n// The backend's AllExceptionsFilter (audience 'public') emits the FLAT envelope\n// `{code, message}` — no details, no request_id, no traceId. `code` is the\n// snake_cased `error` key of the thrown HttpException body (extractError →\n// camelToSnake). 429 responses additionally carry a `Retry-After` header in\n// SECONDS (SessionTokenGuard / RateLimitGuard).\n//\n// KNOWN_CODES below is the VERIFIED set reachable through the five hosted\n// endpoints (grep of `error: '…'` sites in identity-backend @ Tasks 0+1+2 —\n// hosted.controller, checks.controller, media.{controller,service},\n// sessions.service submit flow, session-token.guard, valibot.pipe,\n// check-executor registry, idempotency.interceptor, attestation mapping),\n// plus four CLIENT-SYNTHESIZED codes that never come from the backend:\n// - 'unknown_error' — a response body that was not parseable JSON (proxy HTML\n// on an error, or a malformed 2xx body)\n// - 'upload_failed' — the bare Spaces PUT answered non-2xx (S3 XML, no envelope)\n// - 'network_error' — fetch itself rejected: connection drop / DNS / CORS /\n// mid-transfer failure (status: 0 — no response arrived)\n// - 'timeout' — the request's AbortSignal.timeout fired (status: 0)\n// Task 7's error-copy map must carry entries for all four from day one.\n//\n// Deliberately EXCLUDED (verified unreachable on this surface today):\n// - payment_required / account_suspended — BillingInterceptor gates only\n// handlers decorated @BillableCheck, and no handler is decorated yet.\n// - not_found — the generic unmatched-route 404; a correctly configured client\n// never produces it. Unknown codes route through `isKnownCode() === false`.\n\n/**\n * Every error code the hosted page can receive from the session-token surface.\n * A closed string-literal union — switch over {@link KnownCode} with a `never`\n * default arm for compile-checked exhaustiveness.\n */\nexport const KNOWN_CODES = [\n // auth / addressing (session-token.guard, controllers' own-session guards)\n \"session_token_invalid\", // 401 — missing/invalid/expired/revoked token\n \"session_token_required\", // 403 — non-session-token principal on a hosted route (defensive)\n \"session_token_session_mismatch\", // 403 — route :id differs from the token's bound session\n \"session_not_found\", // 404 — token's session missing/foreign (findOwned)\n // rate limiting (session-token.guard — per-token + per-IP buckets)\n \"rate_limit_exceeded\", // 429 + Retry-After header (seconds)\n // consent gate (Task 0 — submit AND media presign/complete)\n \"consent_required\", // 409 — record consent before uploading/submitting\n // submit flow (sessions.service.submitCheck)\n \"session_not_active\", // 409 — session is terminal/review; no further submissions\n \"check_not_found\", // 404 — session has no such checkType\n \"check_already_finalized\", // 409 — re-submit of a terminal/review check\n \"check_out_of_order\", // 409 — only the frontier check accepts a submission\n \"check_type_unsupported\", // 400 — no registered executor for the checkType\n \"force_outcome_forbidden\", // 403 — forceOutcome on a live session (plan D-C)\n \"attestation_invalid\", // 400 (Task 1) — Turnstile/attestation failed; reload and retry\n \"nni_locked\", // 409 (Plan A Task 2) — session is bound to a server-provided NNI; a different client NNI was sent\n // media (media.service)\n \"media_content_type_not_allowed\", // 400 — outside the per-kind MIME allowlist\n \"media_too_large\", // 413 — over the per-kind byte cap\n \"media_key_invalid\", // 400 — not a well-formed pending key\n \"media_key_forbidden\", // 403 — key names another session's pending space\n \"media_not_found\", // 404 — no uploaded object behind the key\n \"media_unreadable\", // 422 — magic-byte sniff rejected the object\n \"media_session_invalid\", // 400 — sessionId unusable as a key segment (never in practice)\n // idempotency (idempotency.interceptor — Task 2)\n \"idempotency_key_collision\", // 409 — same key, different body hash\n \"idempotency_in_progress\", // 409 — concurrent identical request mid-flight (client auto-retries)\n \"idempotency_key_required\", // 400 — only on @Idempotent({required:true}) routes (none hosted yet)\n // validation + fallback\n \"validation_error\", // 400 — ValibotPipe rejection (camelToSnake of 'ValidationError')\n \"internal_error\", // 500 — unhandled server error\n // client-synthesized (never sent by the backend)\n \"unknown_error\", // unparseable (non-JSON) response body — error OR 2xx (defensive)\n \"upload_failed\", // the bare Spaces PUT answered non-2xx\n \"network_error\", // fetch rejected: connection drop / DNS / CORS / mid-transfer (status 0)\n \"timeout\", // AbortSignal.timeout fired — API calls 30 s default, Spaces PUT 15 min (status 0)\n] as const;\n\n/** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */\nexport type KnownCode = (typeof KNOWN_CODES)[number];\n\n/** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */\nexport function isKnownCode(code: string): code is KnownCode {\n return (KNOWN_CODES as readonly string[]).includes(code);\n}\n\n/**\n * Typed transport error: EVERY failure surfaces as one of these — non-2xx\n * responses, rejected fetches, timeouts, and unparseable bodies alike. The\n * hosted page never sees a raw TypeError/DOMException from the client.\n *\n * - `code` — the public envelope's `code`, or a client-synthesized fallback\n * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed\n * `string` because the wire may grow codes; narrow with {@link isKnownCode}\n * before an exhaustive switch.\n * - `status` — the HTTP status, or 0 when no response arrived at all\n * ('network_error' / 'timeout').\n * - `retryAfterSeconds` — parsed from the `Retry-After` header when present\n * (rate-limit 429s always set it).\n */\nexport class HostedApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly retryAfterSeconds?: number;\n\n constructor(args: { status: number; code: string; message: string; retryAfterSeconds?: number }) {\n super(args.message);\n this.name = \"HostedApiError\";\n this.status = args.status;\n this.code = args.code;\n if (args.retryAfterSeconds !== undefined) this.retryAfterSeconds = args.retryAfterSeconds;\n }\n}\n","// Typed API client for the hosted session-token surface (Plan 6 Task 5).\n// Framework-free browser code — fetch + AbortSignal only, same zero-React rule\n// as core/. Hand-authored against the CURRENT identity-backend (Tasks 0+1+2);\n// see types.ts / errors.ts for the verified wire shapes.\nimport { HostedApiError } from \"./errors\";\nimport type {\n CheckInputByType,\n CheckType,\n CompleteMediaResult,\n ConsentLocale,\n HostedSessionView,\n MediaKind,\n PresignRequest,\n PresignUploadResult,\n RecordConsentResult,\n SessionView,\n SubmitCheckBody,\n} from \"./types\";\n\n/** Default per-request timeout on API calls (override via `requestTimeoutMs`). */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Timeout on the Spaces PUT — matches the presign TTL (900 s): the signature is\n * unusable after that anyway, and a 15 MB clip at 20 KB/s still finishes in\n * ~13 min. Bounds a stalled in-flight socket (the TTL alone only bounds when a\n * PUT can START, not how long a hung transfer may sit).\n */\nconst SPACES_PUT_TIMEOUT_MS = 900_000;\n\n/** Max chars of an S3 error body quoted into an upload_failed message. */\nconst UPLOAD_ERROR_SNIPPET_CHARS = 200;\n\n/** Bounded auto-retry defaults for 409 `idempotency_in_progress` (retries AFTER the first try). */\nconst IN_PROGRESS_RETRY_ATTEMPTS = 5;\nconst IN_PROGRESS_RETRY_DELAY_MS = 400;\n\n/**\n * Strip MIME parameters: `video/webm;codecs=vp8,opus` → `video/webm`.\n *\n * The capture engine (Task 4) emits `clipMimeType` WITH codec parameters, but\n * the presign allowlist holds BARE types only (['video/webm','video/mp4'] /\n * ['image/jpeg','image/png']) and the presigned PUT signs the exact declared\n * Content-Type. Exported so pages can normalize once and stay byte-consistent\n * between presign and PUT.\n */\nexport function stripMimeParams(contentType: string): string {\n return (contentType.split(\";\")[0] ?? \"\").trim();\n}\n\n/** Media-bearing check types → the input field the promoted key goes into. */\nconst MEDIA_INPUT_FIELD = {\n liveness: \"clipKey\",\n face_match: \"imageKey\",\n doc_ocr: \"imageKey\",\n} as const;\n\n/** Check types that take an uploaded media key (population_registry does not). */\nexport type MediaCheckType = keyof typeof MEDIA_INPUT_FIELD;\n\nexport interface SubmitOptions {\n /**\n * Sent as `x-idempotency-key` (the header IdempotencyInterceptor reads).\n * One key per LOGICAL submit — a flaky-network retry with the same key\n * replays the first response without burning another attempt.\n */\n idempotencyKey?: string;\n /** SANDBOX-ONLY deterministic override (plan D-C); a live session 403s it. */\n forceOutcome?: \"pass\" | \"fail\";\n}\n\nexport interface UploadMedia {\n kind: MediaKind;\n blob: Blob;\n /** May carry codec params (engine `clipMimeType`) — stripped before presign AND PUT. */\n contentType: string;\n}\n\nexport interface HostedClientOptions {\n /** API origin, e.g. `https://api.sekyro.ai` — paths are `${apiOrigin}/api/v2/...`. */\n apiOrigin: string;\n /** The raw session token from the hosted URL (short code; legacy `cst_` during its TTL) — sent as `x-session-token` on every API call. */\n sessionToken: string;\n /** Injection seam (tests / non-window contexts). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout for API calls (NOT the Spaces PUT). Default 30 000 ms. */\n requestTimeoutMs?: number;\n /**\n * Tuning for the ONLY automatic retry the client performs: 409\n * `idempotency_in_progress` (a concurrent identical request is mid-flight\n * server-side; the real response lands once it finishes). `attempts` counts\n * retries AFTER the first try. Defaults: 5 × 400 ms.\n */\n inProgressRetry?: { attempts?: number; delayMs?: number };\n}\n\n/**\n * Hand-authored typed client for the five session-token endpoints:\n *\n * GET /api/v2/hosted/session → {@link getSession}\n * POST /api/v2/hosted/consent → {@link recordConsent}\n * POST /api/v2/sessions/:id/media → {@link presign}\n * POST /api/v2/sessions/:id/media/complete → {@link completeMedia}\n * POST /api/v2/sessions/:id/checks/:checkType → {@link submitCheck}\n *\n * plus the bare presigned Spaces PUT ({@link uploadToSpaces}) and the\n * presign→PUT→complete→submit composition ({@link uploadAndSubmit}).\n *\n * Envelopes (verified against sessions-docs.e2e-spec.ts):\n * - success: `{success: true, data}` — unwrapped here, methods return the payload;\n * - error: flat `{code, message}` → thrown as {@link HostedApiError}.\n *\n * The media/checks routes are `:id`-addressed while the token itself is the\n * only credential the page starts with — the client learns its sessionId from\n * `GET /hosted/session` (token-addressed) and lazily bootstraps it when a\n * `:id` route is called first.\n *\n * No automatic retry EXCEPT bounded short-delay retry on 409\n * `idempotency_in_progress`. Everything else — including 429 with its parsed\n * `retryAfterSeconds` — is surfaced to the page to handle.\n */\nexport class HostedClient {\n private readonly apiOrigin: string;\n private readonly sessionToken: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly requestTimeoutMs: number;\n private readonly retryAttempts: number;\n private readonly retryDelayMs: number;\n\n private sessionId: string | null = null;\n private bootstrap: Promise<HostedSessionView> | null = null;\n\n constructor(opts: HostedClientOptions) {\n this.apiOrigin = opts.apiOrigin.replace(/\\/+$/, \"\");\n this.sessionToken = opts.sessionToken;\n // Always wrap and `.call(globalThis, …)`: browsers throw \"Illegal\n // invocation\" when fetch runs with a `this` that isn't the global — both\n // for the default AND for an injected `window.fetch`.\n const impl = opts.fetch;\n this.fetchImpl = (input, init) => (impl ?? globalThis.fetch).call(globalThis, input, init);\n this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.retryAttempts = opts.inProgressRetry?.attempts ?? IN_PROGRESS_RETRY_ATTEMPTS;\n this.retryDelayMs = opts.inProgressRetry?.delayMs ?? IN_PROGRESS_RETRY_DELAY_MS;\n }\n\n /** Token-addressed bootstrap — the hosted page's first call. Caches the sessionId. */\n async getSession(): Promise<HostedSessionView> {\n const view = await this.api<HostedSessionView>(\"GET\", \"/hosted/session\");\n this.sessionId = view.sessionId;\n return view;\n }\n\n /**\n * Record consent once (201; an idempotent replay answers 200 with\n * `alreadyRecorded: true`). Until recorded, media presign/complete AND check\n * submission answer 409 `consent_required`.\n */\n async recordConsent(locale: ConsentLocale): Promise<RecordConsentResult> {\n return this.api<RecordConsentResult>(\"POST\", \"/hosted/consent\", { body: { locale } });\n }\n\n /**\n * Presign a Spaces PUT for a new pending object. `contentType` is stripped of\n * MIME parameters defensively (the allowlist holds bare types; the engine's\n * `clipMimeType` carries codec params) — PUT with the SAME bare type, or the\n * signed-header check rejects the upload.\n */\n async presign(\n kind: MediaKind,\n contentType: string,\n contentLength: number,\n ): Promise<PresignUploadResult> {\n const id = await this.ensureSessionId();\n const body: PresignRequest = { kind, contentType: stripMimeParams(contentType), contentLength };\n return this.api<PresignUploadResult>(\"POST\", `/sessions/${id}/media`, { body });\n }\n\n /**\n * Bare PUT to the presigned Spaces URL: EXACTLY the signed headers — the\n * declared Content-Type and the blob body. NO `x-session-token` (the\n * signature IS the credential; an extra header breaks nothing but leaks the\n * token to a third-party host) and no JSON envelope.\n *\n * `contentType` is param-stripped here too (idempotent for bare types): the\n * presign strips internally, so a caller composing manually with the engine's\n * parameterful `clipMimeType` would otherwise sign `video/webm` but PUT\n * `video/webm;codecs=…` — a signed-header mismatch S3 rejects at runtime.\n *\n * Timeout: 15 min (`AbortSignal.timeout(900_000)`, matching the presign TTL)\n * rather than the API calls' 30 s — a 15 MB clip on a slow link legitimately\n * exceeds 30 s, but a stalled in-flight socket must still be bounded (the TTL\n * alone only bounds when a PUT can START).\n *\n * Failures are ALWAYS typed: non-2xx throws {@link HostedApiError} with the\n * client-synthesized `upload_failed` (message carries a truncated S3 body\n * snippet — e.g. SignatureDoesNotMatch); a mid-transfer drop → `network_error`;\n * the timeout → `timeout`.\n */\n async uploadToSpaces(uploadUrl: string, blob: Blob, contentType: string): Promise<void> {\n let res: Response;\n try {\n res = await this.fetchImpl(uploadUrl, {\n method: \"PUT\",\n headers: { \"content-type\": stripMimeParams(contentType) },\n body: blob,\n signal: AbortSignal.timeout(SPACES_PUT_TIMEOUT_MS),\n });\n } catch (err) {\n throw asTransportError(err);\n }\n if (!res.ok) {\n const snippet = (await res.text().catch(() => \"\")).slice(0, UPLOAD_ERROR_SNIPPET_CHARS);\n throw new HostedApiError({\n status: res.status,\n code: \"upload_failed\",\n message: `media upload failed (HTTP ${res.status})${snippet ? `: ${snippet}` : \"\"}`,\n });\n }\n }\n\n /** Finalize an upload: the backend sniffs + promotes; returns the PROMOTED key to submit. */\n async completeMedia(key: string): Promise<CompleteMediaResult> {\n const id = await this.ensureSessionId();\n return this.api<CompleteMediaResult>(\"POST\", `/sessions/${id}/media/complete`, {\n body: { key },\n });\n }\n\n /**\n * Submit one check. Sends `{input, forceOutcome?}` (SubmitCheckSchema) and the\n * optional `x-idempotency-key` header. Returns the whitelisted SessionView.\n */\n async submitCheck<T extends CheckType>(\n checkType: T,\n input: CheckInputByType[T],\n opts: SubmitOptions = {},\n ): Promise<SessionView> {\n const id = await this.ensureSessionId();\n const body: SubmitCheckBody = {\n input: input as unknown as Record<string, unknown>,\n ...(opts.forceOutcome !== undefined ? { forceOutcome: opts.forceOutcome } : {}),\n };\n return this.api<SessionView>(\"POST\", `/sessions/${id}/checks/${checkType}`, {\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n });\n }\n\n /**\n * Convenience composition: presign → PUT → complete → submit, passing the\n * PROMOTED key (from complete's response — never the pending presign key)\n * into the check's media input field (`clipKey` for liveness, `imageKey` for\n * face_match/doc_ocr). `extraInput` carries the remaining input fields\n * (liveness `attestation`, doc_ocr `side`). The media content type is\n * param-stripped ONCE and used for both presign and PUT, so the signed\n * header always matches.\n */\n async uploadAndSubmit<T extends MediaCheckType>(\n checkType: T,\n media: UploadMedia,\n extraInput: Omit<CheckInputByType[T], (typeof MEDIA_INPUT_FIELD)[T]>,\n opts: SubmitOptions = {},\n ): Promise<SessionView> {\n const bareType = stripMimeParams(media.contentType);\n const presigned = await this.presign(media.kind, bareType, media.blob.size);\n await this.uploadToSpaces(presigned.uploadUrl, media.blob, bareType);\n const completed = await this.completeMedia(presigned.key);\n const input = {\n ...extraInput,\n [MEDIA_INPUT_FIELD[checkType]]: completed.key,\n } as unknown as CheckInputByType[T];\n return this.submitCheck(checkType, input, opts);\n }\n\n // ── transport ──────────────────────────────────────────────────────────────\n\n /** The token's own sessionId — cached from getSession(), lazily bootstrapped. */\n private async ensureSessionId(): Promise<string> {\n if (this.sessionId !== null) return this.sessionId;\n // Dedupe concurrent bootstraps; reset on settle so a failure can be retried.\n this.bootstrap ??= this.getSession().finally(() => {\n this.bootstrap = null;\n });\n return (await this.bootstrap).sessionId;\n }\n\n /**\n * One API request: `${apiOrigin}/api/v2${path}`, `x-session-token` always,\n * AbortSignal timeout (30 s default), `{success, data}` unwrap on 2xx, flat\n * `{code, message}` → {@link HostedApiError} on non-2xx. EVERY failure is\n * typed: a rejected fetch → `network_error`, the timeout → `timeout`, an\n * unparseable 2xx body → `unknown_error` — the page never sees a raw\n * TypeError/DOMException. The ONLY automatic retry is 409\n * `idempotency_in_progress` (bounded, short delay).\n */\n private async api<T>(\n method: \"GET\" | \"POST\",\n path: string,\n opts: { body?: unknown; idempotencyKey?: string } = {},\n ): Promise<T> {\n const url = `${this.apiOrigin}/api/v2${path}`;\n const headers: Record<string, string> = { \"x-session-token\": this.sessionToken };\n if (opts.body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (opts.idempotencyKey !== undefined) headers[\"x-idempotency-key\"] = opts.idempotencyKey;\n\n for (let attempt = 0; ; attempt++) {\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method,\n headers,\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n });\n } catch (err) {\n throw asTransportError(err);\n }\n\n if (res.ok) {\n let raw: unknown;\n try {\n raw = await res.json();\n } catch {\n throw new HostedApiError({\n status: res.status,\n code: \"unknown_error\",\n message: `response body was not valid JSON (HTTP ${res.status})`,\n });\n }\n return unwrap<T>(raw);\n }\n\n const err = await parseErrorResponse(res);\n if (err.code === \"idempotency_in_progress\" && attempt < this.retryAttempts) {\n if (this.retryDelayMs > 0) await sleep(this.retryDelayMs);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Normalize a rejected fetch into the typed contract (status 0 — no response\n * arrived): AbortSignal.timeout aborts with a DOMException named 'TimeoutError'\n * → `timeout`; everything else (TypeError on connection drop / DNS / CORS /\n * mid-transfer failure) → `network_error`. Duck-typed on `.name` because\n * DOMException does not inherit Error in every environment (e.g. jsdom).\n */\nfunction asTransportError(err: unknown): HostedApiError {\n const name = typeof err === \"object\" && err !== null ? (err as { name?: unknown }).name : undefined;\n if (name === \"TimeoutError\") {\n return new HostedApiError({ status: 0, code: \"timeout\", message: \"request timed out\" });\n }\n const detail = err instanceof Error ? err.message : String(err);\n return new HostedApiError({\n status: 0,\n code: \"network_error\",\n message: `network request failed: ${detail}`,\n });\n}\n\n/**\n * Unwrap the global success envelope `{success: true, data}` (ResponseTransform-\n * Interceptor wraps every object body that lacks a `success` key). Defensive:\n * a body without the envelope is returned as-is.\n */\nfunction unwrap<T>(raw: unknown): T {\n if (raw !== null && typeof raw === \"object\" && \"success\" in raw && \"data\" in raw) {\n return (raw as { data: T }).data;\n }\n return raw as T;\n}\n\n/**\n * Parse a non-2xx response into a {@link HostedApiError}: the public envelope\n * is flat `{code, message}`; a non-JSON body (proxy HTML, etc.) degrades to the\n * client-synthesized `unknown_error`. `Retry-After` (seconds) is parsed when\n * present — rate-limit 429s always set it.\n */\nasync function parseErrorResponse(res: Response): Promise<HostedApiError> {\n let code = \"unknown_error\";\n let message = `request failed (HTTP ${res.status})`;\n try {\n const body: unknown = await res.json();\n if (body !== null && typeof body === \"object\") {\n const env = body as { code?: unknown; message?: unknown };\n if (typeof env.code === \"string\" && env.code.length > 0) code = env.code;\n if (typeof env.message === \"string\" && env.message.length > 0) message = env.message;\n }\n } catch {\n // Not JSON — keep the defensive fallback.\n }\n const retryAfterRaw = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterRaw === null ? Number.NaN : Number.parseInt(retryAfterRaw, 10);\n return new HostedApiError({\n status: res.status,\n code,\n message,\n ...(Number.isFinite(retryAfter) && retryAfter >= 0 ? { retryAfterSeconds: retryAfter } : {}),\n });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiCO,IAAM,cAAc;AAAA;AAAA,EAEzB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;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OAAO,OAAO,MAAM,OAAO,SAAS,eAAe,EAAE;AAC1F,SAAO,IAAI,eAAe;AAAA,IACxB,QAAQ,IAAI;AAAA,IACZ;AAAA,IACA;AAAA,IACA,GAAI,OAAO,SAAS,UAAU,KAAK,cAAc,IAAI,EAAE,mBAAmB,WAAW,IAAI,CAAC;AAAA,EAC5F,CAAC;AACH;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":["err"]}
|
|
1
|
+
{"version":3,"sources":["../../src/client/index.ts","../../src/client/errors.ts","../../src/client/hosted-client.ts"],"sourcesContent":["// @sekyro/web/client — typed API client for the hosted\n// session-token surface (Plan 6 Task 5). Framework-free browser code.\nexport {\n HostedClient,\n stripMimeParams,\n type HostedClientOptions,\n type MediaCheckType,\n type SubmitOptions,\n type UploadMedia,\n} from \"./hosted-client\";\nexport { HostedApiError, KNOWN_CODES, isKnownCode, type KnownCode } from \"./errors\";\nexport type {\n AttestationInput,\n CheckInputByType,\n CheckReason,\n CheckState,\n CheckType,\n CompleteMediaResult,\n ConsentLocale,\n DocOcrInput,\n DocReason,\n DocSide,\n FaceMatchInput,\n FaceMatchReason,\n HostedOtpView,\n HostedSessionView,\n HostedStepView,\n LivenessCaptureInput,\n LivenessInput,\n LivenessReason,\n MediaKind,\n PhoneOtpInput,\n PhoneOtpReason,\n PopulationInput,\n PopulationReason,\n PresignRequest,\n PresignUploadResult,\n RecordConsentResult,\n SessionOutcome,\n SessionStatus,\n SessionStepView,\n SessionView,\n SubmitCheckBody,\n} from \"./types\";\n","// Public error map for the session-token surface (Plan 6 Task 5).\n//\n// The backend's AllExceptionsFilter (audience 'public') emits the FLAT envelope\n// `{code, message}` — no details, no request_id, no traceId. `code` is the\n// snake_cased `error` key of the thrown HttpException body (extractError →\n// camelToSnake). 429 responses additionally carry a `Retry-After` header in\n// SECONDS (SessionTokenGuard / RateLimitGuard).\n//\n// KNOWN_CODES below is the VERIFIED set reachable through the five hosted\n// endpoints (grep of `error: '…'` sites in identity-backend @ Tasks 0+1+2 —\n// hosted.controller, checks.controller, media.{controller,service},\n// sessions.service submit flow, session-token.guard, valibot.pipe,\n// check-executor registry, idempotency.interceptor, attestation mapping),\n// plus four CLIENT-SYNTHESIZED codes that never come from the backend:\n// - 'unknown_error' — a response body that was not parseable JSON (proxy HTML\n// on an error, or a malformed 2xx body)\n// - 'upload_failed' — the bare Spaces PUT answered non-2xx (S3 XML, no envelope)\n// - 'network_error' — fetch itself rejected: connection drop / DNS / CORS /\n// mid-transfer failure (status: 0 — no response arrived)\n// - 'timeout' — the request's AbortSignal.timeout fired (status: 0)\n// Task 7's error-copy map must carry entries for all four from day one.\n//\n// Deliberately EXCLUDED (verified unreachable on this surface today):\n// - payment_required / account_suspended — BillingInterceptor gates only\n// handlers decorated @BillableCheck, and no handler is decorated yet.\n// - not_found — the generic unmatched-route 404; a correctly configured client\n// never produces it. Unknown codes route through `isKnownCode() === false`.\n\n/**\n * Every error code the hosted page can receive from the session-token surface.\n * A closed string-literal union — switch over {@link KnownCode} with a `never`\n * default arm for compile-checked exhaustiveness.\n */\nexport const KNOWN_CODES = [\n // auth / addressing (session-token.guard, controllers' own-session guards)\n \"session_token_invalid\", // 401 — missing/invalid/expired/revoked token\n \"session_token_required\", // 403 — non-session-token principal on a hosted route (defensive)\n \"session_token_session_mismatch\", // 403 — route :id differs from the token's bound session\n \"session_not_found\", // 404 — token's session missing/foreign (findOwned)\n // rate limiting (session-token.guard — per-token + per-IP buckets)\n \"rate_limit_exceeded\", // 429 + Retry-After header (seconds)\n // consent gate (Task 0 — submit AND media presign/complete)\n \"consent_required\", // 409 — record consent before uploading/submitting\n // submit flow (sessions.service.submitCheck)\n \"session_not_active\", // 409 — session is terminal/review; no further submissions\n \"check_not_found\", // 404 — session has no such checkType\n \"check_already_finalized\", // 409 — re-submit of a terminal/review check\n \"check_out_of_order\", // 409 — only the frontier check accepts a submission\n \"check_type_unsupported\", // 400 — no registered executor for the checkType\n \"force_outcome_forbidden\", // 403 — forceOutcome on a live session (plan D-C)\n \"attestation_invalid\", // 400 (Task 1) — Turnstile/attestation failed; reload and retry\n \"nni_locked\", // 409 (Plan A Task 2) — session is bound to a server-provided NNI; a different client NNI was sent\n // media (media.service)\n \"media_content_type_not_allowed\", // 400 — outside the per-kind MIME allowlist\n \"media_too_large\", // 413 — over the per-kind byte cap\n \"media_key_invalid\", // 400 — not a well-formed pending key\n \"media_key_forbidden\", // 403 — key names another session's pending space\n \"media_not_found\", // 404 — no uploaded object behind the key\n \"media_unreadable\", // 422 — magic-byte sniff rejected the object\n \"media_session_invalid\", // 400 — sessionId unusable as a key segment (never in practice)\n // idempotency (idempotency.interceptor — Task 2)\n \"idempotency_key_collision\", // 409 — same key, different body hash\n \"idempotency_in_progress\", // 409 — concurrent identical request mid-flight (client auto-retries)\n \"idempotency_key_required\", // 400 — only on @Idempotent({required:true}) routes (none hosted yet)\n // validation + fallback\n \"validation_error\", // 400 — ValibotPipe rejection (camelToSnake of 'ValidationError')\n \"internal_error\", // 500 — unhandled server error\n // client-synthesized (never sent by the backend)\n \"unknown_error\", // unparseable (non-JSON) response body — error OR 2xx (defensive)\n \"upload_failed\", // the bare Spaces PUT answered non-2xx\n \"network_error\", // fetch rejected: connection drop / DNS / CORS / mid-transfer (status 0)\n \"timeout\", // AbortSignal.timeout fired — API calls 30 s default, Spaces PUT 15 min (status 0)\n] as const;\n\n/** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */\nexport type KnownCode = (typeof KNOWN_CODES)[number];\n\n/** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */\nexport function isKnownCode(code: string): code is KnownCode {\n return (KNOWN_CODES as readonly string[]).includes(code);\n}\n\n/**\n * Typed transport error: EVERY failure surfaces as one of these — non-2xx\n * responses, rejected fetches, timeouts, and unparseable bodies alike. The\n * hosted page never sees a raw TypeError/DOMException from the client.\n *\n * - `code` — the public envelope's `code`, or a client-synthesized fallback\n * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed\n * `string` because the wire may grow codes; narrow with {@link isKnownCode}\n * before an exhaustive switch.\n * - `status` — the HTTP status, or 0 when no response arrived at all\n * ('network_error' / 'timeout').\n * - `retryAfterSeconds` — parsed from the `Retry-After` header when present\n * (rate-limit 429s always set it).\n */\nexport class HostedApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly retryAfterSeconds?: number;\n\n constructor(args: { status: number; code: string; message: string; retryAfterSeconds?: number }) {\n super(args.message);\n this.name = \"HostedApiError\";\n this.status = args.status;\n this.code = args.code;\n if (args.retryAfterSeconds !== undefined) this.retryAfterSeconds = args.retryAfterSeconds;\n }\n}\n","// Typed API client for the hosted session-token surface (Plan 6 Task 5).\n// Framework-free browser code — fetch + AbortSignal only, same zero-React rule\n// as core/. Hand-authored against the CURRENT identity-backend (Tasks 0+1+2);\n// see types.ts / errors.ts for the verified wire shapes.\nimport { HostedApiError } from \"./errors\";\nimport type {\n CheckInputByType,\n CheckType,\n CompleteMediaResult,\n ConsentLocale,\n HostedSessionView,\n MediaKind,\n PresignRequest,\n PresignUploadResult,\n RecordConsentResult,\n SessionView,\n SubmitCheckBody,\n} from \"./types\";\n\n/** Default per-request timeout on API calls (override via `requestTimeoutMs`). */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Timeout on the Spaces PUT — matches the presign TTL (900 s): the signature is\n * unusable after that anyway, and a 15 MB clip at 20 KB/s still finishes in\n * ~13 min. Bounds a stalled in-flight socket (the TTL alone only bounds when a\n * PUT can START, not how long a hung transfer may sit).\n */\nconst SPACES_PUT_TIMEOUT_MS = 900_000;\n\n/** Max chars of an S3 error body quoted into an upload_failed message. */\nconst UPLOAD_ERROR_SNIPPET_CHARS = 200;\n\n/** Bounded auto-retry defaults for 409 `idempotency_in_progress` (retries AFTER the first try). */\nconst IN_PROGRESS_RETRY_ATTEMPTS = 5;\nconst IN_PROGRESS_RETRY_DELAY_MS = 400;\n\n/**\n * Strip MIME parameters: `video/webm;codecs=vp8,opus` → `video/webm`.\n *\n * The capture engine (Task 4) emits `clipMimeType` WITH codec parameters, but\n * the presign allowlist holds BARE types only (['video/webm','video/mp4'] /\n * ['image/jpeg','image/png']) and the presigned PUT signs the exact declared\n * Content-Type. Exported so pages can normalize once and stay byte-consistent\n * between presign and PUT.\n */\nexport function stripMimeParams(contentType: string): string {\n return (contentType.split(\";\")[0] ?? \"\").trim();\n}\n\n/** Media-bearing check types → the input field the promoted key goes into. */\nconst MEDIA_INPUT_FIELD = {\n liveness: \"clipKey\",\n face_match: \"imageKey\",\n doc_ocr: \"imageKey\",\n} as const;\n\n/** Check types that take an uploaded media key (population_registry does not). */\nexport type MediaCheckType = keyof typeof MEDIA_INPUT_FIELD;\n\nexport interface SubmitOptions {\n /**\n * Sent as `x-idempotency-key` (the header IdempotencyInterceptor reads).\n * One key per LOGICAL submit — a flaky-network retry with the same key\n * replays the first response without burning another attempt.\n */\n idempotencyKey?: string;\n /** SANDBOX-ONLY deterministic override (plan D-C); a live session 403s it. */\n forceOutcome?: \"pass\" | \"fail\";\n}\n\nexport interface UploadMedia {\n kind: MediaKind;\n blob: Blob;\n /** May carry codec params (engine `clipMimeType`) — stripped before presign AND PUT. */\n contentType: string;\n}\n\nexport interface HostedClientOptions {\n /** API origin, e.g. `https://api.sekyro.ai` — paths are `${apiOrigin}/api/v2/...`. */\n apiOrigin: string;\n /** The raw session token from the hosted URL (short code; legacy `cst_` during its TTL) — sent as `x-session-token` on every API call. */\n sessionToken: string;\n /** Injection seam (tests / non-window contexts). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout for API calls (NOT the Spaces PUT). Default 30 000 ms. */\n requestTimeoutMs?: number;\n /**\n * Tuning for the ONLY automatic retry the client performs: 409\n * `idempotency_in_progress` (a concurrent identical request is mid-flight\n * server-side; the real response lands once it finishes). `attempts` counts\n * retries AFTER the first try. Defaults: 5 × 400 ms.\n */\n inProgressRetry?: { attempts?: number; delayMs?: number };\n}\n\n/**\n * Hand-authored typed client for the five session-token endpoints:\n *\n * GET /api/v2/hosted/session → {@link getSession}\n * POST /api/v2/hosted/consent → {@link recordConsent}\n * POST /api/v2/sessions/:id/media → {@link presign}\n * POST /api/v2/sessions/:id/media/complete → {@link completeMedia}\n * POST /api/v2/sessions/:id/checks/:checkType → {@link submitCheck}\n *\n * plus the bare presigned Spaces PUT ({@link uploadToSpaces}) and the\n * presign→PUT→complete→submit composition ({@link uploadAndSubmit}).\n *\n * Envelopes (verified against sessions-docs.e2e-spec.ts):\n * - success: `{success: true, data}` — unwrapped here, methods return the payload;\n * - error: flat `{code, message}` → thrown as {@link HostedApiError}.\n *\n * The media/checks routes are `:id`-addressed while the token itself is the\n * only credential the page starts with — the client learns its sessionId from\n * `GET /hosted/session` (token-addressed) and lazily bootstraps it when a\n * `:id` route is called first.\n *\n * No automatic retry EXCEPT bounded short-delay retry on 409\n * `idempotency_in_progress`. Everything else — including 429 with its parsed\n * `retryAfterSeconds` — is surfaced to the page to handle.\n */\nexport class HostedClient {\n private readonly apiOrigin: string;\n private readonly sessionToken: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly requestTimeoutMs: number;\n private readonly retryAttempts: number;\n private readonly retryDelayMs: number;\n\n private sessionId: string | null = null;\n private bootstrap: Promise<HostedSessionView> | null = null;\n\n constructor(opts: HostedClientOptions) {\n this.apiOrigin = opts.apiOrigin.replace(/\\/+$/, \"\");\n this.sessionToken = opts.sessionToken;\n // Always wrap and `.call(globalThis, …)`: browsers throw \"Illegal\n // invocation\" when fetch runs with a `this` that isn't the global — both\n // for the default AND for an injected `window.fetch`.\n const impl = opts.fetch;\n this.fetchImpl = (input, init) => (impl ?? globalThis.fetch).call(globalThis, input, init);\n this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.retryAttempts = opts.inProgressRetry?.attempts ?? IN_PROGRESS_RETRY_ATTEMPTS;\n this.retryDelayMs = opts.inProgressRetry?.delayMs ?? IN_PROGRESS_RETRY_DELAY_MS;\n }\n\n /** Token-addressed bootstrap — the hosted page's first call. Caches the sessionId. */\n async getSession(): Promise<HostedSessionView> {\n const view = await this.api<HostedSessionView>(\"GET\", \"/hosted/session\");\n this.sessionId = view.sessionId;\n return view;\n }\n\n /**\n * Record consent once (201; an idempotent replay answers 200 with\n * `alreadyRecorded: true`). Until recorded, media presign/complete AND check\n * submission answer 409 `consent_required`.\n */\n async recordConsent(locale: ConsentLocale): Promise<RecordConsentResult> {\n return this.api<RecordConsentResult>(\"POST\", \"/hosted/consent\", { body: { locale } });\n }\n\n /**\n * Presign a Spaces PUT for a new pending object. `contentType` is stripped of\n * MIME parameters defensively (the allowlist holds bare types; the engine's\n * `clipMimeType` carries codec params) — PUT with the SAME bare type, or the\n * signed-header check rejects the upload.\n */\n async presign(\n kind: MediaKind,\n contentType: string,\n contentLength: number,\n ): Promise<PresignUploadResult> {\n const id = await this.ensureSessionId();\n const body: PresignRequest = { kind, contentType: stripMimeParams(contentType), contentLength };\n return this.api<PresignUploadResult>(\"POST\", `/sessions/${id}/media`, { body });\n }\n\n /**\n * Bare PUT to the presigned Spaces URL: EXACTLY the signed headers — the\n * declared Content-Type and the blob body. NO `x-session-token` (the\n * signature IS the credential; an extra header breaks nothing but leaks the\n * token to a third-party host) and no JSON envelope.\n *\n * `contentType` is param-stripped here too (idempotent for bare types): the\n * presign strips internally, so a caller composing manually with the engine's\n * parameterful `clipMimeType` would otherwise sign `video/webm` but PUT\n * `video/webm;codecs=…` — a signed-header mismatch S3 rejects at runtime.\n *\n * Timeout: 15 min (`AbortSignal.timeout(900_000)`, matching the presign TTL)\n * rather than the API calls' 30 s — a 15 MB clip on a slow link legitimately\n * exceeds 30 s, but a stalled in-flight socket must still be bounded (the TTL\n * alone only bounds when a PUT can START).\n *\n * Failures are ALWAYS typed: non-2xx throws {@link HostedApiError} with the\n * client-synthesized `upload_failed` (message carries a truncated S3 body\n * snippet — e.g. SignatureDoesNotMatch); a mid-transfer drop → `network_error`;\n * the timeout → `timeout`.\n */\n async uploadToSpaces(uploadUrl: string, blob: Blob, contentType: string): Promise<void> {\n let res: Response;\n try {\n res = await this.fetchImpl(uploadUrl, {\n method: \"PUT\",\n headers: { \"content-type\": stripMimeParams(contentType) },\n body: blob,\n signal: AbortSignal.timeout(SPACES_PUT_TIMEOUT_MS),\n });\n } catch (err) {\n throw asTransportError(err);\n }\n if (!res.ok) {\n const snippet = (await res.text().catch(() => \"\")).slice(0, UPLOAD_ERROR_SNIPPET_CHARS);\n throw new HostedApiError({\n status: res.status,\n code: \"upload_failed\",\n message: `media upload failed (HTTP ${res.status})${snippet ? `: ${snippet}` : \"\"}`,\n });\n }\n }\n\n /** Finalize an upload: the backend sniffs + promotes; returns the PROMOTED key to submit. */\n async completeMedia(key: string): Promise<CompleteMediaResult> {\n const id = await this.ensureSessionId();\n return this.api<CompleteMediaResult>(\"POST\", `/sessions/${id}/media/complete`, {\n body: { key },\n });\n }\n\n /**\n * Submit one check. Sends `{input, forceOutcome?}` (SubmitCheckSchema) and the\n * optional `x-idempotency-key` header. Returns the whitelisted SessionView.\n */\n async submitCheck<T extends CheckType>(\n checkType: T,\n input: CheckInputByType[T],\n opts: SubmitOptions = {},\n ): Promise<SessionView> {\n const id = await this.ensureSessionId();\n const body: SubmitCheckBody = {\n input: input as unknown as Record<string, unknown>,\n ...(opts.forceOutcome !== undefined ? { forceOutcome: opts.forceOutcome } : {}),\n };\n return this.api<SessionView>(\"POST\", `/sessions/${id}/checks/${checkType}`, {\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n });\n }\n\n /**\n * Convenience composition: presign → PUT → complete → submit, passing the\n * PROMOTED key (from complete's response — never the pending presign key)\n * into the check's media input field (`clipKey` for liveness, `imageKey` for\n * face_match/doc_ocr). `extraInput` carries the remaining input fields\n * (liveness `attestation`, doc_ocr `side`). The media content type is\n * param-stripped ONCE and used for both presign and PUT, so the signed\n * header always matches.\n */\n async uploadAndSubmit<T extends MediaCheckType>(\n checkType: T,\n media: UploadMedia,\n extraInput: Omit<CheckInputByType[T], (typeof MEDIA_INPUT_FIELD)[T]>,\n opts: SubmitOptions = {},\n ): Promise<SessionView> {\n const bareType = stripMimeParams(media.contentType);\n const presigned = await this.presign(media.kind, bareType, media.blob.size);\n await this.uploadToSpaces(presigned.uploadUrl, media.blob, bareType);\n const completed = await this.completeMedia(presigned.key);\n const input = {\n ...extraInput,\n [MEDIA_INPUT_FIELD[checkType]]: completed.key,\n } as unknown as CheckInputByType[T];\n return this.submitCheck(checkType, input, opts);\n }\n\n // ── transport ──────────────────────────────────────────────────────────────\n\n /** The token's own sessionId — cached from getSession(), lazily bootstrapped. */\n private async ensureSessionId(): Promise<string> {\n if (this.sessionId !== null) return this.sessionId;\n // Dedupe concurrent bootstraps; reset on settle so a failure can be retried.\n this.bootstrap ??= this.getSession().finally(() => {\n this.bootstrap = null;\n });\n return (await this.bootstrap).sessionId;\n }\n\n /**\n * One API request: `${apiOrigin}/api/v2${path}`, `x-session-token` always,\n * AbortSignal timeout (30 s default), `{success, data}` unwrap on 2xx, flat\n * `{code, message}` → {@link HostedApiError} on non-2xx. EVERY failure is\n * typed: a rejected fetch → `network_error`, the timeout → `timeout`, an\n * unparseable 2xx body → `unknown_error` — the page never sees a raw\n * TypeError/DOMException. The ONLY automatic retry is 409\n * `idempotency_in_progress` (bounded, short delay).\n */\n private async api<T>(\n method: \"GET\" | \"POST\",\n path: string,\n opts: { body?: unknown; idempotencyKey?: string } = {},\n ): Promise<T> {\n const url = `${this.apiOrigin}/api/v2${path}`;\n const headers: Record<string, string> = { \"x-session-token\": this.sessionToken };\n if (opts.body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (opts.idempotencyKey !== undefined) headers[\"x-idempotency-key\"] = opts.idempotencyKey;\n\n for (let attempt = 0; ; attempt++) {\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method,\n headers,\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n });\n } catch (err) {\n throw asTransportError(err);\n }\n\n if (res.ok) {\n let raw: unknown;\n try {\n raw = await res.json();\n } catch {\n throw new HostedApiError({\n status: res.status,\n code: \"unknown_error\",\n message: `response body was not valid JSON (HTTP ${res.status})`,\n });\n }\n return unwrap<T>(raw);\n }\n\n const err = await parseErrorResponse(res);\n if (err.code === \"idempotency_in_progress\" && attempt < this.retryAttempts) {\n if (this.retryDelayMs > 0) await sleep(this.retryDelayMs);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Normalize a rejected fetch into the typed contract (status 0 — no response\n * arrived): AbortSignal.timeout aborts with a DOMException named 'TimeoutError'\n * → `timeout`; everything else (TypeError on connection drop / DNS / CORS /\n * mid-transfer failure) → `network_error`. Duck-typed on `.name` because\n * DOMException does not inherit Error in every environment (e.g. jsdom).\n */\nfunction asTransportError(err: unknown): HostedApiError {\n const name = typeof err === \"object\" && err !== null ? (err as { name?: unknown }).name : undefined;\n if (name === \"TimeoutError\") {\n return new HostedApiError({ status: 0, code: \"timeout\", message: \"request timed out\" });\n }\n const detail = err instanceof Error ? err.message : String(err);\n return new HostedApiError({\n status: 0,\n code: \"network_error\",\n message: `network request failed: ${detail}`,\n });\n}\n\n/**\n * Unwrap the global success envelope `{success: true, data}` (ResponseTransform-\n * Interceptor wraps every object body that lacks a `success` key). Defensive:\n * a body without the envelope is returned as-is.\n */\nfunction unwrap<T>(raw: unknown): T {\n if (raw !== null && typeof raw === \"object\" && \"success\" in raw && \"data\" in raw) {\n return (raw as { data: T }).data;\n }\n return raw as T;\n}\n\n/**\n * Parse a non-2xx response into a {@link HostedApiError}: the public envelope\n * is flat `{code, message}`; a non-JSON body (proxy HTML, etc.) degrades to the\n * client-synthesized `unknown_error`. `Retry-After` (seconds) is parsed when\n * present — rate-limit 429s always set it.\n */\nasync function parseErrorResponse(res: Response): Promise<HostedApiError> {\n let code = \"unknown_error\";\n let message = `request failed (HTTP ${res.status})`;\n try {\n const body: unknown = await res.json();\n if (body !== null && typeof body === \"object\") {\n const env = body as { code?: unknown; message?: unknown };\n if (typeof env.code === \"string\" && env.code.length > 0) code = env.code;\n if (typeof env.message === \"string\" && env.message.length > 0) message = env.message;\n }\n } catch {\n // Not JSON — keep the defensive fallback.\n }\n const retryAfterRaw = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterRaw === null ? Number.NaN : Number.parseInt(retryAfterRaw, 10);\n return new HostedApiError({\n status: res.status,\n code,\n message,\n ...(Number.isFinite(retryAfter) && retryAfter >= 0 ? { retryAfterSeconds: retryAfter } : {}),\n });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiCO,IAAM,cAAc;AAAA;AAAA,EAEzB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAMO,SAAS,YAAY,MAAiC;AAC3D,SAAQ,YAAkC,SAAS,IAAI;AACzD;AAgBO,I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,SAAS,2BAA2B,MAAM;AAAA,EAC5C,CAAC;AACH;AAOA,SAAS,OAAU,KAAiB;AAClC,MAAI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,aAAa,OAAO,UAAU,KAAK;AAChF,WAAQ,IAAoB;AAAA,EAC9B;AACA,SAAO;AACT;AAQA,eAAe,mBAAmB,KAAwC;AACxE,MAAI,OAAO;AACX,MAAI,UAAU,wBAAwB,IAAI,MAAM;AAChD,MAAI;AACF,UAAM,OAAgB,MAAM,IAAI,KAAK;AACrC,QAAI,SAAS,QAAQ,OAAO,SAAS,UAAU;AAC7C,YAAM,MAAM;AACZ,UAAI,OAAO,IAAI,SAAS,YAAY,IAAI,KAAK,SAAS,EAAG,QAAO,IAAI;AACpE,UAAI,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,SAAS,EAAG,WAAU,IAAI;AAAA,IAC/E;AAAA,EACF,QAAQ;AAAA,EAER;AACA,QAAM,gBAAgB,IAAI,QAAQ,IAAI,aAAa;AACnD,QAAM,aAAa,kBAAkB,OAAO,OAAO,MAAM,OAAO,SAAS,eAAe,EAAE;AAC1F,SAAO,IAAI,eAAe;AAAA,IACxB,QAAQ,IAAI;AAAA,IACZ;AAAA,IACA;AAAA,IACA,GAAI,OAAO,SAAS,UAAU,KAAK,cAAc,IAAI,EAAE,mBAAmB,WAAW,IAAI,CAAC;AAAA,EAC5F,CAAC;AACH;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":["err"]}
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessInput, L as LivenessReason, M as MediaCheckType,
|
|
1
|
+
export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessCaptureInput, q as LivenessInput, L as LivenessReason, M as MediaCheckType, r as MediaKind, s as PhoneOtpInput, P as PhoneOtpReason, t as PopulationInput, e as PopulationReason, u as PresignRequest, v as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, f as SessionStatus, w as SessionStepView, h as SessionView, x as SubmitCheckBody, y as SubmitOptions, U as UploadMedia, z as stripMimeParams } from '../hosted-client-DWzCRYJK.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Every error code the hosted page can receive from the session-token surface.
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessInput, L as LivenessReason, M as MediaCheckType,
|
|
1
|
+
export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessCaptureInput, q as LivenessInput, L as LivenessReason, M as MediaCheckType, r as MediaKind, s as PhoneOtpInput, P as PhoneOtpReason, t as PopulationInput, e as PopulationReason, u as PresignRequest, v as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, f as SessionStatus, w as SessionStepView, h as SessionView, x as SubmitCheckBody, y as SubmitOptions, U as UploadMedia, z as stripMimeParams } from '../hosted-client-DWzCRYJK.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Every error code the hosted page can receive from the session-token surface.
|