@sekyro/web 0.1.0-rc.3 → 0.1.0-rc.31
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 +433 -0
- package/LICENSE +25 -16
- package/README.md +157 -62
- package/THIRD-PARTY-NOTICES.txt +154 -0
- package/dist/background-monitor-A7FKJOAG.js +1 -0
- package/dist/barcode-detect-C5IOXMKI.js +1 -0
- package/dist/camera-trait-V4UAOPIQ.js +1 -0
- package/dist/capture-constraints-CVqpMNGA.d.cts +48 -0
- package/dist/capture-constraints-CVqpMNGA.d.ts +48 -0
- package/dist/capture-session-doc-2LIRRKFX.js +1 -0
- package/dist/{capture-session-v3-COIO_F2w.d.cts → capture-session-v3-Fbj-X2Ij.d.ts} +259 -13
- package/dist/{capture-session-v3-CvIfcwST.d.ts → capture-session-v3-XtBrXpoW.d.cts} +259 -13
- package/dist/challenge-frame-YAQJ5YMB.js +1 -0
- package/dist/chunk-2LDOXGY3.js +1 -0
- package/dist/chunk-2MX4J26D.js +3 -0
- package/dist/chunk-33KKMPJ5.js +1 -0
- package/dist/chunk-3K3A7O7J.js +1 -0
- package/dist/chunk-53POX7U4.js +1 -0
- package/dist/chunk-6ERQTXMY.js +1 -0
- package/dist/chunk-6Z4MIKGF.js +1 -0
- package/dist/chunk-7QZWBDI5.js +1 -0
- package/dist/chunk-CJHMFPL6.js +1 -0
- package/dist/chunk-CMXN4SOZ.js +1 -0
- package/dist/chunk-CPUECYAJ.js +1 -0
- package/dist/chunk-DFTCAWMP.js +1 -0
- package/dist/chunk-DK5YPBDQ.js +1 -0
- package/dist/chunk-FPXL63KZ.js +1 -0
- package/dist/chunk-FSSMUAKC.js +1 -0
- package/dist/chunk-G6LKLN4U.js +1 -0
- package/dist/chunk-GFJATPUR.js +1 -0
- package/dist/chunk-GI3UFGRQ.js +1 -0
- package/dist/chunk-GXL6ZD4I.js +1 -0
- package/dist/chunk-JLVZ35QK.js +2 -0
- package/dist/chunk-MD4YXLPK.js +1 -0
- package/dist/chunk-OUC57KMS.js +1 -0
- package/dist/chunk-POIQGEZM.js +1 -0
- package/dist/chunk-R3JMNYW5.js +1 -0
- package/dist/chunk-RI3E7GBN.js +1 -0
- package/dist/chunk-SMKCBUJL.js +1 -0
- package/dist/chunk-SUANHBF4.js +1 -0
- package/dist/chunk-SX7TUC3V.js +1 -0
- package/dist/chunk-TN4JWBFJ.js +1 -0
- package/dist/chunk-TSA6GHUG.js +1 -0
- package/dist/chunk-VWGKUQ3C.js +1 -0
- package/dist/chunk-XFDWFJLY.js +1 -0
- package/dist/chunk-ZKF2XMNX.js +1 -0
- package/dist/client/index.cjs +1 -357
- package/dist/client/index.d.cts +6 -37
- package/dist/client/index.d.ts +6 -37
- package/dist/client/index.js +1 -15
- package/dist/clip-inspect-DLJXVKV6.js +1 -0
- package/dist/core/index.cjs +1 -1606
- package/dist/core/index.d.cts +5 -4
- package/dist/core/index.d.ts +5 -4
- package/dist/core/index.js +1 -139
- package/dist/core/ocr/worker.bundle.js +42 -0
- package/dist/core/ocr/worker.cjs +42 -0
- package/dist/core/ocr/worker.d.cts +84 -0
- package/dist/core/ocr/worker.d.ts +84 -0
- package/dist/core/ocr/worker.js +41 -0
- package/dist/core/v3/detect-worker.cjs +1 -392
- package/dist/core/v3/detect-worker.d.cts +1 -1
- package/dist/core/v3/detect-worker.d.ts +1 -1
- package/dist/core/v3/detect-worker.js +1 -13
- package/dist/create-document-capture-X35M4UAK.js +1 -0
- package/dist/create-portrait-capture-5VGYZUOK.js +1 -0
- package/dist/create-verification-RdG6qv51.d.ts +3732 -0
- package/dist/create-verification-lXGU3ac4.d.cts +3732 -0
- package/dist/{detect-worker-CKXHlXx9.d.ts → detect-worker-CHqsPJoM.d.cts} +25 -2
- package/dist/{detect-worker-CKXHlXx9.d.cts → detect-worker-CHqsPJoM.d.ts} +25 -2
- package/dist/detector-scanic-KMAVOHGF.js +1 -0
- package/dist/icao-gate-Cp1C4IEZ.d.ts +578 -0
- package/dist/icao-gate-DVNkPclI.d.cts +578 -0
- package/dist/icao-gate-T3BTOKFJ.js +1 -0
- package/dist/icao-policy-CcrwfsVr.d.ts +80 -0
- package/dist/icao-policy-c2Ykm9r2.d.cts +80 -0
- package/dist/icao-tuning-4ETMF53W.js +1 -0
- package/dist/index.cjs +3 -2649
- package/dist/index.d.cts +138 -5
- package/dist/index.d.ts +138 -5
- package/dist/index.js +1 -28
- package/dist/internal/index.cjs +3 -4179
- package/dist/internal/index.d.cts +390 -371
- package/dist/internal/index.d.ts +390 -371
- package/dist/internal/index.js +1 -647
- package/dist/keyframe-rank-YAJLYJYF.js +1 -0
- package/dist/landmarker-KB7LVXAU.js +1 -0
- package/dist/mrz-band-VYHOTDHY.js +1 -0
- package/dist/plan-runner-T2ZTSBI4.js +1 -0
- package/dist/popup/index.cjs +1 -76
- package/dist/popup/index.d.cts +9 -3
- package/dist/popup/index.d.ts +9 -3
- package/dist/popup/index.js +1 -11
- package/dist/print-SEWS3VHQ.js +1 -0
- package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
- package/dist/segmenter-USLNBX65.js +1 -0
- package/dist/types-B47mZ5TT.d.cts +2107 -0
- package/dist/types-B47mZ5TT.d.ts +2107 -0
- package/dist/upload-file-EGXXM6TQ.js +1 -0
- package/package.json +30 -11
- package/sbom.cdx.json +349 -0
- package/dist/capture-constraints-BujkZcfb.d.cts +0 -21
- package/dist/capture-constraints-BujkZcfb.d.ts +0 -21
- package/dist/chunk-7TC6TOZ4.js +0 -1095
- package/dist/chunk-7TC6TOZ4.js.map +0 -1
- package/dist/chunk-FIXX2AXC.js +0 -864
- package/dist/chunk-FIXX2AXC.js.map +0 -1
- package/dist/chunk-MWNFSNMP.js +0 -52
- package/dist/chunk-MWNFSNMP.js.map +0 -1
- package/dist/chunk-NILNKLK6.js +0 -50
- package/dist/chunk-NILNKLK6.js.map +0 -1
- package/dist/chunk-NWF46H7K.js +0 -359
- package/dist/chunk-NWF46H7K.js.map +0 -1
- package/dist/chunk-WY6U7AIK.js +0 -193
- package/dist/chunk-WY6U7AIK.js.map +0 -1
- package/dist/chunk-YVFF4Q4G.js +0 -327
- package/dist/chunk-YVFF4Q4G.js.map +0 -1
- package/dist/client/index.cjs.map +0 -1
- package/dist/client/index.js.map +0 -1
- package/dist/core/index.cjs.map +0 -1
- package/dist/core/index.js.map +0 -1
- package/dist/core/v3/detect-worker.cjs.map +0 -1
- package/dist/core/v3/detect-worker.js.map +0 -1
- package/dist/create-verification-CP18eq1Q.d.cts +0 -348
- package/dist/create-verification-CswF2As-.d.ts +0 -348
- package/dist/detector-scanic-4C6IEW2K.js +0 -787
- package/dist/detector-scanic-4C6IEW2K.js.map +0 -1
- package/dist/hosted-client-BpvBqu9f.d.cts +0 -408
- package/dist/hosted-client-BpvBqu9f.d.ts +0 -408
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/internal/index.cjs.map +0 -1
- package/dist/internal/index.js.map +0 -1
- package/dist/popup/index.cjs.map +0 -1
- package/dist/popup/index.js.map +0 -1
- package/dist/scanic-ml-stub-S2OZ6HEF.js +0 -10
- package/dist/scanic-ml-stub-S2OZ6HEF.js.map +0 -1
package/dist/core/index.cjs
CHANGED
|
@@ -1,1606 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/core/index.ts
|
|
31
|
-
var core_exports = {};
|
|
32
|
-
__export(core_exports, {
|
|
33
|
-
CENTERED_FACTOR: () => CENTERED_FACTOR,
|
|
34
|
-
CIRCLE_RADIUS_FACTOR: () => CIRCLE_RADIUS_FACTOR,
|
|
35
|
-
CLIP_MS: () => CLIP_MS,
|
|
36
|
-
CaptureSessionV3: () => CaptureSessionV3,
|
|
37
|
-
ClipError: () => ClipError,
|
|
38
|
-
ClipRecorder: () => ClipRecorder,
|
|
39
|
-
DEFAULT_CLIP_MIME: () => DEFAULT_CLIP_MIME,
|
|
40
|
-
DEFAULT_TIER_ORDER: () => DEFAULT_TIER_ORDER,
|
|
41
|
-
DEFAULT_V3_ASSET_BASE_URL: () => DEFAULT_V3_ASSET_BASE_URL,
|
|
42
|
-
DEVICE_PROFILES: () => DEVICE_PROFILES,
|
|
43
|
-
DetectScheduler: () => DetectScheduler,
|
|
44
|
-
DetectorLadderError: () => DetectorLadderError,
|
|
45
|
-
DeviceProfiler: () => DeviceProfiler,
|
|
46
|
-
EXPOSURE_BAND: () => EXPOSURE_BAND,
|
|
47
|
-
FaceGateV3: () => FaceGateV3,
|
|
48
|
-
IN_CIRCLE_FACTOR: () => IN_CIRCLE_FACTOR,
|
|
49
|
-
KEYFRAME_CANDIDATES: () => KEYFRAME_CANDIDATES,
|
|
50
|
-
KEYFRAME_WINDOW_MS: () => KEYFRAME_WINDOW_MS,
|
|
51
|
-
MAX_CLIP_BYTES: () => MAX_CLIP_BYTES,
|
|
52
|
-
MIME_CANDIDATES: () => MIME_CANDIDATES,
|
|
53
|
-
SHARP_REF: () => SHARP_REF,
|
|
54
|
-
STOP_GRACE_MS: () => STOP_GRACE_MS,
|
|
55
|
-
TIMESLICE_MS: () => TIMESLICE_MS,
|
|
56
|
-
V3_GATE_DEFAULTS: () => V3_GATE_DEFAULTS,
|
|
57
|
-
VIDEO_BPS: () => VIDEO_BPS,
|
|
58
|
-
buildCaptureConstraints: () => buildCaptureConstraints,
|
|
59
|
-
buildLivenessV2FormData: () => buildLivenessV2FormData,
|
|
60
|
-
cameraPreflight: () => cameraPreflight,
|
|
61
|
-
captureMirroredKeyframe: () => captureMirroredKeyframe,
|
|
62
|
-
classifyDevice: () => classifyDevice,
|
|
63
|
-
createDetector: () => createDetector,
|
|
64
|
-
detectIsMobile: () => detectIsMobile,
|
|
65
|
-
errorCopy: () => errorCopy,
|
|
66
|
-
exposure: () => exposure,
|
|
67
|
-
extForMime: () => extForMime,
|
|
68
|
-
intrinsicSize: () => intrinsicSize,
|
|
69
|
-
isClipTooLarge: () => isClipTooLarge,
|
|
70
|
-
isMediaRecorderSupported: () => isMediaRecorderSupported,
|
|
71
|
-
mapGetUserMediaError: () => mapGetUserMediaError,
|
|
72
|
-
meanLuma: () => meanLuma,
|
|
73
|
-
pickMimeType: () => pickMimeType,
|
|
74
|
-
probeDevice: () => probeDevice,
|
|
75
|
-
sharpness: () => sharpness,
|
|
76
|
-
toStreamPixels: () => toStreamPixels,
|
|
77
|
-
uiCopy: () => uiCopy
|
|
78
|
-
});
|
|
79
|
-
module.exports = __toCommonJS(core_exports);
|
|
80
|
-
|
|
81
|
-
// src/core/media.ts
|
|
82
|
-
var MIME_CANDIDATES = [
|
|
83
|
-
"video/mp4;codecs=avc1.42E01E,mp4a.40.2",
|
|
84
|
-
"video/mp4;codecs=avc1.42E01E",
|
|
85
|
-
"video/mp4",
|
|
86
|
-
"video/webm;codecs=vp9,opus",
|
|
87
|
-
"video/webm;codecs=vp9",
|
|
88
|
-
"video/webm;codecs=vp8,opus",
|
|
89
|
-
"video/webm;codecs=vp8",
|
|
90
|
-
"video/webm"
|
|
91
|
-
];
|
|
92
|
-
function pickMimeType() {
|
|
93
|
-
const MR = globalThis.MediaRecorder;
|
|
94
|
-
if (!MR || typeof MR.isTypeSupported !== "function") return "";
|
|
95
|
-
return MIME_CANDIDATES.find((t) => MR.isTypeSupported(t)) ?? "";
|
|
96
|
-
}
|
|
97
|
-
var DEFAULT_CLIP_MIME = "video/webm";
|
|
98
|
-
function mapGetUserMediaError(err) {
|
|
99
|
-
if (err instanceof TypeError) return "insecure";
|
|
100
|
-
const name = err?.name ?? "";
|
|
101
|
-
switch (name) {
|
|
102
|
-
case "NotAllowedError":
|
|
103
|
-
case "PermissionDeniedError":
|
|
104
|
-
return "permission";
|
|
105
|
-
case "NotFoundError":
|
|
106
|
-
case "DevicesNotFoundError":
|
|
107
|
-
return "notfound";
|
|
108
|
-
case "NotReadableError":
|
|
109
|
-
case "TrackStartError":
|
|
110
|
-
return "inuse";
|
|
111
|
-
case "OverconstrainedError":
|
|
112
|
-
case "ConstraintNotSatisfiedError":
|
|
113
|
-
return "overconstrained";
|
|
114
|
-
default:
|
|
115
|
-
return "generic";
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
function cameraPreflight() {
|
|
119
|
-
const w = globalThis;
|
|
120
|
-
if (typeof w.window !== "undefined" && w.window.isSecureContext === false)
|
|
121
|
-
return "INSECURE_CONTEXT";
|
|
122
|
-
const md = w.navigator?.mediaDevices;
|
|
123
|
-
if (!md || typeof md.getUserMedia !== "function") return "UNSUPPORTED";
|
|
124
|
-
return "OK";
|
|
125
|
-
}
|
|
126
|
-
function isMediaRecorderSupported() {
|
|
127
|
-
const MR = globalThis.MediaRecorder;
|
|
128
|
-
return typeof MR !== "undefined" && typeof MR.isTypeSupported === "function";
|
|
129
|
-
}
|
|
130
|
-
var MAX_CLIP_BYTES = 8 * 1024 * 1024;
|
|
131
|
-
function isClipTooLarge(blob) {
|
|
132
|
-
return blob.size > MAX_CLIP_BYTES;
|
|
133
|
-
}
|
|
134
|
-
function extForMime(mime) {
|
|
135
|
-
const m = (mime || "").toLowerCase();
|
|
136
|
-
if (m.startsWith("image/jpeg")) return "jpg";
|
|
137
|
-
if (m.startsWith("video/mp4")) return "mp4";
|
|
138
|
-
if (m.startsWith("video/webm")) return "webm";
|
|
139
|
-
return "webm";
|
|
140
|
-
}
|
|
141
|
-
function buildLivenessV2FormData(args) {
|
|
142
|
-
const { token, clip, keyframe } = args;
|
|
143
|
-
const ts = args.ts ?? Date.now();
|
|
144
|
-
const clipType = clip.type || DEFAULT_CLIP_MIME;
|
|
145
|
-
const kfType = keyframe.type || "image/jpeg";
|
|
146
|
-
const fd = new FormData();
|
|
147
|
-
fd.append("token", token);
|
|
148
|
-
fd.append("clip", new File([clip], `liveness-${ts}.${extForMime(clipType)}`, { type: clipType }));
|
|
149
|
-
fd.append("keyframe", new File([keyframe], `keyframe-${ts}.${extForMime(kfType)}`, { type: kfType }));
|
|
150
|
-
return fd;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// src/core/keyframe.ts
|
|
154
|
-
function captureMirroredKeyframe(video, canvas, quality = 0.92) {
|
|
155
|
-
return new Promise((resolve, reject) => {
|
|
156
|
-
const w = video.videoWidth;
|
|
157
|
-
const h = video.videoHeight;
|
|
158
|
-
if (!w || !h) {
|
|
159
|
-
reject(new Error("video-not-ready"));
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
|
-
const ctx = canvas.getContext("2d");
|
|
163
|
-
if (!ctx) {
|
|
164
|
-
reject(new Error("no-2d-context"));
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
canvas.width = w;
|
|
168
|
-
canvas.height = h;
|
|
169
|
-
ctx.scale(-1, 1);
|
|
170
|
-
ctx.drawImage(video, -w, 0);
|
|
171
|
-
canvas.toBlob(
|
|
172
|
-
(blob) => blob ? resolve(blob) : reject(new Error("empty-keyframe")),
|
|
173
|
-
"image/jpeg",
|
|
174
|
-
quality
|
|
175
|
-
);
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// src/core/messages.ts
|
|
180
|
-
var errorCopy = {
|
|
181
|
-
permission: {
|
|
182
|
-
key: "fcv2.err.permission",
|
|
183
|
-
fr: "Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."
|
|
184
|
-
},
|
|
185
|
-
notfound: {
|
|
186
|
-
key: "fcv2.err.notfound",
|
|
187
|
-
fr: "Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."
|
|
188
|
-
},
|
|
189
|
-
inuse: {
|
|
190
|
-
key: "fcv2.err.inuse",
|
|
191
|
-
fr: "La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."
|
|
192
|
-
},
|
|
193
|
-
overconstrained: {
|
|
194
|
-
key: "fcv2.err.overconstrained",
|
|
195
|
-
fr: "La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"
|
|
196
|
-
},
|
|
197
|
-
insecure: {
|
|
198
|
-
key: "fcv2.err.insecure",
|
|
199
|
-
fr: "La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."
|
|
200
|
-
},
|
|
201
|
-
unsupported: {
|
|
202
|
-
key: "fcv2.err.unsupported",
|
|
203
|
-
fr: "Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."
|
|
204
|
-
},
|
|
205
|
-
generic: {
|
|
206
|
-
key: "fcv2.err.generic",
|
|
207
|
-
fr: "Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."
|
|
208
|
-
}
|
|
209
|
-
};
|
|
210
|
-
var uiCopy = {
|
|
211
|
-
recording: { key: "fcv2.recording", fr: "Enregistrement en cours\u2026" },
|
|
212
|
-
uploading: { key: "fcv2.uploading", fr: "Envoi en cours\u2026" },
|
|
213
|
-
clipTooLarge: {
|
|
214
|
-
key: "fcv2.err.cliptoolarge",
|
|
215
|
-
fr: "La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."
|
|
216
|
-
},
|
|
217
|
-
retry: { key: "fcv2.retry", fr: "R\xE9essayer" },
|
|
218
|
-
listen: { key: "fcv2.listen", fr: "\xC9couter" }
|
|
219
|
-
};
|
|
220
|
-
|
|
221
|
-
// src/core/clip-recorder.ts
|
|
222
|
-
var CLIP_MS = 2500;
|
|
223
|
-
var TIMESLICE_MS = 1e3;
|
|
224
|
-
var STOP_GRACE_MS = 1500;
|
|
225
|
-
var VIDEO_BPS = 25e5;
|
|
226
|
-
var ClipError = class extends Error {
|
|
227
|
-
constructor(kind, msg) {
|
|
228
|
-
super(msg ?? kind);
|
|
229
|
-
this.kind = kind;
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
var ClipRecorder = class {
|
|
233
|
-
constructor() {
|
|
234
|
-
this.recorder = null;
|
|
235
|
-
this.stream = null;
|
|
236
|
-
// own field so teardown can stop tracks (REVIEW FIX 8)
|
|
237
|
-
this.chunks = [];
|
|
238
|
-
this.bytes = 0;
|
|
239
|
-
this.hardStopTimer = null;
|
|
240
|
-
this.graceTimer = null;
|
|
241
|
-
this.settled = false;
|
|
242
|
-
}
|
|
243
|
-
clearTimers() {
|
|
244
|
-
if (this.hardStopTimer) clearTimeout(this.hardStopTimer);
|
|
245
|
-
if (this.graceTimer) clearTimeout(this.graceTimer);
|
|
246
|
-
this.hardStopTimer = null;
|
|
247
|
-
this.graceTimer = null;
|
|
248
|
-
}
|
|
249
|
-
/** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;
|
|
250
|
-
* rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim
|
|
251
|
-
* (iOS workarounds included).
|
|
252
|
-
*
|
|
253
|
-
* ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a
|
|
254
|
-
* second record() while one is in flight rejects ClipError("generic") instead of
|
|
255
|
-
* corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning
|
|
256
|
-
* component; a class API invites reuse. Zero impact on clip bytes.)
|
|
257
|
-
*
|
|
258
|
-
* `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window
|
|
259
|
-
* elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to
|
|
260
|
-
* STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze
|
|
261
|
-
* the display on the already-captured keyframe the instant recording ends,
|
|
262
|
-
* instead of waiting for the blob. PURE NOTIFICATION — it does not touch
|
|
263
|
-
* timers, chunks, or the finalize path, so it is calibration-neutral (no
|
|
264
|
-
* effect on clip bytes). Never fires on a rejected capture (error /
|
|
265
|
-
* cliptoolarge settle before the hard-stop and clear the timer). */
|
|
266
|
-
record(stream, onStopped) {
|
|
267
|
-
if (this.recorder && !this.settled) {
|
|
268
|
-
return Promise.reject(
|
|
269
|
-
new ClipError(
|
|
270
|
-
"generic",
|
|
271
|
-
"record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"
|
|
272
|
-
)
|
|
273
|
-
);
|
|
274
|
-
}
|
|
275
|
-
this.recorder = null;
|
|
276
|
-
this.clearTimers();
|
|
277
|
-
this.chunks = [];
|
|
278
|
-
this.bytes = 0;
|
|
279
|
-
this.settled = false;
|
|
280
|
-
this.stream = stream;
|
|
281
|
-
const picked = pickMimeType();
|
|
282
|
-
return new Promise((resolve, reject) => {
|
|
283
|
-
let recorder;
|
|
284
|
-
try {
|
|
285
|
-
recorder = new MediaRecorder(
|
|
286
|
-
stream,
|
|
287
|
-
picked ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS } : { videoBitsPerSecond: VIDEO_BPS }
|
|
288
|
-
);
|
|
289
|
-
} catch {
|
|
290
|
-
try {
|
|
291
|
-
recorder = new MediaRecorder(stream);
|
|
292
|
-
} catch {
|
|
293
|
-
reject(new ClipError("unsupported"));
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
this.recorder = recorder;
|
|
298
|
-
const settle = (fn) => {
|
|
299
|
-
if (this.settled) return;
|
|
300
|
-
this.settled = true;
|
|
301
|
-
this.clearTimers();
|
|
302
|
-
fn();
|
|
303
|
-
};
|
|
304
|
-
const finalize = () => settle(() => {
|
|
305
|
-
const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;
|
|
306
|
-
const blob = new Blob(this.chunks, { type });
|
|
307
|
-
if (isClipTooLarge(blob)) {
|
|
308
|
-
reject(new ClipError("cliptoolarge"));
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
resolve({ blob, mimeType: type });
|
|
312
|
-
});
|
|
313
|
-
recorder.ondataavailable = (e) => {
|
|
314
|
-
if (e.data && e.data.size) {
|
|
315
|
-
this.chunks.push(e.data);
|
|
316
|
-
this.bytes += e.data.size;
|
|
317
|
-
if (this.bytes > MAX_CLIP_BYTES) {
|
|
318
|
-
settle(() => {
|
|
319
|
-
try {
|
|
320
|
-
if (recorder.state !== "inactive") recorder.stop();
|
|
321
|
-
} catch {
|
|
322
|
-
}
|
|
323
|
-
reject(new ClipError("cliptoolarge"));
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
};
|
|
328
|
-
recorder.onstop = finalize;
|
|
329
|
-
recorder.onerror = () => settle(() => reject(new ClipError("generic")));
|
|
330
|
-
try {
|
|
331
|
-
recorder.start(TIMESLICE_MS);
|
|
332
|
-
} catch {
|
|
333
|
-
settle(() => reject(new ClipError("generic")));
|
|
334
|
-
return;
|
|
335
|
-
}
|
|
336
|
-
this.hardStopTimer = setTimeout(() => {
|
|
337
|
-
if (!this.settled) onStopped?.();
|
|
338
|
-
if (recorder.state !== "inactive") {
|
|
339
|
-
try {
|
|
340
|
-
recorder.stop();
|
|
341
|
-
} catch {
|
|
342
|
-
finalize();
|
|
343
|
-
}
|
|
344
|
-
this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);
|
|
345
|
-
} else {
|
|
346
|
-
finalize();
|
|
347
|
-
}
|
|
348
|
-
}, CLIP_MS);
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
/** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount
|
|
352
|
-
* effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.
|
|
353
|
-
*
|
|
354
|
-
* MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in
|
|
355
|
-
* flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()
|
|
356
|
-
* fires onstop → finalize from whatever chunks arrived so far), or — because this
|
|
357
|
-
* method clears the hard-stop/grace timers — never settle it at all if onstop never
|
|
358
|
-
* fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution
|
|
359
|
-
* arriving after stop() as a full CLIP_MS clip, and must not await a record()
|
|
360
|
-
* promise past stop() without their own timeout. (Task 4's CaptureSession owns
|
|
361
|
-
* sequencing on top of this contract.) */
|
|
362
|
-
stop(stream) {
|
|
363
|
-
this.clearTimers();
|
|
364
|
-
const rec = this.recorder;
|
|
365
|
-
if (rec && rec.state !== "inactive") {
|
|
366
|
-
try {
|
|
367
|
-
rec.stop();
|
|
368
|
-
} catch {
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
this.recorder = null;
|
|
372
|
-
const s = stream ?? this.stream;
|
|
373
|
-
s?.getTracks().forEach((t) => t.stop());
|
|
374
|
-
this.stream = null;
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
|
|
378
|
-
// src/core/capture-constraints.ts
|
|
379
|
-
function buildCaptureConstraints(isMobile, facingMode) {
|
|
380
|
-
void isMobile;
|
|
381
|
-
return {
|
|
382
|
-
video: {
|
|
383
|
-
width: { ideal: 1280, max: 1280 },
|
|
384
|
-
height: { ideal: 720, max: 720 },
|
|
385
|
-
facingMode,
|
|
386
|
-
frameRate: { ideal: 24, max: 30 }
|
|
387
|
-
},
|
|
388
|
-
audio: false
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
function detectIsMobile() {
|
|
392
|
-
if (typeof window === "undefined" || typeof navigator === "undefined") return false;
|
|
393
|
-
return window.innerWidth <= 768 || /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
|
394
|
-
String(navigator.userAgent ?? "")
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
var CIRCLE_RADIUS_FACTOR = 0.45;
|
|
398
|
-
var IN_CIRCLE_FACTOR = 0.9;
|
|
399
|
-
var CENTERED_FACTOR = 0.4;
|
|
400
|
-
|
|
401
|
-
// src/core/v3/detector-blaze.ts
|
|
402
|
-
var BLAZE_INIT_TIMEOUT_MS = 1e4;
|
|
403
|
-
var BlazeDetector = class _BlazeDetector {
|
|
404
|
-
constructor(inner, fallbackReason) {
|
|
405
|
-
this.tier = "blaze";
|
|
406
|
-
this.inner = inner;
|
|
407
|
-
if (fallbackReason !== void 0) this.fallbackReason = fallbackReason;
|
|
408
|
-
}
|
|
409
|
-
static async create(assetBaseUrl, fallbackReason) {
|
|
410
|
-
const vision = await import("@mediapipe/tasks-vision");
|
|
411
|
-
const fileset = await vision.FilesetResolver.forVisionTasks(assetBaseUrl);
|
|
412
|
-
const inner = await vision.FaceDetector.createFromOptions(fileset, {
|
|
413
|
-
baseOptions: {
|
|
414
|
-
modelAssetPath: `${assetBaseUrl}/blaze_face_short_range.tflite`,
|
|
415
|
-
// CPU delegate — the iOS-Safari-safe path (see header). NEVER 'GPU'.
|
|
416
|
-
delegate: "CPU"
|
|
417
|
-
},
|
|
418
|
-
runningMode: "IMAGE"
|
|
419
|
-
});
|
|
420
|
-
return new _BlazeDetector(inner, fallbackReason);
|
|
421
|
-
}
|
|
422
|
-
async detect(source, sourceWidth, sourceHeight) {
|
|
423
|
-
let detections;
|
|
424
|
-
try {
|
|
425
|
-
detections = this.inner.detect(source).detections;
|
|
426
|
-
} catch {
|
|
427
|
-
return null;
|
|
428
|
-
}
|
|
429
|
-
const best = pickMostConfident(detections);
|
|
430
|
-
if (best?.boundingBox === void 0) return null;
|
|
431
|
-
const size = intrinsicSize(source);
|
|
432
|
-
const eyes = extractEyes(best.keypoints, size);
|
|
433
|
-
const observation = {
|
|
434
|
-
box: {
|
|
435
|
-
x: best.boundingBox.originX,
|
|
436
|
-
y: best.boundingBox.originY,
|
|
437
|
-
width: best.boundingBox.width,
|
|
438
|
-
height: best.boundingBox.height
|
|
439
|
-
},
|
|
440
|
-
...eyes !== void 0 ? { eyes } : {},
|
|
441
|
-
score: best.categories[0]?.score ?? 0
|
|
442
|
-
};
|
|
443
|
-
return toStreamPixels(observation, source, sourceWidth, sourceHeight);
|
|
444
|
-
}
|
|
445
|
-
destroy() {
|
|
446
|
-
try {
|
|
447
|
-
this.inner.close();
|
|
448
|
-
} catch {
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
};
|
|
452
|
-
function pickMostConfident(detections) {
|
|
453
|
-
let best;
|
|
454
|
-
let bestScore = -1;
|
|
455
|
-
for (const detection of detections) {
|
|
456
|
-
const score = detection.categories[0]?.score ?? 0;
|
|
457
|
-
if (score > bestScore) {
|
|
458
|
-
best = detection;
|
|
459
|
-
bestScore = score;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
return best;
|
|
463
|
-
}
|
|
464
|
-
function extractEyes(keypoints, size) {
|
|
465
|
-
const a = keypoints?.[0];
|
|
466
|
-
const b = keypoints?.[1];
|
|
467
|
-
if (a === void 0 || b === void 0) return void 0;
|
|
468
|
-
const toSource = (p) => ({ x: p.x * size.width, y: p.y * size.height });
|
|
469
|
-
const [pa, pb] = [toSource(a), toSource(b)];
|
|
470
|
-
return pa.x <= pb.x ? { left: pa, right: pb } : { left: pb, right: pa };
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// src/core/v3/detector-native.ts
|
|
474
|
-
function smokeSource() {
|
|
475
|
-
if (typeof OffscreenCanvas === "function") return new OffscreenCanvas(2, 2);
|
|
476
|
-
const canvas = document.createElement("canvas");
|
|
477
|
-
canvas.width = 2;
|
|
478
|
-
canvas.height = 2;
|
|
479
|
-
return canvas;
|
|
480
|
-
}
|
|
481
|
-
async function probeNativeDetector() {
|
|
482
|
-
const ctor = globalThis.FaceDetector;
|
|
483
|
-
if (typeof ctor !== "function") return { ok: false, reason: "unsupported" };
|
|
484
|
-
try {
|
|
485
|
-
const instance = new ctor({ fastMode: true, maxDetectedFaces: 1 });
|
|
486
|
-
await instance.detect(smokeSource());
|
|
487
|
-
return { ok: true, instance };
|
|
488
|
-
} catch (err) {
|
|
489
|
-
return { ok: false, reason: `smoke_failed:${err instanceof Error ? err.message : String(err)}` };
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
var NativeDetector = class {
|
|
493
|
-
constructor(inner, fallbackReason) {
|
|
494
|
-
this.tier = "native";
|
|
495
|
-
this.inner = inner;
|
|
496
|
-
if (fallbackReason !== void 0) this.fallbackReason = fallbackReason;
|
|
497
|
-
}
|
|
498
|
-
async detect(source, sourceWidth, sourceHeight) {
|
|
499
|
-
let faces;
|
|
500
|
-
try {
|
|
501
|
-
faces = await this.inner.detect(source);
|
|
502
|
-
} catch {
|
|
503
|
-
return null;
|
|
504
|
-
}
|
|
505
|
-
const face = faces[0];
|
|
506
|
-
if (face === void 0) return null;
|
|
507
|
-
const eyes = extractEyes2(face.landmarks);
|
|
508
|
-
const observation = {
|
|
509
|
-
box: {
|
|
510
|
-
x: face.boundingBox.x,
|
|
511
|
-
y: face.boundingBox.y,
|
|
512
|
-
width: face.boundingBox.width,
|
|
513
|
-
height: face.boundingBox.height
|
|
514
|
-
},
|
|
515
|
-
...eyes !== void 0 ? { eyes } : {},
|
|
516
|
-
// The Shape Detection API exposes no confidence — the smoke-tested
|
|
517
|
-
// native tier treats any detection as confident.
|
|
518
|
-
score: 1
|
|
519
|
-
};
|
|
520
|
-
return toStreamPixels(observation, source, sourceWidth, sourceHeight);
|
|
521
|
-
}
|
|
522
|
-
destroy() {
|
|
523
|
-
}
|
|
524
|
-
};
|
|
525
|
-
function extractEyes2(landmarks) {
|
|
526
|
-
if (landmarks === void 0) return void 0;
|
|
527
|
-
const eyePoints = landmarks.filter((landmark) => landmark.type === "eye").map((landmark) => landmark.locations[0]).filter((point) => point !== void 0);
|
|
528
|
-
const [a, b] = eyePoints;
|
|
529
|
-
if (a === void 0 || b === void 0) return void 0;
|
|
530
|
-
return a.x <= b.x ? { left: a, right: b } : { left: b, right: a };
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// src/core/v3/detector.ts
|
|
534
|
-
var DEFAULT_V3_ASSET_BASE_URL = "/models-v3";
|
|
535
|
-
var DEFAULT_TIER_ORDER = ["native", "blaze"];
|
|
536
|
-
var DetectorLadderError = class extends Error {
|
|
537
|
-
constructor(fallbackReason) {
|
|
538
|
-
super(`no detector tier available (${fallbackReason})`);
|
|
539
|
-
this.name = "DetectorLadderError";
|
|
540
|
-
this.fallbackReason = fallbackReason;
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
function intrinsicSize(source) {
|
|
544
|
-
const candidate = source;
|
|
545
|
-
if (typeof candidate.videoWidth === "number" && candidate.videoWidth > 0) {
|
|
546
|
-
return { width: candidate.videoWidth, height: candidate.videoHeight ?? 0 };
|
|
547
|
-
}
|
|
548
|
-
if (typeof candidate.naturalWidth === "number" && candidate.naturalWidth > 0) {
|
|
549
|
-
return { width: candidate.naturalWidth, height: candidate.naturalHeight ?? 0 };
|
|
550
|
-
}
|
|
551
|
-
const width = typeof candidate.width === "number" ? candidate.width : 0;
|
|
552
|
-
const height = typeof candidate.height === "number" ? candidate.height : 0;
|
|
553
|
-
return { width, height };
|
|
554
|
-
}
|
|
555
|
-
function toStreamPixels(observation, source, streamWidth, streamHeight) {
|
|
556
|
-
const size = intrinsicSize(source);
|
|
557
|
-
const scaleX = size.width > 0 ? streamWidth / size.width : 1;
|
|
558
|
-
const scaleY = size.height > 0 ? streamHeight / size.height : 1;
|
|
559
|
-
const scalePoint = (p) => ({ x: p.x * scaleX, y: p.y * scaleY });
|
|
560
|
-
return {
|
|
561
|
-
box: {
|
|
562
|
-
x: observation.box.x * scaleX,
|
|
563
|
-
y: observation.box.y * scaleY,
|
|
564
|
-
width: observation.box.width * scaleX,
|
|
565
|
-
height: observation.box.height * scaleY
|
|
566
|
-
},
|
|
567
|
-
...observation.eyes !== void 0 ? { eyes: { left: scalePoint(observation.eyes.left), right: scalePoint(observation.eyes.right) } } : {},
|
|
568
|
-
score: observation.score
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
function describeError(err) {
|
|
572
|
-
return err instanceof Error ? err.message : String(err);
|
|
573
|
-
}
|
|
574
|
-
async function createDetector(options) {
|
|
575
|
-
const order = options.preferred ?? DEFAULT_TIER_ORDER;
|
|
576
|
-
const reasons = [];
|
|
577
|
-
for (const tier of order) {
|
|
578
|
-
if (tier === "native") {
|
|
579
|
-
const probed = await probeNativeDetector();
|
|
580
|
-
if (probed.ok) {
|
|
581
|
-
return new NativeDetector(probed.instance, reasonOf(reasons));
|
|
582
|
-
}
|
|
583
|
-
reasons.push(`native:${probed.reason}`);
|
|
584
|
-
continue;
|
|
585
|
-
}
|
|
586
|
-
try {
|
|
587
|
-
return await withTimeout(
|
|
588
|
-
BlazeDetector.create(
|
|
589
|
-
options.v3AssetBaseUrl ?? DEFAULT_V3_ASSET_BASE_URL,
|
|
590
|
-
reasonOf(reasons)
|
|
591
|
-
),
|
|
592
|
-
options.blazeInitTimeoutMs ?? BLAZE_INIT_TIMEOUT_MS
|
|
593
|
-
);
|
|
594
|
-
} catch (err) {
|
|
595
|
-
reasons.push(
|
|
596
|
-
err instanceof InitTimeoutError ? "blaze:blaze_init_timeout" : `blaze:${describeError(err)}`
|
|
597
|
-
);
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
throw new DetectorLadderError(reasonOf(reasons) ?? "no_tier_available");
|
|
601
|
-
}
|
|
602
|
-
function reasonOf(reasons) {
|
|
603
|
-
return reasons.length > 0 ? reasons.join("; ") : void 0;
|
|
604
|
-
}
|
|
605
|
-
var InitTimeoutError = class extends Error {
|
|
606
|
-
};
|
|
607
|
-
function withTimeout(promise, deadlineMs) {
|
|
608
|
-
return new Promise((resolvePromise, rejectPromise) => {
|
|
609
|
-
const timer = setTimeout(() => {
|
|
610
|
-
rejectPromise(new InitTimeoutError(`init exceeded ${deadlineMs}ms`));
|
|
611
|
-
promise.then(
|
|
612
|
-
(value) => value.destroy(),
|
|
613
|
-
() => void 0
|
|
614
|
-
);
|
|
615
|
-
}, deadlineMs);
|
|
616
|
-
promise.then(
|
|
617
|
-
(value) => {
|
|
618
|
-
clearTimeout(timer);
|
|
619
|
-
resolvePromise(value);
|
|
620
|
-
},
|
|
621
|
-
(err) => {
|
|
622
|
-
clearTimeout(timer);
|
|
623
|
-
rejectPromise(err);
|
|
624
|
-
}
|
|
625
|
-
);
|
|
626
|
-
});
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
// src/core/v3/frame-quality.ts
|
|
630
|
-
var SHARP_REF = 180;
|
|
631
|
-
var EXPOSURE_BAND = [100, 190];
|
|
632
|
-
var EXPOSURE_FALLOFF = 64;
|
|
633
|
-
function lumaAt(data, index) {
|
|
634
|
-
return 0.299 * (data[index] ?? 0) + 0.587 * (data[index + 1] ?? 0) + 0.114 * (data[index + 2] ?? 0);
|
|
635
|
-
}
|
|
636
|
-
function meanLuma(image) {
|
|
637
|
-
const { data, width, height } = image;
|
|
638
|
-
const pixels = width * height;
|
|
639
|
-
if (pixels === 0) return 0;
|
|
640
|
-
let sum = 0;
|
|
641
|
-
for (let i = 0; i < pixels; i += 1) sum += lumaAt(data, i * 4);
|
|
642
|
-
return sum / pixels;
|
|
643
|
-
}
|
|
644
|
-
function sharpness(image) {
|
|
645
|
-
const { data, width, height } = image;
|
|
646
|
-
if (width < 3 || height < 3) return 0;
|
|
647
|
-
const gray = new Float32Array(width * height);
|
|
648
|
-
for (let i = 0; i < gray.length; i += 1) gray[i] = lumaAt(data, i * 4);
|
|
649
|
-
let sum = 0;
|
|
650
|
-
let sumSquares = 0;
|
|
651
|
-
let count = 0;
|
|
652
|
-
for (let y = 1; y < height - 1; y += 1) {
|
|
653
|
-
for (let x = 1; x < width - 1; x += 1) {
|
|
654
|
-
const i = y * width + x;
|
|
655
|
-
const response = (gray[i - width] ?? 0) + (gray[i - 1] ?? 0) + (gray[i + 1] ?? 0) + (gray[i + width] ?? 0) - 4 * (gray[i] ?? 0);
|
|
656
|
-
sum += response;
|
|
657
|
-
sumSquares += response * response;
|
|
658
|
-
count += 1;
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
if (count === 0) return 0;
|
|
662
|
-
const mean = sum / count;
|
|
663
|
-
const variance = sumSquares / count - mean * mean;
|
|
664
|
-
return Math.min(1, Math.max(0, variance) / SHARP_REF);
|
|
665
|
-
}
|
|
666
|
-
function exposure(image) {
|
|
667
|
-
const mean = meanLuma(image);
|
|
668
|
-
const [low, high] = EXPOSURE_BAND;
|
|
669
|
-
const distance = mean < low ? low - mean : mean > high ? mean - high : 0;
|
|
670
|
-
return Math.max(0, 1 - distance / EXPOSURE_FALLOFF);
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
// src/core/v3/face-gate-v3.ts
|
|
674
|
-
var V3_GATE_DEFAULTS = Object.freeze({
|
|
675
|
-
Q_GOOD: 0.6,
|
|
676
|
-
RISE_PER_S: 0.9,
|
|
677
|
-
FALL_PER_S: 0.25,
|
|
678
|
-
CENTER_FALLOFF_IOD_MULTIPLE: 1.35,
|
|
679
|
-
BOX_EYE_OFFSET_FACTOR: 0.12,
|
|
680
|
-
IOD_BOX_PROXY_FACTOR: 0.42,
|
|
681
|
-
SIZE_IDEAL_MIN: 0.12,
|
|
682
|
-
SIZE_IDEAL_MAX: 0.3,
|
|
683
|
-
SIZE_HARD_MIN: 0.08,
|
|
684
|
-
SIZE_HARD_MAX: 0.45,
|
|
685
|
-
ROLL_MAX_DEG: 25,
|
|
686
|
-
MOTION_VELOCITY_IOD_PER_S: 0.5,
|
|
687
|
-
MOTION_TAU_S: 0.4,
|
|
688
|
-
MOTION_DEADBAND_IOD_PER_S: 0.1,
|
|
689
|
-
READY_WINDOW_MS: 500,
|
|
690
|
-
// (READY_MEAN_Q, the former 0.75 window MEAN, is gone — 2026-10-17 field
|
|
691
|
-
// bug: a steady q anywhere in [Q_GOOD, 0.75) saturated p at 1, passed every
|
|
692
|
-
// guide ("hold still") and could never reach the mean, so the ring sat full
|
|
693
|
-
// and green with nothing recording. Readiness now checks the window against
|
|
694
|
-
// Q_GOOD, which keeps the one-flaky-tick forgiveness and the second-bad-tick
|
|
695
|
-
// block without a dead band above the rise threshold.)
|
|
696
|
-
GUIDE_SIZE: 0.6,
|
|
697
|
-
GUIDE_CENTERING: 0.6,
|
|
698
|
-
GUIDE_POSE: 0.6,
|
|
699
|
-
GUIDE_EXPOSURE: 0.6,
|
|
700
|
-
GUIDE_SHARPNESS: 0.35,
|
|
701
|
-
GUIDE_MOTION: 0.5
|
|
702
|
-
});
|
|
703
|
-
var clamp01 = (value) => Math.min(1, Math.max(0, value));
|
|
704
|
-
var FaceGateV3 = class {
|
|
705
|
-
constructor(overrides = {}) {
|
|
706
|
-
this.p = 0;
|
|
707
|
-
this.lastTickAt = null;
|
|
708
|
-
this.lastCenter = null;
|
|
709
|
-
this.velocityEma = 0;
|
|
710
|
-
this.qWindow = [];
|
|
711
|
-
/** Which side of the ideal band the last size measurement fell on. */
|
|
712
|
-
this.lastSizeDirection = "ideal";
|
|
713
|
-
this.t = { ...V3_GATE_DEFAULTS, ...overrides };
|
|
714
|
-
}
|
|
715
|
-
reset() {
|
|
716
|
-
this.p = 0;
|
|
717
|
-
this.lastTickAt = null;
|
|
718
|
-
this.lastCenter = null;
|
|
719
|
-
this.velocityEma = 0;
|
|
720
|
-
this.qWindow = [];
|
|
721
|
-
this.lastSizeDirection = "ideal";
|
|
722
|
-
}
|
|
723
|
-
tick(input) {
|
|
724
|
-
const { observation, quality, timestampMs } = input;
|
|
725
|
-
const dtSeconds = this.lastTickAt === null ? 0 : Math.max(0, (timestampMs - this.lastTickAt) / 1e3);
|
|
726
|
-
this.lastTickAt = timestampMs;
|
|
727
|
-
const factors = {
|
|
728
|
-
presence: 0,
|
|
729
|
-
centering: 0,
|
|
730
|
-
size: 0,
|
|
731
|
-
pose: 0,
|
|
732
|
-
sharpness: clamp01(quality.sharpness),
|
|
733
|
-
exposure: clamp01(quality.exposure),
|
|
734
|
-
motion: 1
|
|
735
|
-
};
|
|
736
|
-
if (observation !== null) {
|
|
737
|
-
factors.presence = 1;
|
|
738
|
-
const geometry = this.geometryOf(observation, input);
|
|
739
|
-
factors.centering = geometry.centering;
|
|
740
|
-
factors.size = geometry.size;
|
|
741
|
-
factors.pose = geometry.pose;
|
|
742
|
-
factors.motion = this.motionOf(
|
|
743
|
-
geometry.center,
|
|
744
|
-
geometry.iod,
|
|
745
|
-
timestampMs
|
|
746
|
-
);
|
|
747
|
-
} else {
|
|
748
|
-
this.lastCenter = null;
|
|
749
|
-
this.velocityEma = 0;
|
|
750
|
-
}
|
|
751
|
-
const q = Math.min(
|
|
752
|
-
factors.presence,
|
|
753
|
-
factors.centering,
|
|
754
|
-
factors.size,
|
|
755
|
-
factors.pose,
|
|
756
|
-
factors.sharpness,
|
|
757
|
-
factors.exposure,
|
|
758
|
-
factors.motion
|
|
759
|
-
);
|
|
760
|
-
this.p = clamp01(
|
|
761
|
-
this.p + (q >= this.t.Q_GOOD ? this.t.RISE_PER_S * q : -this.t.FALL_PER_S * (1 - q)) * dtSeconds
|
|
762
|
-
);
|
|
763
|
-
this.qWindow.push({ at: timestampMs, q });
|
|
764
|
-
this.qWindow = this.qWindow.filter(
|
|
765
|
-
(entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS
|
|
766
|
-
);
|
|
767
|
-
let windowSamples = this.qWindow.map((entry) => entry.q);
|
|
768
|
-
if (windowSamples.length >= 3) {
|
|
769
|
-
const worst = Math.min(...windowSamples);
|
|
770
|
-
const worstIndex = windowSamples.indexOf(worst);
|
|
771
|
-
windowSamples = windowSamples.filter((_, index) => index !== worstIndex);
|
|
772
|
-
}
|
|
773
|
-
const ready = this.p >= 1 && windowSamples.every((sample) => sample >= this.t.Q_GOOD);
|
|
774
|
-
return {
|
|
775
|
-
at: timestampMs,
|
|
776
|
-
q,
|
|
777
|
-
p: this.p,
|
|
778
|
-
factors,
|
|
779
|
-
guidanceKey: this.guidanceOf(factors, quality, q),
|
|
780
|
-
ready
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
geometryOf(observation, input) {
|
|
784
|
-
const { box, eyes } = observation;
|
|
785
|
-
const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };
|
|
786
|
-
const shortSide = Math.min(input.frameWidth, input.frameHeight);
|
|
787
|
-
const center = eyes !== void 0 ? {
|
|
788
|
-
x: (eyes.left.x + eyes.right.x) / 2,
|
|
789
|
-
y: (eyes.left.y + eyes.right.y) / 2
|
|
790
|
-
} : {
|
|
791
|
-
x: box.x + box.width / 2,
|
|
792
|
-
y: box.y + box.height / 2 - this.t.BOX_EYE_OFFSET_FACTOR * box.height
|
|
793
|
-
};
|
|
794
|
-
const iod = eyes !== void 0 ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y) : this.t.IOD_BOX_PROXY_FACTOR * box.width;
|
|
795
|
-
const distance = Math.hypot(
|
|
796
|
-
center.x - frameCenter.x,
|
|
797
|
-
center.y - frameCenter.y
|
|
798
|
-
);
|
|
799
|
-
const centering = iod <= 0 ? 0 : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));
|
|
800
|
-
const ratio = shortSide > 0 ? iod / shortSide : 0;
|
|
801
|
-
this.lastSizeDirection = ratio < this.t.SIZE_IDEAL_MIN ? "far" : ratio > this.t.SIZE_IDEAL_MAX ? "close" : "ideal";
|
|
802
|
-
let size;
|
|
803
|
-
if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {
|
|
804
|
-
size = 0;
|
|
805
|
-
} else if (ratio < this.t.SIZE_IDEAL_MIN) {
|
|
806
|
-
size = (ratio - this.t.SIZE_HARD_MIN) / (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);
|
|
807
|
-
} else if (ratio > this.t.SIZE_IDEAL_MAX) {
|
|
808
|
-
size = (this.t.SIZE_HARD_MAX - ratio) / (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);
|
|
809
|
-
} else {
|
|
810
|
-
size = 1;
|
|
811
|
-
}
|
|
812
|
-
let pose = 1;
|
|
813
|
-
if (eyes !== void 0) {
|
|
814
|
-
const rollDeg = Math.abs(
|
|
815
|
-
Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x)
|
|
816
|
-
) * 180 / Math.PI;
|
|
817
|
-
pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);
|
|
818
|
-
}
|
|
819
|
-
return { center, iod, centering, size, pose };
|
|
820
|
-
}
|
|
821
|
-
motionOf(center, iod, at) {
|
|
822
|
-
const previous = this.lastCenter;
|
|
823
|
-
this.lastCenter = { ...center, at };
|
|
824
|
-
if (previous === null || iod <= 0) return 1;
|
|
825
|
-
const dtSeconds = (at - previous.at) / 1e3;
|
|
826
|
-
if (dtSeconds <= 0) return 1;
|
|
827
|
-
let velocityIodPerS = Math.hypot(center.x - previous.x, center.y - previous.y) / iod / dtSeconds;
|
|
828
|
-
if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)
|
|
829
|
-
velocityIodPerS = 0;
|
|
830
|
-
const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);
|
|
831
|
-
this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;
|
|
832
|
-
return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);
|
|
833
|
-
}
|
|
834
|
-
/** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):
|
|
835
|
-
* presence → size → centering → pose → exposure → sharpness → hold.
|
|
836
|
-
*
|
|
837
|
-
* HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears
|
|
838
|
-
* its guide threshold but q (= min factor) is still below Q_GOOD — i.e.
|
|
839
|
-
* progress is DRAINING — "hold still" would be a lie ("Perfect" while
|
|
840
|
-
* nothing advances; the field symptom was users discovering by accident
|
|
841
|
-
* that only leaning in fires the gate). In that state the WORST factor
|
|
842
|
-
* speaks even though it passed its guide level, so the user always hears
|
|
843
|
-
* the change that actually unblocks recording. */
|
|
844
|
-
guidanceOf(factors, quality, q) {
|
|
845
|
-
if (factors.presence <= 0) return "fcv3.no_face";
|
|
846
|
-
if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();
|
|
847
|
-
if (factors.centering < this.t.GUIDE_CENTERING) return "fcv3.center_face";
|
|
848
|
-
if (factors.pose < this.t.GUIDE_POSE) return "fcv3.straighten";
|
|
849
|
-
if (factors.exposure < this.t.GUIDE_EXPOSURE)
|
|
850
|
-
return this.exposureGuidance(quality);
|
|
851
|
-
if (factors.sharpness < this.t.GUIDE_SHARPNESS) return "fcv3.steady_camera";
|
|
852
|
-
if (factors.motion < this.t.GUIDE_MOTION) return "fcv3.hold_still";
|
|
853
|
-
if (q < this.t.Q_GOOD) {
|
|
854
|
-
const coachable = [
|
|
855
|
-
["size", this.sizeGuidance()],
|
|
856
|
-
["centering", "fcv3.center_face"],
|
|
857
|
-
["pose", "fcv3.straighten"],
|
|
858
|
-
["exposure", this.exposureGuidance(quality)],
|
|
859
|
-
["sharpness", "fcv3.steady_camera"],
|
|
860
|
-
["motion", "fcv3.hold_still"]
|
|
861
|
-
];
|
|
862
|
-
let worst = coachable[0];
|
|
863
|
-
for (const entry of coachable) {
|
|
864
|
-
if (factors[entry[0]] < factors[worst[0]]) worst = entry;
|
|
865
|
-
}
|
|
866
|
-
return worst[1];
|
|
867
|
-
}
|
|
868
|
-
return "fcv3.hold_still";
|
|
869
|
-
}
|
|
870
|
-
/** Direction from the size band set THIS tick (never inverted at the hard
|
|
871
|
-
* limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */
|
|
872
|
-
sizeGuidance() {
|
|
873
|
-
return this.lastSizeDirection === "far" ? "fcv3.come_closer" : "fcv3.move_back";
|
|
874
|
-
}
|
|
875
|
-
/** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */
|
|
876
|
-
exposureGuidance(quality) {
|
|
877
|
-
const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;
|
|
878
|
-
return quality.meanLuma < bandMid ? "fcv3.more_light" : "fcv3.too_bright";
|
|
879
|
-
}
|
|
880
|
-
};
|
|
881
|
-
|
|
882
|
-
// src/core/v3/device-profile.ts
|
|
883
|
-
var DEVICE_PROFILES = Object.freeze({
|
|
884
|
-
LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: "reduced" }),
|
|
885
|
-
MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: "full" }),
|
|
886
|
-
HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: "full" })
|
|
887
|
-
});
|
|
888
|
-
var SIMD_TEST_BYTES = new Uint8Array([
|
|
889
|
-
0,
|
|
890
|
-
97,
|
|
891
|
-
115,
|
|
892
|
-
109,
|
|
893
|
-
1,
|
|
894
|
-
0,
|
|
895
|
-
0,
|
|
896
|
-
0,
|
|
897
|
-
1,
|
|
898
|
-
5,
|
|
899
|
-
1,
|
|
900
|
-
96,
|
|
901
|
-
0,
|
|
902
|
-
1,
|
|
903
|
-
123,
|
|
904
|
-
3,
|
|
905
|
-
2,
|
|
906
|
-
1,
|
|
907
|
-
0,
|
|
908
|
-
10,
|
|
909
|
-
10,
|
|
910
|
-
1,
|
|
911
|
-
8,
|
|
912
|
-
0,
|
|
913
|
-
65,
|
|
914
|
-
0,
|
|
915
|
-
253,
|
|
916
|
-
15,
|
|
917
|
-
253,
|
|
918
|
-
98,
|
|
919
|
-
11
|
|
920
|
-
]);
|
|
921
|
-
function probeDevice() {
|
|
922
|
-
const nav = typeof navigator === "undefined" ? void 0 : navigator;
|
|
923
|
-
let simd = false;
|
|
924
|
-
try {
|
|
925
|
-
simd = typeof WebAssembly !== "undefined" && WebAssembly.validate(SIMD_TEST_BYTES);
|
|
926
|
-
} catch {
|
|
927
|
-
simd = false;
|
|
928
|
-
}
|
|
929
|
-
return {
|
|
930
|
-
cores: nav?.hardwareConcurrency ?? 2,
|
|
931
|
-
memGB: nav?.deviceMemory ?? null,
|
|
932
|
-
simd
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
function classifyDevice(probe) {
|
|
936
|
-
const memGB = probe.memGB ?? 4;
|
|
937
|
-
if (probe.cores < 4 || memGB < 3) return "LOW";
|
|
938
|
-
if (probe.cores >= 8 && memGB >= 6) return "HIGH";
|
|
939
|
-
return "MID";
|
|
940
|
-
}
|
|
941
|
-
var ORDER = ["LOW", "MID", "HIGH"];
|
|
942
|
-
var DeviceProfiler = class {
|
|
943
|
-
constructor(initial) {
|
|
944
|
-
this.samples = [];
|
|
945
|
-
this.adjusted = false;
|
|
946
|
-
this.current = initial;
|
|
947
|
-
}
|
|
948
|
-
get deviceClass() {
|
|
949
|
-
return this.current;
|
|
950
|
-
}
|
|
951
|
-
get profile() {
|
|
952
|
-
return DEVICE_PROFILES[this.current];
|
|
953
|
-
}
|
|
954
|
-
record(detectMs) {
|
|
955
|
-
if (this.adjusted || this.samples.length >= 10) return this.current;
|
|
956
|
-
this.samples.push(detectMs);
|
|
957
|
-
if (this.samples.length < 10) return this.current;
|
|
958
|
-
this.adjusted = true;
|
|
959
|
-
const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;
|
|
960
|
-
if (mean > 70) {
|
|
961
|
-
this.current = "LOW";
|
|
962
|
-
} else if (mean < 25) {
|
|
963
|
-
const index = ORDER.indexOf(this.current);
|
|
964
|
-
this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;
|
|
965
|
-
}
|
|
966
|
-
return this.current;
|
|
967
|
-
}
|
|
968
|
-
};
|
|
969
|
-
|
|
970
|
-
// src/core/v3/detect-scheduler.ts
|
|
971
|
-
var STATS_WINDOW = 20;
|
|
972
|
-
var DetectScheduler = class {
|
|
973
|
-
constructor(options) {
|
|
974
|
-
this.timer = null;
|
|
975
|
-
this.frameCallbackId = null;
|
|
976
|
-
this.running = false;
|
|
977
|
-
this.busy = false;
|
|
978
|
-
this.lastRunAt = Number.NEGATIVE_INFINITY;
|
|
979
|
-
this.degradeCount = 0;
|
|
980
|
-
this.durations = [];
|
|
981
|
-
this.options = options;
|
|
982
|
-
this.periodMs = 1e3 / options.cadenceHz;
|
|
983
|
-
}
|
|
984
|
-
start() {
|
|
985
|
-
if (this.running) return;
|
|
986
|
-
this.running = true;
|
|
987
|
-
const video = this.options.video;
|
|
988
|
-
if (typeof video?.requestVideoFrameCallback === "function") {
|
|
989
|
-
const loop = () => {
|
|
990
|
-
if (!this.running) return;
|
|
991
|
-
this.frameCallbackId = video.requestVideoFrameCallback?.(() => {
|
|
992
|
-
this.frameCallbackId = null;
|
|
993
|
-
if (this.now() - this.lastRunAt >= this.periodMs) this.tick();
|
|
994
|
-
loop();
|
|
995
|
-
});
|
|
996
|
-
};
|
|
997
|
-
loop();
|
|
998
|
-
return;
|
|
999
|
-
}
|
|
1000
|
-
this.timer = setInterval(() => this.tick(), this.periodMs);
|
|
1001
|
-
}
|
|
1002
|
-
stop() {
|
|
1003
|
-
this.running = false;
|
|
1004
|
-
if (this.timer !== null) {
|
|
1005
|
-
clearInterval(this.timer);
|
|
1006
|
-
this.timer = null;
|
|
1007
|
-
}
|
|
1008
|
-
if (this.frameCallbackId !== null) {
|
|
1009
|
-
this.options.video?.cancelVideoFrameCallback?.(
|
|
1010
|
-
this.frameCallbackId
|
|
1011
|
-
);
|
|
1012
|
-
this.frameCallbackId = null;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
stats() {
|
|
1016
|
-
const meanDetectMs = this.durations.length === 0 ? 0 : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;
|
|
1017
|
-
return { degradeCount: this.degradeCount, meanDetectMs };
|
|
1018
|
-
}
|
|
1019
|
-
now() {
|
|
1020
|
-
return this.options.now?.() ?? performance.now();
|
|
1021
|
-
}
|
|
1022
|
-
tick() {
|
|
1023
|
-
if (!this.running) return;
|
|
1024
|
-
if (this.busy) {
|
|
1025
|
-
this.degradeCount += 1;
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
|
-
this.busy = true;
|
|
1029
|
-
this.lastRunAt = this.now();
|
|
1030
|
-
const startedAt = this.now();
|
|
1031
|
-
this.options.run().catch(() => void 0).finally(() => {
|
|
1032
|
-
this.busy = false;
|
|
1033
|
-
this.durations.push(this.now() - startedAt);
|
|
1034
|
-
if (this.durations.length > STATS_WINDOW) this.durations.shift();
|
|
1035
|
-
});
|
|
1036
|
-
}
|
|
1037
|
-
};
|
|
1038
|
-
|
|
1039
|
-
// src/core/v3/detect-worker.ts
|
|
1040
|
-
var WORKER_PROTOCOL_VERSION = 1;
|
|
1041
|
-
function workerOffloadSupported() {
|
|
1042
|
-
return typeof OffscreenCanvas === "function" && typeof createImageBitmap === "function" && typeof Worker === "function";
|
|
1043
|
-
}
|
|
1044
|
-
function installWorkerDetectorHost(scope, deps = {}) {
|
|
1045
|
-
const create = deps.createDetector ?? createDetector;
|
|
1046
|
-
let detector = null;
|
|
1047
|
-
scope.onmessage = (event) => {
|
|
1048
|
-
const message = event.data;
|
|
1049
|
-
if (message.v !== WORKER_PROTOCOL_VERSION) {
|
|
1050
|
-
message.bitmap?.close?.();
|
|
1051
|
-
return;
|
|
1052
|
-
}
|
|
1053
|
-
if (message.type === "init") {
|
|
1054
|
-
void create(message.options).then((created) => {
|
|
1055
|
-
detector = created;
|
|
1056
|
-
const ready = {
|
|
1057
|
-
v: WORKER_PROTOCOL_VERSION,
|
|
1058
|
-
type: "ready",
|
|
1059
|
-
tier: created.tier,
|
|
1060
|
-
...created.fallbackReason !== void 0 ? { fallbackReason: created.fallbackReason } : {}
|
|
1061
|
-
};
|
|
1062
|
-
scope.postMessage(ready);
|
|
1063
|
-
});
|
|
1064
|
-
return;
|
|
1065
|
-
}
|
|
1066
|
-
if (message.type === "detect") {
|
|
1067
|
-
const respond = (observation) => {
|
|
1068
|
-
const result = {
|
|
1069
|
-
v: WORKER_PROTOCOL_VERSION,
|
|
1070
|
-
type: "result",
|
|
1071
|
-
id: message.id,
|
|
1072
|
-
observation
|
|
1073
|
-
};
|
|
1074
|
-
scope.postMessage(result);
|
|
1075
|
-
message.bitmap.close?.();
|
|
1076
|
-
};
|
|
1077
|
-
if (detector === null) {
|
|
1078
|
-
respond(null);
|
|
1079
|
-
return;
|
|
1080
|
-
}
|
|
1081
|
-
void detector.detect(message.bitmap, message.streamWidth, message.streamHeight).then(respond, () => respond(null));
|
|
1082
|
-
}
|
|
1083
|
-
};
|
|
1084
|
-
}
|
|
1085
|
-
if (typeof self !== "undefined" && typeof self.importScripts === "function") {
|
|
1086
|
-
installWorkerDetectorHost(self);
|
|
1087
|
-
}
|
|
1088
|
-
var WorkerDetectorProxy = class _WorkerDetectorProxy {
|
|
1089
|
-
constructor(worker, ready) {
|
|
1090
|
-
this.pending = /* @__PURE__ */ new Map();
|
|
1091
|
-
this.nextId = 1;
|
|
1092
|
-
this.worker = worker;
|
|
1093
|
-
this.tier = ready.tier;
|
|
1094
|
-
if (ready.fallbackReason !== void 0) this.fallbackReason = ready.fallbackReason;
|
|
1095
|
-
worker.addEventListener("message", (event) => {
|
|
1096
|
-
const message = event.data;
|
|
1097
|
-
if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== "result") return;
|
|
1098
|
-
const resolve = this.pending.get(message.id);
|
|
1099
|
-
this.pending.delete(message.id);
|
|
1100
|
-
resolve?.(message.observation);
|
|
1101
|
-
});
|
|
1102
|
-
}
|
|
1103
|
-
static create(worker, options, readyTimeoutMs = 1e4) {
|
|
1104
|
-
return new Promise((resolve, reject) => {
|
|
1105
|
-
const timer = setTimeout(() => {
|
|
1106
|
-
worker.removeEventListener("message", onReady);
|
|
1107
|
-
worker.terminate();
|
|
1108
|
-
reject(new Error(`worker detector not ready within ${readyTimeoutMs}ms`));
|
|
1109
|
-
}, readyTimeoutMs);
|
|
1110
|
-
const onReady = (event) => {
|
|
1111
|
-
const message = event.data;
|
|
1112
|
-
if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== "ready") return;
|
|
1113
|
-
clearTimeout(timer);
|
|
1114
|
-
worker.removeEventListener("message", onReady);
|
|
1115
|
-
resolve(new _WorkerDetectorProxy(worker, message));
|
|
1116
|
-
};
|
|
1117
|
-
worker.addEventListener("message", onReady);
|
|
1118
|
-
const init = { v: WORKER_PROTOCOL_VERSION, type: "init", options };
|
|
1119
|
-
worker.postMessage(init);
|
|
1120
|
-
});
|
|
1121
|
-
}
|
|
1122
|
-
async detect(source, sourceWidth, sourceHeight) {
|
|
1123
|
-
let bitmap;
|
|
1124
|
-
try {
|
|
1125
|
-
if (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap) {
|
|
1126
|
-
bitmap = source;
|
|
1127
|
-
} else if (typeof createImageBitmap === "function") {
|
|
1128
|
-
bitmap = await createImageBitmap(source);
|
|
1129
|
-
} else {
|
|
1130
|
-
bitmap = source;
|
|
1131
|
-
}
|
|
1132
|
-
} catch {
|
|
1133
|
-
return null;
|
|
1134
|
-
}
|
|
1135
|
-
const id = this.nextId;
|
|
1136
|
-
this.nextId += 1;
|
|
1137
|
-
return new Promise((resolve) => {
|
|
1138
|
-
this.pending.set(id, resolve);
|
|
1139
|
-
const message = {
|
|
1140
|
-
v: WORKER_PROTOCOL_VERSION,
|
|
1141
|
-
type: "detect",
|
|
1142
|
-
id,
|
|
1143
|
-
bitmap,
|
|
1144
|
-
streamWidth: sourceWidth,
|
|
1145
|
-
streamHeight: sourceHeight
|
|
1146
|
-
};
|
|
1147
|
-
this.worker.postMessage(message, [bitmap]);
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
destroy() {
|
|
1151
|
-
for (const resolve of this.pending.values()) resolve(null);
|
|
1152
|
-
this.pending.clear();
|
|
1153
|
-
this.worker.terminate();
|
|
1154
|
-
}
|
|
1155
|
-
};
|
|
1156
|
-
|
|
1157
|
-
// src/core/v3/capture-session-v3.ts
|
|
1158
|
-
var KEYFRAME_CANDIDATES = 4;
|
|
1159
|
-
var KEYFRAME_WINDOW_MS = 600;
|
|
1160
|
-
var NEUTRAL_QUALITY = { sharpness: 1, exposure: 1, meanLuma: 128 };
|
|
1161
|
-
var CaptureSessionV3 = class {
|
|
1162
|
-
constructor(options) {
|
|
1163
|
-
this.handlers = /* @__PURE__ */ new Map();
|
|
1164
|
-
this.stateValue = "idle";
|
|
1165
|
-
this.attempt = 0;
|
|
1166
|
-
this.stream = null;
|
|
1167
|
-
this.detector = null;
|
|
1168
|
-
this.scheduler = null;
|
|
1169
|
-
this.gate = null;
|
|
1170
|
-
this.profiler = null;
|
|
1171
|
-
this.lastGuidanceKey = null;
|
|
1172
|
-
this.positioningStartedAt = 0;
|
|
1173
|
-
this.fired = false;
|
|
1174
|
-
this.carriedDegrade = 0;
|
|
1175
|
-
this.carriedMeans = [];
|
|
1176
|
-
/** Reused downscale canvas — falls back to the raw video where canvas 2D
|
|
1177
|
-
* is unavailable (jsdom) so tests and exotic hosts keep detecting. */
|
|
1178
|
-
this.snapshotCanvas = null;
|
|
1179
|
-
this.options = options;
|
|
1180
|
-
this.facing = options.facingMode ?? "user";
|
|
1181
|
-
}
|
|
1182
|
-
get state() {
|
|
1183
|
-
return this.stateValue;
|
|
1184
|
-
}
|
|
1185
|
-
on(event, handler) {
|
|
1186
|
-
let set = this.handlers.get(event);
|
|
1187
|
-
if (!set) {
|
|
1188
|
-
set = /* @__PURE__ */ new Set();
|
|
1189
|
-
this.handlers.set(event, set);
|
|
1190
|
-
}
|
|
1191
|
-
set.add(handler);
|
|
1192
|
-
return () => set?.delete(handler);
|
|
1193
|
-
}
|
|
1194
|
-
emit(event, payload) {
|
|
1195
|
-
for (const handler of [...this.handlers.get(event) ?? []]) {
|
|
1196
|
-
handler(payload);
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
async start() {
|
|
1200
|
-
this.attempt += 1;
|
|
1201
|
-
await this.run(this.attempt);
|
|
1202
|
-
}
|
|
1203
|
-
/** Full reset + camera restart — the documented recovery path (v1 parity). */
|
|
1204
|
-
retry() {
|
|
1205
|
-
this.teardownAttempt();
|
|
1206
|
-
void this.start();
|
|
1207
|
-
}
|
|
1208
|
-
switchCamera() {
|
|
1209
|
-
this.facing = this.facing === "user" ? "environment" : "user";
|
|
1210
|
-
this.teardownAttempt();
|
|
1211
|
-
void this.start();
|
|
1212
|
-
}
|
|
1213
|
-
destroy() {
|
|
1214
|
-
this.attempt += 1;
|
|
1215
|
-
this.teardownAttempt();
|
|
1216
|
-
this.detector?.destroy();
|
|
1217
|
-
this.detector = null;
|
|
1218
|
-
this.options.video.srcObject = null;
|
|
1219
|
-
}
|
|
1220
|
-
// ── attempt lifecycle ──────────────────────────────────────────────────────
|
|
1221
|
-
async run(attempt) {
|
|
1222
|
-
const { options } = this;
|
|
1223
|
-
this.fired = false;
|
|
1224
|
-
this.lastGuidanceKey = null;
|
|
1225
|
-
this.carriedDegrade = 0;
|
|
1226
|
-
this.carriedMeans = [];
|
|
1227
|
-
this.setState("preflight");
|
|
1228
|
-
const preflight = cameraPreflight();
|
|
1229
|
-
if (preflight !== "OK") {
|
|
1230
|
-
this.fail(preflight === "INSECURE_CONTEXT" ? "insecure" : "unsupported");
|
|
1231
|
-
return;
|
|
1232
|
-
}
|
|
1233
|
-
this.setState("acquiring");
|
|
1234
|
-
const getUserMedia = options.getUserMedia ?? ((constraints) => navigator.mediaDevices.getUserMedia(constraints));
|
|
1235
|
-
let stream;
|
|
1236
|
-
try {
|
|
1237
|
-
stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));
|
|
1238
|
-
} catch (err) {
|
|
1239
|
-
if (attempt !== this.attempt) return;
|
|
1240
|
-
this.fail(mapGetUserMediaError(err));
|
|
1241
|
-
return;
|
|
1242
|
-
}
|
|
1243
|
-
if (attempt !== this.attempt) {
|
|
1244
|
-
for (const track of stream.getTracks()) track.stop();
|
|
1245
|
-
return;
|
|
1246
|
-
}
|
|
1247
|
-
this.stream = stream;
|
|
1248
|
-
options.video.srcObject = stream;
|
|
1249
|
-
await options.video.play().catch(() => void 0);
|
|
1250
|
-
if (attempt !== this.attempt) return;
|
|
1251
|
-
if (this.detector === null) {
|
|
1252
|
-
const ladderOptions = {
|
|
1253
|
-
...options.v3AssetBaseUrl !== void 0 ? { v3AssetBaseUrl: options.v3AssetBaseUrl } : {}
|
|
1254
|
-
};
|
|
1255
|
-
const create = options.createDetector ?? (options.createWorker !== void 0 && workerOffloadSupported() ? async () => {
|
|
1256
|
-
try {
|
|
1257
|
-
return await WorkerDetectorProxy.create(
|
|
1258
|
-
options.createWorker(),
|
|
1259
|
-
ladderOptions
|
|
1260
|
-
);
|
|
1261
|
-
} catch {
|
|
1262
|
-
return createDetector(ladderOptions);
|
|
1263
|
-
}
|
|
1264
|
-
} : () => createDetector(ladderOptions));
|
|
1265
|
-
let created;
|
|
1266
|
-
try {
|
|
1267
|
-
created = await create();
|
|
1268
|
-
} catch (err) {
|
|
1269
|
-
if (attempt === this.attempt) {
|
|
1270
|
-
this.fail(
|
|
1271
|
-
"models",
|
|
1272
|
-
err instanceof DetectorLadderError ? err.fallbackReason : describeError2(err)
|
|
1273
|
-
);
|
|
1274
|
-
}
|
|
1275
|
-
return;
|
|
1276
|
-
}
|
|
1277
|
-
if (attempt !== this.attempt) {
|
|
1278
|
-
created.destroy();
|
|
1279
|
-
return;
|
|
1280
|
-
}
|
|
1281
|
-
this.detector = created;
|
|
1282
|
-
this.options.telemetry?.({
|
|
1283
|
-
type: "detector",
|
|
1284
|
-
tier: created.tier,
|
|
1285
|
-
...created.fallbackReason !== void 0 ? { fallbackReason: created.fallbackReason } : {}
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
const probe = probeDevice();
|
|
1289
|
-
const staticClass = options.deviceClass ?? classifyDevice(probe);
|
|
1290
|
-
this.profiler = new DeviceProfiler(staticClass);
|
|
1291
|
-
this.options.telemetry?.({
|
|
1292
|
-
type: "profile",
|
|
1293
|
-
staticClass,
|
|
1294
|
-
activeClass: this.profiler.deviceClass,
|
|
1295
|
-
simd: probe.simd
|
|
1296
|
-
});
|
|
1297
|
-
this.gate = new FaceGateV3(options.thresholds ?? {});
|
|
1298
|
-
this.setState("positioning");
|
|
1299
|
-
this.positioningStartedAt = this.now();
|
|
1300
|
-
this.startScheduler(attempt);
|
|
1301
|
-
}
|
|
1302
|
-
/** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */
|
|
1303
|
-
get animations() {
|
|
1304
|
-
return this.profiler?.profile.animations ?? "full";
|
|
1305
|
-
}
|
|
1306
|
-
startScheduler(attempt) {
|
|
1307
|
-
const profiler = this.profiler;
|
|
1308
|
-
if (profiler === null) return;
|
|
1309
|
-
if (this.scheduler !== null) {
|
|
1310
|
-
const stats = this.scheduler.stats();
|
|
1311
|
-
this.carriedDegrade += stats.degradeCount;
|
|
1312
|
-
if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);
|
|
1313
|
-
this.scheduler.stop();
|
|
1314
|
-
}
|
|
1315
|
-
const scheduler = new DetectScheduler({
|
|
1316
|
-
cadenceHz: profiler.profile.cadenceHz,
|
|
1317
|
-
video: this.options.video,
|
|
1318
|
-
...this.options.now !== void 0 ? { now: this.options.now } : {},
|
|
1319
|
-
run: () => this.detectTick(attempt)
|
|
1320
|
-
});
|
|
1321
|
-
this.scheduler = scheduler;
|
|
1322
|
-
scheduler.start();
|
|
1323
|
-
}
|
|
1324
|
-
async detectTick(attempt) {
|
|
1325
|
-
const { detector, gate, profiler } = this;
|
|
1326
|
-
const video = this.options.video;
|
|
1327
|
-
if (attempt !== this.attempt || detector === null || gate === null || profiler === null)
|
|
1328
|
-
return;
|
|
1329
|
-
if (this.fired || video.videoWidth === 0) return;
|
|
1330
|
-
const before = profiler.deviceClass;
|
|
1331
|
-
const t0 = this.now();
|
|
1332
|
-
const source = this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ?? this.defaultSnapshot(video, profiler.profile.inputWidth);
|
|
1333
|
-
let observation = null;
|
|
1334
|
-
try {
|
|
1335
|
-
observation = await detector.detect(source, video.videoWidth, video.videoHeight);
|
|
1336
|
-
} catch {
|
|
1337
|
-
observation = null;
|
|
1338
|
-
}
|
|
1339
|
-
if (attempt !== this.attempt || this.fired) return;
|
|
1340
|
-
profiler.record(this.now() - t0);
|
|
1341
|
-
if (profiler.deviceClass !== before) this.startScheduler(attempt);
|
|
1342
|
-
const quality = observation === null ? NEUTRAL_QUALITY : this.options.measureQuality?.(video, observation.box) ?? this.defaultQuality(video, observation.box);
|
|
1343
|
-
const tick = gate.tick({
|
|
1344
|
-
timestampMs: this.now(),
|
|
1345
|
-
observation,
|
|
1346
|
-
quality,
|
|
1347
|
-
frameWidth: video.videoWidth,
|
|
1348
|
-
frameHeight: video.videoHeight
|
|
1349
|
-
});
|
|
1350
|
-
this.emit("checks", {
|
|
1351
|
-
engine: "v3",
|
|
1352
|
-
progress: tick.p,
|
|
1353
|
-
q: tick.q,
|
|
1354
|
-
factors: tick.factors,
|
|
1355
|
-
attempt
|
|
1356
|
-
});
|
|
1357
|
-
if (tick.guidanceKey !== this.lastGuidanceKey) {
|
|
1358
|
-
this.lastGuidanceKey = tick.guidanceKey;
|
|
1359
|
-
this.emit("guidance", { key: tick.guidanceKey });
|
|
1360
|
-
}
|
|
1361
|
-
if (tick.ready && this.stateValue === "positioning") {
|
|
1362
|
-
this.fired = true;
|
|
1363
|
-
void this.fire(attempt);
|
|
1364
|
-
}
|
|
1365
|
-
}
|
|
1366
|
-
async fire(attempt) {
|
|
1367
|
-
const { options } = this;
|
|
1368
|
-
const scheduler = this.scheduler;
|
|
1369
|
-
scheduler?.stop();
|
|
1370
|
-
const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };
|
|
1371
|
-
const means = [...this.carriedMeans, ...stats.meanDetectMs > 0 ? [stats.meanDetectMs] : []];
|
|
1372
|
-
options.telemetry?.({
|
|
1373
|
-
type: "fired",
|
|
1374
|
-
timeToGateMs: this.now() - this.positioningStartedAt,
|
|
1375
|
-
degradeCount: this.carriedDegrade + stats.degradeCount,
|
|
1376
|
-
meanDetectMs: means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length
|
|
1377
|
-
});
|
|
1378
|
-
const mode = options.mode ?? "clip";
|
|
1379
|
-
const bestOf = this.collectKeyframes(attempt);
|
|
1380
|
-
if (mode === "photo") {
|
|
1381
|
-
const best2 = await bestOf;
|
|
1382
|
-
if (attempt !== this.attempt) return;
|
|
1383
|
-
if (best2 === null) {
|
|
1384
|
-
this.fail("generic");
|
|
1385
|
-
return;
|
|
1386
|
-
}
|
|
1387
|
-
this.finishCapture({ keyframe: best2.blob, previewDataUrl: best2.previewDataUrl });
|
|
1388
|
-
return;
|
|
1389
|
-
}
|
|
1390
|
-
this.setState("recording");
|
|
1391
|
-
const recorder = options.createRecorder?.() ?? new ClipRecorder();
|
|
1392
|
-
const stream = this.stream;
|
|
1393
|
-
if (stream === null) {
|
|
1394
|
-
this.fail("generic");
|
|
1395
|
-
return;
|
|
1396
|
-
}
|
|
1397
|
-
let frozenBest = null;
|
|
1398
|
-
void bestOf.then(
|
|
1399
|
-
(candidate) => {
|
|
1400
|
-
frozenBest = candidate;
|
|
1401
|
-
},
|
|
1402
|
-
() => {
|
|
1403
|
-
}
|
|
1404
|
-
);
|
|
1405
|
-
const onRecordingStopped = () => {
|
|
1406
|
-
if (attempt !== this.attempt) return;
|
|
1407
|
-
if (frozenBest !== null) {
|
|
1408
|
-
this.emit("frozen", { previewDataUrl: frozenBest.previewDataUrl });
|
|
1409
|
-
}
|
|
1410
|
-
};
|
|
1411
|
-
let clip;
|
|
1412
|
-
let best;
|
|
1413
|
-
try {
|
|
1414
|
-
[clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);
|
|
1415
|
-
} catch (err) {
|
|
1416
|
-
if (attempt !== this.attempt) return;
|
|
1417
|
-
const kind = err.kind;
|
|
1418
|
-
this.fail(kind === "cliptoolarge" ? "cliptoolarge" : "recorder");
|
|
1419
|
-
return;
|
|
1420
|
-
}
|
|
1421
|
-
if (attempt !== this.attempt) return;
|
|
1422
|
-
if (isClipTooLarge(clip.blob)) {
|
|
1423
|
-
this.fail("cliptoolarge");
|
|
1424
|
-
return;
|
|
1425
|
-
}
|
|
1426
|
-
if (best === null) {
|
|
1427
|
-
this.fail("generic");
|
|
1428
|
-
return;
|
|
1429
|
-
}
|
|
1430
|
-
this.finishCapture({
|
|
1431
|
-
clip: clip.blob,
|
|
1432
|
-
clipMimeType: clip.mimeType,
|
|
1433
|
-
keyframe: best.blob,
|
|
1434
|
-
previewDataUrl: best.previewDataUrl
|
|
1435
|
-
});
|
|
1436
|
-
}
|
|
1437
|
-
/** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —
|
|
1438
|
-
* sharpest wins (reuses frame-quality.sharpness via the capture seam). */
|
|
1439
|
-
async collectKeyframes(attempt) {
|
|
1440
|
-
const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));
|
|
1441
|
-
const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);
|
|
1442
|
-
let best = null;
|
|
1443
|
-
for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {
|
|
1444
|
-
if (attempt !== this.attempt) return best;
|
|
1445
|
-
try {
|
|
1446
|
-
const candidate = await capture(this.options.video);
|
|
1447
|
-
if (best === null || candidate.sharpness > best.sharpness) best = candidate;
|
|
1448
|
-
} catch {
|
|
1449
|
-
}
|
|
1450
|
-
if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);
|
|
1451
|
-
}
|
|
1452
|
-
return best;
|
|
1453
|
-
}
|
|
1454
|
-
finishCapture(artifacts) {
|
|
1455
|
-
this.stopTracks();
|
|
1456
|
-
this.setState("captured");
|
|
1457
|
-
this.emit("artifacts", artifacts);
|
|
1458
|
-
}
|
|
1459
|
-
// ── defaults for the canvas-bound seams ────────────────────────────────────
|
|
1460
|
-
async defaultKeyframe(video) {
|
|
1461
|
-
const canvas = document.createElement("canvas");
|
|
1462
|
-
const blob = await captureMirroredKeyframe(video, canvas);
|
|
1463
|
-
const previewDataUrl = canvas.toDataURL("image/jpeg", 0.92);
|
|
1464
|
-
return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };
|
|
1465
|
-
}
|
|
1466
|
-
defaultSnapshot(video, targetWidth) {
|
|
1467
|
-
try {
|
|
1468
|
-
const canvas = this.snapshotCanvas ?? document.createElement("canvas");
|
|
1469
|
-
const scale = targetWidth / Math.max(1, video.videoWidth);
|
|
1470
|
-
const width = Math.max(1, Math.round(video.videoWidth * scale));
|
|
1471
|
-
const height = Math.max(1, Math.round(video.videoHeight * scale));
|
|
1472
|
-
const ctx = canvas.getContext("2d");
|
|
1473
|
-
if (ctx === null) return video;
|
|
1474
|
-
if (canvas.width !== width) canvas.width = width;
|
|
1475
|
-
if (canvas.height !== height) canvas.height = height;
|
|
1476
|
-
ctx.drawImage(video, 0, 0, width, height);
|
|
1477
|
-
this.snapshotCanvas = canvas;
|
|
1478
|
-
return canvas;
|
|
1479
|
-
} catch {
|
|
1480
|
-
return video;
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
defaultQuality(video, box) {
|
|
1484
|
-
const crop = cropImageData(video, box, 96);
|
|
1485
|
-
if (crop === null) return NEUTRAL_QUALITY;
|
|
1486
|
-
return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };
|
|
1487
|
-
}
|
|
1488
|
-
centerSharpness(video) {
|
|
1489
|
-
const size = intrinsicSize(video);
|
|
1490
|
-
const crop = cropImageData(
|
|
1491
|
-
video,
|
|
1492
|
-
{ x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },
|
|
1493
|
-
96
|
|
1494
|
-
);
|
|
1495
|
-
return crop === null ? 0 : sharpness(crop);
|
|
1496
|
-
}
|
|
1497
|
-
// ── teardown ──────────────────────────────────────────────────────────────
|
|
1498
|
-
teardownAttempt() {
|
|
1499
|
-
this.scheduler?.stop();
|
|
1500
|
-
this.scheduler = null;
|
|
1501
|
-
this.gate = null;
|
|
1502
|
-
this.stopTracks();
|
|
1503
|
-
}
|
|
1504
|
-
stopTracks() {
|
|
1505
|
-
if (this.stream === null) return;
|
|
1506
|
-
for (const track of this.stream.getTracks()) track.stop();
|
|
1507
|
-
this.stream = null;
|
|
1508
|
-
}
|
|
1509
|
-
fail(kind, fallbackReason) {
|
|
1510
|
-
this.scheduler?.stop();
|
|
1511
|
-
this.stopTracks();
|
|
1512
|
-
this.setState("error");
|
|
1513
|
-
this.options.telemetry?.({
|
|
1514
|
-
type: "error",
|
|
1515
|
-
kind,
|
|
1516
|
-
...fallbackReason !== void 0 ? { fallbackReason } : {}
|
|
1517
|
-
});
|
|
1518
|
-
this.emit("error", { kind, retryable: kind !== "insecure" && kind !== "unsupported" });
|
|
1519
|
-
}
|
|
1520
|
-
setState(state) {
|
|
1521
|
-
this.stateValue = state;
|
|
1522
|
-
this.emit("statechange", { state });
|
|
1523
|
-
}
|
|
1524
|
-
now() {
|
|
1525
|
-
return this.options.now?.() ?? performance.now();
|
|
1526
|
-
}
|
|
1527
|
-
};
|
|
1528
|
-
function delay(ms) {
|
|
1529
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1530
|
-
}
|
|
1531
|
-
function describeError2(err) {
|
|
1532
|
-
return err instanceof Error ? err.message : String(err);
|
|
1533
|
-
}
|
|
1534
|
-
function cropImageData(video, box, targetWidth) {
|
|
1535
|
-
try {
|
|
1536
|
-
const canvas = document.createElement("canvas");
|
|
1537
|
-
const scale = targetWidth / Math.max(1, box.width);
|
|
1538
|
-
canvas.width = Math.max(1, Math.round(box.width * scale));
|
|
1539
|
-
canvas.height = Math.max(1, Math.round(box.height * scale));
|
|
1540
|
-
const ctx = canvas.getContext("2d");
|
|
1541
|
-
if (ctx === null) return null;
|
|
1542
|
-
ctx.drawImage(
|
|
1543
|
-
video,
|
|
1544
|
-
box.x,
|
|
1545
|
-
box.y,
|
|
1546
|
-
box.width,
|
|
1547
|
-
box.height,
|
|
1548
|
-
0,
|
|
1549
|
-
0,
|
|
1550
|
-
canvas.width,
|
|
1551
|
-
canvas.height
|
|
1552
|
-
);
|
|
1553
|
-
return ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
1554
|
-
} catch {
|
|
1555
|
-
return null;
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1559
|
-
0 && (module.exports = {
|
|
1560
|
-
CENTERED_FACTOR,
|
|
1561
|
-
CIRCLE_RADIUS_FACTOR,
|
|
1562
|
-
CLIP_MS,
|
|
1563
|
-
CaptureSessionV3,
|
|
1564
|
-
ClipError,
|
|
1565
|
-
ClipRecorder,
|
|
1566
|
-
DEFAULT_CLIP_MIME,
|
|
1567
|
-
DEFAULT_TIER_ORDER,
|
|
1568
|
-
DEFAULT_V3_ASSET_BASE_URL,
|
|
1569
|
-
DEVICE_PROFILES,
|
|
1570
|
-
DetectScheduler,
|
|
1571
|
-
DetectorLadderError,
|
|
1572
|
-
DeviceProfiler,
|
|
1573
|
-
EXPOSURE_BAND,
|
|
1574
|
-
FaceGateV3,
|
|
1575
|
-
IN_CIRCLE_FACTOR,
|
|
1576
|
-
KEYFRAME_CANDIDATES,
|
|
1577
|
-
KEYFRAME_WINDOW_MS,
|
|
1578
|
-
MAX_CLIP_BYTES,
|
|
1579
|
-
MIME_CANDIDATES,
|
|
1580
|
-
SHARP_REF,
|
|
1581
|
-
STOP_GRACE_MS,
|
|
1582
|
-
TIMESLICE_MS,
|
|
1583
|
-
V3_GATE_DEFAULTS,
|
|
1584
|
-
VIDEO_BPS,
|
|
1585
|
-
buildCaptureConstraints,
|
|
1586
|
-
buildLivenessV2FormData,
|
|
1587
|
-
cameraPreflight,
|
|
1588
|
-
captureMirroredKeyframe,
|
|
1589
|
-
classifyDevice,
|
|
1590
|
-
createDetector,
|
|
1591
|
-
detectIsMobile,
|
|
1592
|
-
errorCopy,
|
|
1593
|
-
exposure,
|
|
1594
|
-
extForMime,
|
|
1595
|
-
intrinsicSize,
|
|
1596
|
-
isClipTooLarge,
|
|
1597
|
-
isMediaRecorderSupported,
|
|
1598
|
-
mapGetUserMediaError,
|
|
1599
|
-
meanLuma,
|
|
1600
|
-
pickMimeType,
|
|
1601
|
-
probeDevice,
|
|
1602
|
-
sharpness,
|
|
1603
|
-
toStreamPixels,
|
|
1604
|
-
uiCopy
|
|
1605
|
-
});
|
|
1606
|
-
//# sourceMappingURL=index.cjs.map
|
|
1
|
+
"use strict";var fr=Object.create;var Y=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var hr=Object.getOwnPropertyNames;var gr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>{for(var r in e)Y(t,r,{get:e[r],enumerable:!0})},We=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hr(e))!br.call(t,i)&&i!==r&&Y(t,i,{get:()=>e[i],enumerable:!(n=pr(e,i))||n.enumerable});return t};var yr=(t,e,r)=>(r=t!=null?fr(gr(t)):{},We(e||!t||!t.__esModule?Y(r,"default",{value:t,enumerable:!0}):r,t)),vr=t=>We(Y({},"__esModule",{value:!0}),t);var nt={};N(nt,{blobBytes:()=>Ye,inspectClip:()=>Rr,inspectClipBytes:()=>Ze,webmDurationMs:()=>Hr,withWebmDuration:()=>Br});async function Rr(t){try{return Ze(await Ye(t))}catch{return null}}async function Ye(t){return typeof t.arrayBuffer=="function"?new Uint8Array(await t.arrayBuffer()):new Promise((e,r)=>{let n=new FileReader;n.onload=()=>e(new Uint8Array(n.result)),n.onerror=()=>r(n.error),n.readAsArrayBuffer(t)})}function Ze(t){if(t.length<8)return null;try{if(t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163)return Gr(t);if(ye(t,4,4)==="ftyp")return Ar(t)}catch{return null}return null}function Ar(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=[],n=null,i=null,a=0,o=(c,u)=>{let l=c;for(;l+8<=u;){let d=e.getUint32(l),f=ye(t,l+4,4),h=8;if(d===1){if(l+16>u)return;d=Number(e.getBigUint64(l+8)),h=16}else d===0&&(d=u-l);if(d<h)return;let p=Math.min(l+d,u),m=l+h;if(f==="trak"&&(n={id:0,video:!1,timescale:0,frames:0,units:0,defaultDuration:0},r.push(n)),f==="traf"&&(i=null,a=0),_r.has(f))o(m,p);else if(f==="tkhd"&&n)n.id=e.getUint32(m+(t[m]===1?20:12));else if(f==="hdlr"&&n)n.video=ye(t,m+8,4)==="vide";else if(f==="mdhd"&&n)n.timescale=e.getUint32(m+(t[m]===1?20:12));else if(f==="stts"&&n){let b=e.getUint32(m+4);for(let g=0;g<b;g++){let y=e.getUint32(m+8+g*8);n.frames+=y,n.units+=y*e.getUint32(m+12+g*8)}}else if(f==="trex"){let b=r.find(g=>g.id===e.getUint32(m+4));b&&(b.defaultDuration=e.getUint32(m+12))}else if(f==="tfhd"){let b=e.getUint32(m)&16777215;i=r.find(y=>y.id===e.getUint32(m+4))??null;let g=m+8;b&1&&(g+=8),b&2&&(g+=4),a=b&8?e.getUint32(g):i?.defaultDuration??0}else if(f==="trun"&&i){let b=e.getUint32(m)&16777215,g=e.getUint32(m+4),y=m+8;b&1&&(y+=4),b&4&&(y+=4);let S=(b&256?4:0)+(b&512?4:0)+(b&1024?4:0)+(b&2048?4:0);for(let M=0;M<g;M++)i.units+=b&256?e.getUint32(y+M*S):a;i.frames+=g}l=p}};o(0,t.length);let s=r.find(c=>c.video&&c.timescale>0);return!s||s.frames===0?null:{container:"mp4",frames:s.frames,durationMs:ke(s.units*1e3/s.timescale)}}function Ur(t,e){let r=t[e];if(r===void 0||r===0)return null;let n=Math.clz32(r)-23;if(n<1||n>4||e+n>t.length)return null;let i=0;for(let a=0;a<n;a++)i=i*256+t[e+a];return[i,n]}function rt(t,e){let r=t[e];if(r===void 0||r===0)return null;let n=Math.clz32(r)-23;if(n<1||n>8||e+n>t.length)return null;let i=r&255>>n,a=i===255>>n;for(let o=1;o<n;o++){let s=t[e+o];i=i*256+s,s!==255&&(a=!1)}return[a?-1:i,n]}function C(t,e,r){let n=0;for(let i=0;i<r;i++)n=n*256+t[e+i];return n}function Me(t){let e=[],r=0;for(;r<t.length;){let n=Ur(t,r);if(!n)break;let i=rt(t,r+n[1]);if(!i)break;let a={id:n[0],start:r,sizeAt:r+n[1],data:r+n[1]+i[1],size:i[0]};if(e.push(a),tt.has(a.id))r=a.data;else{if(a.size<0)break;r=a.data+a.size}}return e}function Gr(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=1e6,n=[],i=0,a=[];for(let c of Me(t)){if(c.data+Math.max(0,c.size)>t.length&&!tt.has(c.id))break;switch(c.id){case ve:r=C(t,c.data,c.size)||r;break;case $e:n.push({num:0,type:0});break;case Or:n.length&&(n[n.length-1].num=C(t,c.data,c.size));break;case Pr:n.length&&(n[n.length-1].type=C(t,c.data,c.size));break;case Fr:i=C(t,c.data,c.size);break;case Lr:case Nr:{let u=rt(t,c.data);if(!u||c.data+u[1]+2>t.length)break;let l=n.filter(d=>d.type===1).map(d=>d.num);if(l.length>0&&!l.includes(u[0]))break;a.push((i+e.getInt16(c.data+u[1]))*r/1e6);break}default:break}}if(a.length===0)return null;a.sort((c,u)=>c-u);let o=a.slice(1).map((c,u)=>c-a[u]),s=o.length?o.sort((c,u)=>c-u)[Math.floor(o.length/2)]:0;return{container:"webm",frames:a.length,durationMs:ke(a[a.length-1]-a[0]+s)}}function Br(t,e){if(!(e>0))return null;let r=Me(t),n=r.find(m=>m.id===je);if(!n||n.size!==-1||r.some(m=>m.id===Vr))return null;let i=r.find(m=>m.id===Qe);if(!i||i.size<0||i.data+i.size>t.length)return null;let a=1e6,o=[];for(let m of r)m.start<i.data||m.start>=i.data+i.size||(m.id===ve&&(a=C(t,m.data,m.size)||a),m.id!==et&&o.push(t.subarray(m.start,m.data+m.size)));let s=new Uint8Array(11);s.set([68,137,136]),new DataView(s.buffer).setFloat64(3,e*1e6/a);let c=o.reduce((m,b)=>m+b.length,0)+s.length,u=new Uint8Array(12);u.set([21,73,169,102,1]);let l=c;for(let m=11;m>=5;m--)u[m]=l&255,l=Math.floor(l/256);let d=t.subarray(i.data+i.size),f=new Uint8Array(i.start+u.length+c+d.length),h=0,p=m=>{f.set(m,h),h+=m.length};return p(t.subarray(0,i.start)),p(u),o.forEach(p),p(s),p(d),f}function Hr(t){let e=1e6,r=null,n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let i of Me(t))if(i.id===ve&&(e=C(t,i.data,i.size)||e),i.id===et&&(r=i.size===8?n.getFloat64(i.data):i.size===4?n.getFloat32(i.data):null),i.id===Je)break;return r===null?null:ke(r*e/1e6)}function ye(t,e,r){let n="";for(let i=0;i<r&&e+i<t.length;i++)n+=String.fromCharCode(t[e+i]);return n}function ke(t){return Math.round(t*10)/10}var _r,je,Qe,Dr,$e,Je,Ir,ve,et,Or,Pr,Fr,Lr,Nr,Vr,tt,it=L(()=>{"use strict";_r=new Set(["moov","trak","mdia","minf","stbl","mvex","moof","traf","edts"]);je=408125543,Qe=357149030,Dr=374648427,$e=174,Je=524531317,Ir=160,ve=2807729,et=17545,Or=215,Pr=131,Fr=231,Lr=163,Nr=161,Vr=290298740,tt=new Set([je,Qe,Dr,$e,Je,Ir])});function Tt(t){let e=(t??"").trim().toLowerCase();return e.length===0?"unknown":sn.some(r=>e.includes(r))?"known_virtual":cn.some(r=>r.test(e))?"platform":"unknown"}var sn,cn,wt=L(()=>{"use strict";sn=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],cn=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i]});var xt={};N(xt,{bounded:()=>q,cameraHash:()=>Et,hex16:()=>oe,noteCameraTrait:()=>dn});function q(t,e){return new Promise(r=>{let n=setTimeout(()=>r(void 0),e),i=a=>{clearTimeout(n),r(a)};try{t().then(i,()=>i(void 0))}catch{i(void 0)}})}async function oe(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(t)));return Array.from(new Uint8Array(e).subarray(0,8),r=>r.toString(16).padStart(2,"0")).join("")}function ln(t){try{return t.getSettings?.().facingMode==="environment"}catch{return!1}}async function Et(t){try{if(t.readyState==="ended"||ln(t))return;let e={};try{e=t.getCapabilities?.()??{}}catch{}let r=await q(()=>navigator.mediaDevices.enumerateDevices(),un);return await oe([Oe(e.width),Oe(e.height),Oe(e.frameRate),Ie(e.facingMode),Ie(e.focusMode),Ie(e.exposureMode),Tt(t.label),r?.filter(n=>n.kind==="videoinput").length??null])}catch{return}}async function dn(t,e){let r=await Et(t);r&&e.noteCamera(r)}var un,Ie,Oe,Pe=L(()=>{"use strict";wt();un=1e3;Ie=t=>Array.isArray(t)?[...t].sort():null,Oe=t=>{let e=t;return e==null?null:[e.min??null,e.max??null]}});var At={};N(At,{computePrint:()=>Tn,readHints:()=>_t});function Ct(t,e){if(typeof t!="string")return;let r=t.trim();return r.length>0&&r.length<=e?r:void 0}async function _t(){let t=navigator.userAgentData;if(typeof t?.getHighEntropyValues!="function")return;let e=await q(()=>t.getHighEntropyValues(["model","platformVersion"]),hn);if(e==null)return;let r=Ct(e.model,bn),n=Ct(e.platformVersion,yn),i={...r!==void 0?{model:r}:{},...n!==void 0?{platformVersion:n}:{}};return Object.keys(i).length>0?i:void 0}async function kn(){let[t,e]=await Promise.all([new Rt.Thumbmark({stabilize:["private","iframe"],exclude:["permissions","webrtc","speech"],logging:!1,collect_beacon:!1,timeout:fn}).get(),_t()]),r=t?.thumbmark;if(typeof r!="string"||r.length<vn||r.length>Mn)return;let n={};for(let i of mn){let a=t.components?.[i];a==null||a.timeout==="true"||(n[i]=await oe(a))}return{hash:r,c:n,...e!==void 0?{hints:e}:{}}}function Sn(){return new Promise(t=>{typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(()=>t(),{timeout:gn}):t()})}async function Tn(t){return t()||(await Sn(),t())?"busy":q(kn,pn)}var Rt,mn,fn,pn,hn,gn,bn,yn,vn,Mn,Dt=L(()=>{"use strict";Rt=require("@thumbmarkjs/thumbmarkjs");Pe();mn=["canvas","webgl","audio","fonts","hardware","screen","system","locales","math","plugins"],fn=2e3,pn=4e3,hn=1e3,gn=2e3,bn=64,yn=32,vn=8,Mn=128});var ir={};N(ir,{RANK_CANDIDATES:()=>qn,RANK_TOLERANCE:()=>le,RANK_WINDOW_MS:()=>Xn,ROLL_ZERO_DEG:()=>Zn,SHARPNESS_REPORT_MAX:()=>rr,YAW_REPORT_MAX:()=>tr,YAW_ZERO_IOD:()=>Yn,collectRankedKeyframes:()=>nr,default:()=>Qn,featuresOf:()=>Jt,frontalOf:()=>$t,rankKeyframes:()=>er});function $t(t){let e=t.eyes;if(e===void 0)return{frontal:1,yaw:null,roll:null};let r=e.right.x-e.left.x,n=e.right.y-e.left.y,i=r*r+n*n;if(i===0)return{frontal:1,yaw:null,roll:null};let a=Math.abs(Math.atan2(n,Math.abs(r))*180/Math.PI),o=Qt(1-a/30),s=null,c=t.nose;if(c!==void 0){let u=(e.left.x+e.right.x)/2,l=(e.left.y+e.right.y)/2;s=Math.abs(((c.x-u)*r+(c.y-l)*n)/i),o*=Qt(1-s/.5)}return{frontal:o,yaw:s,roll:a}}function Jt(t,e){return t===null?{face:!1,frontal:0,yaw:null,roll:null,eyes:null,score:0,sharpness:e}:{face:!0,...$t(t),eyes:null,score:t.score,sharpness:e}}function er(t){let e=t.map((i,a)=>a),r=(i,a)=>{let o=Number.NEGATIVE_INFINITY;for(let s of e)o=Math.max(o,i(t[s]));e=e.filter(s=>i(t[s])>=o-a)};r(i=>i.frontal,le.frontal),r(i=>i.eyes??1,le.eyes),r(i=>i.score,le.score);let n=-1;for(let i of e)(n===-1||t[i].sharpness>t[n].sharpness)&&(n=i);return n}function jn(t){return{face:t.face,frontal:F(t.frontal),...t.yaw!==null?{yaw:Math.min(F(t.yaw),tr)}:{},...t.roll!==null?{roll:F(t.roll)}:{},...t.eyes!==null?{eyes:F(t.eyes)}:{},score:F(t.score),sharpness:Math.min(F(t.sharpness),rr)}}async function nr(t,e){let{options:r}=t,n=r.video,i=r.now??(()=>performance.now()),a=r.captureKeyframe??(f=>t.defaultKeyframe(f)),o=600/3,s=[],c=[],u=0;for(let f=0;f<4;f+=1){if(e!==t.attempt)return null;let h=t.detector,p=Promise.resolve(null),m,b=0;try{if(h!==null){let M=t.profiler?.profile.inputWidth??160,k=r.makeSnapshot?.(n,M)??t.defaultSnapshot(n,M);m=a(n).then(E=>(b=i(),E));let v=i();p=h.detect(k,n.videoWidth,n.videoHeight).then(E=>(u+=i()-v,E),()=>null)}else m=a(n).then(M=>(b=i(),M));let[y,S]=await Promise.all([m,p]);s.push(y),c.push(Jt(S,y.sharpness))}catch{m?.catch(()=>{})}let g=b>0?Math.max(0,i()-b):0;f<3&&await new Promise(y=>setTimeout(y,Math.max(0,o-g)))}if(e!==t.attempt)return null;let l=er(c);if(l===-1)return null;let d=0;c.forEach((f,h)=>{f.sharpness>c[d].sharpness&&(d=h)});try{r.telemetry?.({type:"keyframe",tier:t.detector?.tier??null,chosen:l,sharpest:d,detectMs:Math.round(u),candidates:c.map(jn)})}catch{}return s[l]??null}var qn,Xn,Yn,Zn,le,Qt,F,tr,rr,Qn,ar=L(()=>{"use strict";qn=4,Xn=600,Yn=.5,Zn=30,le={frontal:.1,eyes:.1,score:.05},Qt=t=>t<0?0:t>1?1:t;F=t=>Number.isFinite(t)?Math.round(t*1e3)/1e3:0,tr=99,rr=999999;Qn=nr});var ni={};N(ni,{CENTERED_FACTOR:()=>Zr,CIRCLE_RADIUS_FACTOR:()=>Xr,CLIP_MS:()=>$,CaptureSessionV3:()=>Ke,ClipError:()=>T,ClipRecorder:()=>U,DEFAULT_CLIP_MIME:()=>j,DEFAULT_TIER_ORDER:()=>bt,DEFAULT_V3_ASSET_BASE_URL:()=>gt,DEVICE_PROFILES:()=>Mt,DetectScheduler:()=>z,DetectorLadderError:()=>_,DeviceProfiler:()=>W,ENCODER_TAIL_MS:()=>st,EXPOSURE_BAND:()=>K,FRAME_POLL_MS:()=>ut,FaceGateV3:()=>I,GATE_SNAPSHOT_MS:()=>cr,GateBlockStats:()=>P,HOLD_UPRIGHT_KEY:()=>de,INSPECT_WAIT_MS:()=>lt,IN_CIRCLE_FACTOR:()=>Yr,KEYFRAME_CANDIDATES:()=>me,KEYFRAME_WINDOW_MS:()=>lr,MAX_CLIP_BYTES:()=>Q,MAX_OVERRUN_MS:()=>ct,MIME_CANDIDATES:()=>Z,PHONE_MAX_SHORT_SIDE:()=>mt,PROVENANCE_WAIT_MS:()=>dr,SECOND_FACE_AREA_RATIO:()=>ht,SHARP_REF:()=>ki,SHORT_CLIP_TOLERANCE_MS:()=>dt,STOP_GRACE_MS:()=>ot,TIMESLICE_MS:()=>at,UPRIGHT_WATCH_MS:()=>ur,V3_GATE_DEFAULTS:()=>vt,VIDEO_BPS:()=>Te,betterTake:()=>we,blockReasonOf:()=>jt,buildCaptureConstraints:()=>Ee,buildLivenessV2FormData:()=>Sr,cameraPreflight:()=>he,captureMirroredKeyframe:()=>ge,classifyDevice:()=>De,countExtraFaces:()=>B,createDetector:()=>A,detectFormFactor:()=>ee,detectIsMobile:()=>xe,errorCopy:()=>Tr,exposure:()=>Re,extForMime:()=>fe,intrinsicSize:()=>R,isClipTooLarge:()=>V,isMediaRecorderSupported:()=>kr,mapGetUserMediaError:()=>pe,meanLuma:()=>ie,needsRetake:()=>J,pickMimeType:()=>Mr,probeDevice:()=>Ae,sharpness:()=>ae,toStreamPixels:()=>H,trackFacingMode:()=>G,uiCopy:()=>wr});module.exports=vr(ni);var Z=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function Mr(){let t=globalThis.MediaRecorder;return!t||typeof t.isTypeSupported!="function"?"":Z.find(e=>t.isTypeSupported(e))??""}var j="video/webm";function pe(t){if(t instanceof TypeError)return"insecure";switch(t?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function he(){let t=globalThis;if(typeof t.window<"u"&&t.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=t.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function kr(){let t=globalThis.MediaRecorder;return typeof t<"u"&&typeof t.isTypeSupported=="function"}var Q=8*1024*1024;function V(t){return t.size>Q}function fe(t){let e=(t||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function Sr(t){let{token:e,clip:r,keyframe:n}=t,i=t.ts??Date.now(),a=r.type||j,o=n.type||"image/jpeg",s=new FormData;return s.append("token",e),s.append("clip",new File([r],`liveness-${i}.${fe(a)}`,{type:a})),s.append("keyframe",new File([n],`keyframe-${i}.${fe(o)}`,{type:o})),s}function ge(t,e,r=.92){return new Promise((n,i)=>{let a=t.videoWidth,o=t.videoHeight;if(!a||!o){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=a,e.height=o,s.scale(-1,1),s.drawImage(t,-a,0),e.toBlob(c=>c?n(c):i(new Error("empty-keyframe")),"image/jpeg",r)})}var Tr={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},wr={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var Er=[...Z.filter(t=>t.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],ze=new Set;function xr(t){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(t??"");return e?Number(e[1]):null}function qe(t=Cr(),e=globalThis.navigator?.userAgent){if(t===void 0)return"";let r=xr(e)===126;for(let n of Er)if(!(ze.has(n)||r&&n.startsWith("video/mp4")))try{if(t(n))return n}catch{}return""}function be(t){t!==""&&ze.add(t)}function Xe(t){return t.replace(/^video\/x-matroska/i,"video/webm")}function Cr(){let t=globalThis.MediaRecorder;return t&&typeof t.isTypeSupported=="function"?e=>t.isTypeSupported(e):void 0}var $=2500,at=1e3,ot=1500,Te=25e5,st=100,ct=700,ut=20,lt=1500,Se=null;function Kr(){return Se??(Se=Promise.resolve().then(()=>(it(),nt)).catch(t=>{throw Se=null,t})),Se.catch(()=>null)}var T=class extends Error{constructor(e,r){super(r??e),this.kind=e}},dt=100;function J(t,e){return t.stats===void 0?!1:t.stats===null?!0:t.stats.durationMs<e-dt}function we(t,e){return t.stats?e.stats?t.stats.durationMs>e.stats.durationMs:!0:!1}var U=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,r,n,i=$,a){let o=qe(),s=Kr();return this.recordRaw(e,r,n,i,a,o).then(c=>Wr(c,s),c=>{throw c instanceof T&&(c.requestedMimeType=o),c})}recordRaw(e,r,n,i,a,o){return this.recorder&&!this.settled?Promise.reject(new T("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((s,c)=>{let u;try{u=new MediaRecorder(e,o?{mimeType:o,videoBitsPerSecond:Te}:{videoBitsPerSecond:Te})}catch{try{u=new MediaRecorder(e)}catch{c(new T("unsupported"));return}}this.recorder=u;let l=g=>{this.settled||(this.settled=!0,this.clearTimers(),g())},d=()=>l(()=>{let g=Xe(u.mimeType||o||j),y=new Blob(this.chunks,{type:g});if(y.size===0){c(new T("generic","empty clip"));return}if(V(y)){c(new T("cliptoolarge"));return}s({blob:y,mimeType:g,requestedMimeType:o})});u.ondataavailable=g=>{g.data&&g.data.size&&(this.chunks.push(g.data),this.bytes+=g.data.size,this.bytes>Q&&l(()=>{try{u.state!=="inactive"&&u.stop()}catch{}c(new T("cliptoolarge"))}))},u.onstop=d,u.onerror=()=>l(()=>c(new T("generic")));let f=this.now();if(n!==void 0||a!==void 0){let g=!1;u.onstart=()=>{if(!(g||this.settled)&&(g=!0,f=this.now(),n!==void 0))try{n()}catch{}}}try{u.start(at)}catch{l(()=>c(new T("generic")));return}let h=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||r?.(),u.state!=="inactive"){try{u.stop()}catch{d()}this.graceTimer=setTimeout(d,ot)}else d()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(h,i);return}let m=null,b=!1;this.hardStopTimer=setTimeout(h,i+ct),this.pollTimer=setInterval(()=>{if(this.settled||b)return;let g=null;try{g=a.latest()}catch{g=null}let y=g?.presentationTimeMs;y!==void 0&&Number.isFinite(y)&&y>=f&&m===null&&(m=y);let S=m!==null&&y!==void 0&&y-m>=i,M=m===null&&this.now()-p>=i;if(!(!S&&!M)){if(b=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,M){h();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(h,st)}},ut)}))}stop(e){this.clearTimers();let r=this.recorder;if(r&&r.state!=="inactive")try{r.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};async function Wr(t,e){let r,n=new Promise(u=>{r=setTimeout(()=>u(null),lt)}),i=await Promise.race([e,n]);if(clearTimeout(r),i===null)return t;let a;try{a=await i.blobBytes(t.blob)}catch{return{...t,stats:null}}let o=i.inspectClipBytes(a);if(o?.container!=="webm")return{...t,stats:o};let s=i.withWebmDuration(a,o.durationMs);if(s===null)return{...t,stats:o};let c=i.inspectClipBytes(s);return c===null||c.frames!==o.frames||c.durationMs!==o.durationMs?{...t,stats:o}:{...t,blob:new Blob([s],{type:t.blob.type}),stats:o}}function Ee(t,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}var mt=600;function ee(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let t=navigator.userAgentData,e=t?.mobile||/Android|i(Pad)?OS/.test(String(t?.platform)),r=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(r))return"phone";if(/iPad/i.test(r))return"tablet";if(/Android/i.test(r))return/Mobile/i.test(r)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(r))return"phone";if(!e){if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(r))return"tablet";if(/Windows NT|CrOS/.test(r)||!qr())return"desktop"}let n=zr();return n>0&&n<mt?"phone":"tablet"}function xe(){return ee()!=="desktop"}function zr(){try{let t=window.screen,e=Number(t?.width??0),r=Number(t?.height??0);return e>0&&r>0?Math.min(e,r):0}catch{return 0}}function G(t){try{let r=t?.getVideoTracks?.()[0]?.getSettings?.().facingMode;return r==="user"||r==="environment"?r:null}catch{return null}}function qr(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var Xr=.45,Yr=.9,Zr=.4;var ft=1e4,te=class t{constructor(e,r){this.tier="blaze";this.inner=e,r!==void 0&&(this.fallbackReason=r)}static async create(e,r){let n=await import("@mediapipe/tasks-vision"),i=await n.FilesetResolver.forVisionTasks(e),a=await n.FaceDetector.createFromOptions(i,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new t(a,r)}async detect(e,r,n){let i;try{i=this.inner.detect(e).detections}catch{return null}let a=jr(i);if(a?.boundingBox===void 0)return null;let o=R(e),s=Qr(a.keypoints,o),c=a.keypoints?.[2],u={box:{x:a.boundingBox.originX,y:a.boundingBox.originY,width:a.boundingBox.width,height:a.boundingBox.height},...s!==void 0?{eyes:s}:{},...c!==void 0?{nose:{x:c.x*o.width,y:c.y*o.height}}:{},score:a.categories[0]?.score??0,extraFaces:B(i.map(l=>l.boundingBox??{width:0,height:0}),i.indexOf(a))};return H(u,e,r,n)}destroy(){try{this.inner.close()}catch{}}};function jr(t){let e,r=-1;for(let n of t){let i=n.categories[0]?.score??0;i>r&&(e=n,r=i)}return e}function Qr(t,e){let r=t?.[0],n=t?.[1];if(r===void 0||n===void 0)return;let i=s=>({x:s.x*e.width,y:s.y*e.height}),[a,o]=[i(r),i(n)];return a.x<=o.x?{left:a,right:o}:{left:o,right:a}}function $r(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let t=document.createElement("canvas");return t.width=2,t.height=2,t}var Jr=4;async function pt(){let t=globalThis.FaceDetector;if(typeof t!="function")return{ok:!1,reason:"unsupported"};try{let e=new t({fastMode:!0,maxDetectedFaces:Jr});return await e.detect($r()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var re=class{constructor(e,r){this.tier="native";this.inner=e,r!==void 0&&(this.fallbackReason=r)}async detect(e,r,n){let i;try{i=await this.inner.detect(e)}catch{return null}let a=i.map(l=>l.boundingBox),o=-1;a.forEach((l,d)=>{let f=a[o];(f===void 0||l.width*l.height>f.width*f.height)&&(o=d)});let s=i[o];if(s===void 0)return null;let c=en(s.landmarks),u={box:{x:s.boundingBox.x,y:s.boundingBox.y,width:s.boundingBox.width,height:s.boundingBox.height},...c!==void 0?{eyes:c}:{},score:1,extraFaces:B(a,o)};return H(u,e,r,n)}destroy(){}};function en(t){if(t===void 0)return;let e=t.filter(i=>i.type==="eye").map(i=>i.locations[0]).filter(i=>i!==void 0),[r,n]=e;if(!(r===void 0||n===void 0))return r.x<=n.x?{left:r,right:n}:{left:n,right:r}}var ht=.25;function B(t,e){let r=t[e],n=r===void 0?0:r.width*r.height;if(!(n>0))return 0;let i=0;return t.forEach((a,o)=>{o!==e&&a.width*a.height>=ht*n&&(i+=1)}),i}var gt="/models-v3",bt=["native","blaze"],_=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function R(t){let e=t;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let r=typeof e.width=="number"?e.width:0,n=typeof e.height=="number"?e.height:0;return{width:r,height:n}}function H(t,e,r,n){let i=R(e),a=i.width>0?r/i.width:1,o=i.height>0?n/i.height:1,s=c=>({x:c.x*a,y:c.y*o});return{box:{x:t.box.x*a,y:t.box.y*o,width:t.box.width*a,height:t.box.height*o},...t.eyes!==void 0?{eyes:{left:s(t.eyes.left),right:s(t.eyes.right)}}:{},...t.nose!==void 0?{nose:s(t.nose)}:{},score:t.score,...t.extraFaces!==void 0?{extraFaces:t.extraFaces}:{}}}function tn(t){return t instanceof Error?t.message:String(t)}async function A(t){let e=t.preferred??bt,r=[];for(let n of e){if(n==="native"){let i=await pt();if(i.ok)return new re(i.instance,Ce(r));r.push(`native:${i.reason}`);continue}try{return await rn(te.create(t.v3AssetBaseUrl??gt,Ce(r)),t.blazeInitTimeoutMs??ft)}catch(i){r.push(i instanceof ne?"blaze:blaze_init_timeout":`blaze:${tn(i)}`)}}throw new _(Ce(r)??"no_tier_available")}function Ce(t){return t.length>0?t.join("; "):void 0}var ne=class extends Error{};function rn(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>{n(new ne(`init exceeded ${e}ms`)),t.then(a=>a.destroy(),()=>{})},e);t.then(a=>{clearTimeout(i),r(a)},a=>{clearTimeout(i),n(a)})})}var ki=180,K=[100,190],nn=64;function yt(t,e){return .299*(t[e]??0)+.587*(t[e+1]??0)+.114*(t[e+2]??0)}function ie(t){let{data:e,width:r,height:n}=t,i=r*n;if(i===0)return 0;let a=0;for(let o=0;o<i;o+=1)a+=yt(e,o*4);return a/i}function ae(t){let{data:e,width:r,height:n}=t;if(r<3||n<3)return 0;let i=new Float32Array(r*n);for(let l=0;l<i.length;l+=1)i[l]=yt(e,l*4);let a=0,o=0,s=0;for(let l=1;l<n-1;l+=1)for(let d=1;d<r-1;d+=1){let f=l*r+d,h=(i[f-r]??0)+(i[f-1]??0)+(i[f+1]??0)+(i[f+r]??0)-4*(i[f]??0);a+=h,o+=h*h,s+=1}if(s===0)return 0;let c=a/s,u=o/s-c*c;return Math.min(1,Math.max(0,u)/180)}function Re(t){let e=ie(t),[r,n]=K,i=e<r?r-e:e>n?e-n:0;return Math.max(0,1-i/nn)}var vt=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),D=t=>Math.min(1,Math.max(0,t)),I=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...vt,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:r,quality:n,timestampMs:i}=e,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let o={presence:0,single:1,centering:0,size:0,pose:0,sharpness:D(n.sharpness),exposure:D(n.exposure),motion:1};if(r!==null){o.presence=1,o.single=(r.extraFaces??0)>0?0:1;let l=this.geometryOf(r,e);o.centering=l.centering,o.size=l.size,o.pose=l.pose,o.motion=this.motionOf(l.center,l.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(o.presence,o.single,o.centering,o.size,o.pose,o.sharpness,o.exposure,o.motion);this.p=D(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*a),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(l=>l.at>=i-this.t.READY_WINDOW_MS);let c=this.qWindow.map(l=>l.q);if(c.length>=3){let l=Math.min(...c),d=c.indexOf(l);c=c.filter((f,h)=>h!==d)}let u=this.p>=1&&c.every(l=>l>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:o,guidanceKey:this.guidanceOf(o,n,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,r){let{box:n,eyes:i}=e,a={x:r.frameWidth/2,y:r.frameHeight/2},o=Math.min(r.frameWidth,r.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:n.x+n.width/2,y:n.y+n.height/2-this.t.BOX_EYE_OFFSET_FACTOR*n.height},c=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*n.width,u=Math.hypot(s.x-a.x,s.y-a.y),l=c<=0?0:1-D(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),d=o>0?c/o:0;this.lastSizeDirection=d<this.t.SIZE_IDEAL_MIN?"far":d>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;d<this.t.SIZE_HARD_MIN||d>this.t.SIZE_HARD_MAX?f=0:d<this.t.SIZE_IDEAL_MIN?f=(d-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):d>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-d)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-D(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:c,centering:l,size:f,pose:h}}motionOf(e,r,n){let i=this.lastCenter;if(this.lastCenter={...e,at:n},i===null||r<=0)return 1;let a=(n-i.at)/1e3;if(a<=0)return 1;let o=Math.hypot(e.x-i.x,e.y-i.y)/r/a;o<=this.t.MOTION_DEADBAND_IOD_PER_S&&(o=0);let s=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=s*o+(1-s)*this.velocityEma,1-D(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,r,n){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(r);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(n<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(r)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=i[0];for(let o of i)e[o[0]]<e[a[0]]&&(a=o);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let r=(K[0]+K[1])/2;return e.meanLuma<r?"fcv3.more_light":"fcv3.too_bright"}};var Mt=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),an=new Uint8Array([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,15,253,98,11]);function Ae(){let t=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(an)}catch{e=!1}return{cores:t?.hardwareConcurrency??2,memGB:t?.deviceMemory??null,simd:e}}function De(t){let e=t.memGB??4;return t.cores<4||e<3?"LOW":t.cores>=8&&e>=6?"HIGH":"MID"}var _e=["LOW","MID","HIGH"],W=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return Mt[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let r=this.samples.reduce((n,i)=>n+i,0)/this.samples.length;if(r>70)this.current="LOW";else if(r<25){let n=_e.indexOf(this.current);this.current=_e[Math.min(_e.length-1,n+1)]??this.current}return this.current}};var z=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let r=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),r()}))};r();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((r,n)=>r+n,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var kt="0.1.0-rc.31";var on=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function St(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return on.test(e)}var It="sekyro.did",wn=1e4,Ft=()=>globalThis.process?.versions?.node,Ot;function Pt(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function En(){try{let t=localStorage.getItem(It);if(t)return t;let e=Pt();return e!==void 0&&localStorage.setItem(It,e),e}catch{return Ot??(Ot=Pt()),Ot}}async function xn(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function Cn(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function Rn(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function _n(t){let e,r,n,i,a,o,s=()=>o?.readyState==="live",c=()=>{a!==void 0||!globalThis.crypto?.subtle||Ft()||s()||(a=Promise.race([Promise.resolve().then(()=>(Dt(),At)),new Promise(u=>setTimeout(u,wn))]).then(u=>u?.computePrint(s)).then(u=>{u==="busy"?a=void 0:i=u}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(u){u&&(e=u.slice(0,128))},noteCamera(u){r=u},noteCameraTrack(u){o=u},async deviceHeader(){try{n??(n=xn().catch(()=>""));let u=[];navigator.webdriver&&u.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&u.push("headless");let l=await n,d=En(),f={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],ids:[...d?[{kind:"web_local",value:d.slice(0,128)}]:[],...l?[{kind:"web_fp",value:l}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...Cn(),...e?{cameraLabel:e}:{},...u.length?{signals:u}:{},...i?{print:{v:2,...i,...r?{camera:r}:{}}}:{},...St()?{inApp:!0}:{}},h=Rn(JSON.stringify(f));return c(),h}catch{return}},printReady(){return a??Promise.resolve()}}}var Fe=Symbol.for("sekyro.web.clientContext"),Le=globalThis,Ne=Le[Fe]??(Le[Fe]=_n({sdk:`@sekyro/web@${kt}`}));function Lt(t){try{let e=t.getVideoTracks?.()[0];if(e){if(Ne.noteCameraLabel(e.label),Ne.noteCameraTrack(e),Ft())return;Promise.resolve().then(()=>(Pe(),xt)).then(r=>r.noteCameraTrait(e,Ne)).catch(()=>{})}}catch{}}var Ve=Symbol.for("sekyro.web.cameraStreams"),Ue=globalThis,An=Ue[Ve]??(Ue[Ve]=new Set);function Nt(t){try{An.add(t)}catch{}}var Dn=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],In=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function On(t){let e=(t??"").trim().toLowerCase();return e.length===0?"unknown":Dn.some(r=>e.includes(r))?"known_virtual":In.some(r=>r.test(e))?"platform":"unknown"}function Vt(t){if(typeof t!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(t))}catch{return!1}}function Pn(t=globalThis){return Vt(t.navigator?.mediaDevices?.getUserMedia)&&Vt(t.MediaStreamTrack?.prototype?.getSettings)}async function Fn(t,e=globalThis){let r=e.crypto?.subtle?.digest;if(typeof r=="function")try{let n=new Uint8Array(await r.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(t)));return Array.from(n.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ut(t,e=globalThis){let r={};try{r=typeof t.getSettings=="function"?t.getSettings()??{}:{}}catch{r={}}let n={};if((r.facingMode==="user"||r.facingMode==="environment"||r.facingMode==="left"||r.facingMode==="right")&&(n.facingMode=r.facingMode),typeof r.frameRate=="number"&&Number.isFinite(r.frameRate)&&(n.frameRate=r.frameRate),typeof r.width=="number"&&Number.isFinite(r.width)&&(n.width=r.width),typeof r.height=="number"&&Number.isFinite(r.height)&&(n.height=r.height),typeof r.deviceId=="string"&&r.deviceId.length>0){let a=await Fn(r.deviceId,e);a!==void 0&&(n.deviceIdHash=a)}let i;try{i=t.label}catch{i=void 0}return{trackSettings:n,capabilitiesPresent:typeof t.getCapabilities=="function",labelClass:On(i),prototypesIntact:Pn(e)}}var Ge=t=>Math.round(t*100)/100;function Gt(t){let e=t,r=typeof e?.requestVideoFrameCallback=="function",n=null,i=null,a=0,o=0,s=0,c=0,u=0,l=0,d=()=>{!r||e?.requestVideoFrameCallback===void 0||(n=e.requestVideoFrameCallback((f,h)=>{if(n=null,!r)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;o+=1;let b=m-s;s+=b/o,c+=b*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,l+=1),a+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},d()}))};return d(),{latest:()=>i,stats:()=>({n:a,meanGapMs:o===0?0:Ge(s),stdGapMs:o<2?0:Ge(Math.sqrt(c/(o-1))),captureLatencyMs:l===0?null:Ge(u/l)}),stop:()=>{r&&(r=!1,n!==null&&e?.cancelVideoFrameCallback?.(n),n=null)}}}function Bt(t,e,r){return{...t,rvfc:e,rampPainter:r}}var Ln=["magenta","yellow","green","blue"];var Nn=4,Vn=4,se=t=>typeof t=="number"&&Number.isFinite(t);function ce(t){if(typeof t!="object"||t===null)return!1;let e=t;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(n=>Ln.includes(n))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let r=-1;for(let n of e.onsetsMs){if(!se(n)||n<0||n<=r)return!1;r=n}return!(!se(e.holdMs)||e.holdMs<=0||!se(e.endMs)||e.endMs<=r||!se(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function Ht(t,e){return ce(t)?Math.max(e,Math.ceil(t.clipMs)):e}function Kt(t,e){let r=e.now??(()=>performance.now()),n=ce(t)?t:void 0,i=[],a=null,o=null,s=null,c=!1,u=null,l=p=>{u=p;try{e.paint(p)}catch{}},d=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(o??p)},f=(p,m,b=0)=>{if(c)return;let g=Math.max(0,p-d(r()));a=setTimeout(()=>{if(a=null,!c){if(b<Nn&&d(r())<p-Vn){f(p,m,b+1);return}m()}},g)},h=p=>{if(n===void 0)return;let m=n.endMs;if(p>=n.colours.length){f(m,()=>l(null));return}let b=n.onsetsMs[p],g=p+1<n.onsetsMs.length?n.onsetsMs[p+1]:m;f(b,()=>{let y=d(r());if(y>m){u!==null&&l(null);return}let S=n.colours[p];l(S);let M=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(M,Math.round(y)),colour:S});let k=b+n.holdMs;if(k<g){f(k,()=>{if(d(r())>m){u!==null&&l(null);return}l("dark"),h(p+1)});return}h(p+1)})};return{started(p){if(n===void 0||c||o!==null)return;o=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,u!==null&&l(null))},report(){return n===void 0?void 0:{nonce:n.nonce,rendered:[...i]}}}}var Un=40;function O(t){if(t===null||typeof t!="object"&&typeof t!="function")return;let e;try{e=t.name}catch{return}return Gn(e)}function Gn(t){if(typeof t!="string")return;let e=t.replace(/[^A-Za-z]/g,"").slice(0,Un);return e===""?void 0:e}function Wt(t){let e=pe(t);if(e!=="generic")return e;switch(O(t)){case"AbortError":return"inuse";case"SecurityError":return"permission";default:return e}}function Bn(t){let e=t.toLowerCase();return e===""?"unknown":/front|facing front|user|selfie|face ?time/.test(e)?"front":/ultra|0\.5x|wide angle/.test(e)?"ultra":/tele|zoom|periscope|[2-9]x/.test(e)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(e)?"depth":/dual|triple/.test(e)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(e)?"main":"unknown"}function Hn(t){let e=/camera2?\s*(\d+)/i.exec(t);return e?Number(e[1]):Number.POSITIVE_INFINITY}function zt(t){let e={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return t.filter(r=>(r.kind===void 0||r.kind==="videoinput")&&r.deviceId!=="").map((r,n)=>({id:r.deviceId,kind:Bn(r.label),index:Hn(r.label),i:n})).filter(r=>e[r.kind]<9).sort((r,n)=>e[r.kind]-e[n.kind]||r.index-n.index||r.i-n.i).map(r=>r.id)}var X=class extends Error{constructor(){super("the back camera could not be opened");this.name="BackCameraUnavailableError"}},qt=new Set(["NotAllowedError","PermissionDeniedError","SecurityError"]);function Xt(t){try{return String(t?.name??"")}catch{return""}}function Be(t){if(t!==null)for(let e of t.getTracks())e.stop()}async function Yt(t,e,r){let n=l=>({video:{...e,...l},audio:!1});if(t==="user")return r.getUserMedia(n({facingMode:"user"}));let i=l=>G(l)!=="user";try{let l=await r.getUserMedia(n({facingMode:{exact:"environment"}}));if(i(l))return l;Be(l)}catch(l){if(qt.has(Xt(l)))throw l}let a=!1,o=async()=>{if(r.enumerateDevices===void 0||a)return null;let l;try{l=zt(await r.enumerateDevices()).slice(0,3)}catch{return null}a=l.length>0;for(let d of l){let f;try{f=await r.getUserMedia(n({deviceId:{exact:d}}))}catch(h){if(qt.has(Xt(h)))throw h;continue}if(i(f))return f;Be(f)}return null},s=await o();if(s!==null)return s;let c=await r.getUserMedia(n({facingMode:"environment"}));if(i(c))return c;Be(c);let u=await o();if(u!==null)return u;throw new X}var x=1;function Zt(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Wn(t,e={}){let r=e.createDetector??A,n=null;t.onmessage=i=>{let a=i.data;if(a.v!==x){a.bitmap?.close?.();return}if(a.type==="init"){r(a.options).then(o=>{n=o;let s={v:x,type:"ready",tier:o.tier,...o.fallbackReason!==void 0?{fallbackReason:o.fallbackReason}:{}};t.postMessage(s)});return}if(a.type==="detect"){let o=s=>{let c={v:x,type:"result",id:a.id,observation:s};t.postMessage(c),a.bitmap.close?.()};if(n===null){o(null);return}n.detect(a.bitmap,a.streamWidth,a.streamHeight).then(o,()=>o(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Wn(self);var ue=class t{constructor(e,r){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=r.tier,r.fallbackReason!==void 0&&(this.fallbackReason=r.fallbackReason),e.addEventListener("message",n=>{let i=n.data;if(i.v!==x||i.type!=="result")return;let a=this.pending.get(i.id);this.pending.delete(i.id),a?.(i.observation)})}static create(e,r,n=1e4){return new Promise((i,a)=>{let o=setTimeout(()=>{e.removeEventListener("message",s),e.terminate(),a(new Error(`worker detector not ready within ${n}ms`))},n),s=u=>{let l=u.data;l.v!==x||l.type!=="ready"||(clearTimeout(o),e.removeEventListener("message",s),i(new t(e,l)))};e.addEventListener("message",s);let c={v:x,type:"init",options:r};e.postMessage(c)})}async detect(e,r,n){let i;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?i=e:typeof createImageBitmap=="function"?i=await createImageBitmap(e):i=e}catch{return null}let a=this.nextId;return this.nextId+=1,new Promise(o=>{this.pending.set(a,o);let s={v:x,type:"detect",id:a,bitmap:i,streamWidth:r,streamHeight:n};this.worker.postMessage(s,[i])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var zn=["single","size","centering","pose","exposure","sharpness","motion"];function jt(t){if(t.accepted)return null;if(t.factors.presence<=0)return"no_face";let e="single";for(let r of zn)t.factors[r]<t.factors[e]&&(e=r);return e}var P=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let r=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let n=jt(e);if(n===null){this.acceptedMs+=r;return}let i=this.blocked[n]??{count:0,ms:0};i.count+=1,i.ms+=r,this.blocked[n]=i}summary(){let e={};for(let[r,n]of Object.entries(this.blocked))e[r]={count:n.count,ms:Math.round(n.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var cr=1e3,de="fcv3.hold_upright",ur=200,me=4,lr=600,dr=1e3,or={sharpness:1,exposure:1,meanLuma:128};function $n(t,e){return e.width=t.videoWidth,e.height=t.videoHeight,e.getContext("2d").drawImage(t,0,0),new Promise((r,n)=>e.toBlob(i=>i?r(i):n(new Error("empty-keyframe")),"image/jpeg",.92))}function Jn(){return ee()==="phone"}var Ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,r){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(r),()=>n?.delete(r)}emit(e,r){for(let n of[...this.handlers.get(e)??[]])n(r)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:r}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(r.isPhone??Jn)(),this.setState("preflight");let n=he();if(n!=="OK"){this.fail(n==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=r.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),a;this.cameraRequestedAt=this.now();try{let{facingMode:u,...l}=Ee(xe(),this.facing).video;a=await Yt(this.facing,l,{getUserMedia:i,enumerateDevices:ri(r)})}catch(u){if(e!==this.attempt)return;if(u instanceof X){this.fail("backcamera",{phase:"acquiring",name:O(u)});return}this.fail(Wt(u),{phase:"acquiring",name:O(u)});return}if(Lt(a),Nt(a),e!==this.attempt){for(let u of a.getTracks())u.stop();return}this.stream=a;let o=a.getVideoTracks?.()[0];if(this.trackProvenance=o===void 0?null:Ut(o).catch(()=>null),this.facing=G(a)??this.facing,r.video.srcObject=a,await r.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:r.v3AssetBaseUrl},l=r.createDetector??(r.createWorker!==void 0&&Zt()?async()=>{try{return await ue.create(r.createWorker(),u)}catch{return A(u)}}:()=>A(u)),d;try{d=await l()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:O(f)},f instanceof _?f.fallbackReason:ti(f));return}if(e!==this.attempt){d.destroy();return}this.detector=d,this.options.telemetry?.({type:"detector",tier:d.tier,fallbackReason:d.fallbackReason})}let s=Ae(),c=r.deviceClass??De(s);this.profiler=new W(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new I(r.thresholds??{}),this.blockStats=new P,this.lastGateSnapshotAt=this.now(),r.rankKeyframes?.()&&Promise.resolve().then(()=>(ar(),ir)).then(u=>He=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let r=this.profiler;if(r===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let n=new z({cadenceHz:r.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=n,n.start()}async detectTick(e){let{detector:r,gate:n,profiler:i}=this,a=this.options.video;if(e!==this.attempt||r===null||n===null||i===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let o=i.deviceClass,s=this.now(),c=this.options.makeSnapshot?.(a,i.profile.inputWidth)??this.defaultSnapshot(a,i.profile.inputWidth),u=null;try{u=await r.detect(c,a.videoWidth,a.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==o&&this.startScheduler(e);let l=u===null?or:this.options.measureQuality?.(a,u.box)??this.defaultQuality(a,u.box),d=n.tick({timestampMs:this.now(),observation:u,quality:l,frameWidth:a.videoWidth,frameHeight:a.videoHeight});d.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=d.at),this.blockStats?.record(d),!d.ready&&d.at-this.lastGateSnapshotAt>=cr&&(this.lastGateSnapshotAt=d.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:d.p,q:d.q,factors:d.factors,attempt:e}),d.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),d.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=d.at,this.fire(e))}async fire(e){let{options:r}=this,n=this.scheduler;n?.stop(),this.reportGate(!0);let i=n?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];r.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:a.length===0?0:a.reduce((k,v)=>k+v,0)/a.length});let o=r.mode??"clip",s=r.rankKeyframes?.()&&He?He.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(o==="photo"){let k=this.watchRotation(e,null),v=await s;if(k(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...E});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let u=r.screenRamp?.(),l=ce(u),d=null;s.then(k=>{d=k},()=>{});let f=()=>{e===this.attempt&&d!==null&&this.emit("frozen",{previewDataUrl:d.previewDataUrl})},h=Ht(u,$),p=null,m,b=0;try{let k=this.recordTake(e,c,u,h,void 0).then(w=>w,w=>({failed:w})),[v,E]=await Promise.all([k,s]);if(m=E,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;be(v.failed.requestedMimeType??"")}else p=v,J(v.clip,h)?v.clip.stats===null&&be(v.clip.requestedMimeType??""):f();if(p===null||J(p.clip,h)){b=1,r.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let w=null;try{w=await this.recordTake(e,c,u,h,f)}catch(mr){if(p===null)throw mr}if(e!==this.attempt)return;w!==null&&(p===null||we(w.clip,p.clip))&&(p=w),w===null&&f()}}catch(k){if(e!==this.attempt)return;let v=k.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:O(k)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:g,rvfc:y,report:S}=p;if(V(g.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let M=await this.provenance(y,l);e===this.attempt&&this.finishCapture({clip:g.blob,clipMimeType:g.mimeType,...g.stats?{clipStats:g.stats}:{},clipRetakes:b,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...S!==void 0&&S.rendered.length>0?{screenRamp:S}:{},...M})}async recordTake(e,r,n,i,a){let o=this.options.createRecorder?.()??new U({now:()=>this.now()}),s=Gt(this.options.video),c=Kt(n,{paint:d=>{(d===null||e===this.attempt)&&this.emit("ramp",{colour:d})},now:()=>this.now(),frames:s.latest});this.ramp=c;let u=()=>{s.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},l=this.watchRotation(e,o);try{return{clip:await o.record(r,a,()=>c.started(this.now()),i,s),rvfc:s.stats(),report:c.report()}}finally{l(),u()}}async provenance(e,r){let n=this.trackProvenance;if(n===null)return{};let i,a=new Promise(s=>{i=setTimeout(()=>s(null),dr)}),o=await Promise.race([n,a]);return clearTimeout(i),o===null?{}:{provenance:Bt(o,e,r)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==de&&(this.lastGuidanceKey=de,this.emit("guidance",{key:de}))}watchRotation(e,r){if(!this.uprightGuard)return()=>{};let n=this.options.video,i=()=>{if(e!==this.attempt||r!==null&&this.stateValue!=="recording"){s();return}n.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,r))},a=setInterval(i,ur);n.addEventListener?.("resize",i);let o=!1;function s(){o||(o=!0,clearInterval(a),n.removeEventListener?.("resize",i))}return s}abortRecording(e,r){if(e!==this.attempt)return;this.attempt+=1;let n=this.attempt;try{r?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new I(this.options.thresholds??{}),this.blockStats=new P,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(n),this.startScheduler(n)}async collectKeyframes(e){let r=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),n=lr/(me-1),i=null;for(let a=0;a<me;a+=1){if(e!==this.attempt)return i;try{let o=await r(this.options.video);(i===null||o.sharpness>i.sharpness)&&(i=o)}catch{}a<me-1&&await ei(n)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let r=this.captureTiming();this.emit("artifacts",r===void 0?e:{...e,timing:r})}captureTiming(){let e={},r=(n,i,a)=>{i!==null&&a!==null&&(e[n]=Math.max(0,Math.round(a-i)))};return r("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),r("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),r("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let r=document.createElement("canvas"),n=await(this.facing==="user"?ge:$n)(e,r),i=r.toDataURL("image/jpeg",.92);return{blob:n,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,r){try{let n=this.snapshotCanvas??document.createElement("canvas"),i=r/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*i)),o=Math.max(1,Math.round(e.videoHeight*i)),s=n.getContext("2d");return s===null?e:(n.width!==a&&(n.width=a),n.height!==o&&(n.height=o),s.drawImage(e,0,0,a,o),this.snapshotCanvas=n,n)}catch{return e}}defaultQuality(e,r){let n=sr(e,r,96);return n===null?or:{sharpness:ae(n),exposure:Re(n),meanLuma:ie(n)}}centerSharpness(e){let r=R(e),n=sr(e,{x:r.width*.25,y:r.height*.25,width:r.width*.5,height:r.height*.5},96);return n===null?0:ae(n)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let r=this.blockStats,n=this.profiler;if(r===null||n===null)return;let i=r.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:n.deviceClass,cadenceHz:n.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,r,n){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:n});let{phase:i,name:a}=r;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:i}:{phase:i,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},He;function ei(t){return new Promise(e=>setTimeout(e,t))}function ti(t){return t instanceof Error?t.message:String(t)}function sr(t,e,r){try{let n=document.createElement("canvas"),i=r/Math.max(1,e.width);n.width=Math.max(1,Math.round(e.width*i)),n.height=Math.max(1,Math.round(e.height*i));let a=n.getContext("2d");return a===null?null:(a.drawImage(t,e.x,e.y,e.width,e.height,0,0,n.width,n.height),a.getImageData(0,0,n.width,n.height))}catch{return null}}function ri(t){if(t.enumerateDevices!==void 0)return t.enumerateDevices;if(t.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,ENCODER_TAIL_MS,EXPOSURE_BAND,FRAME_POLL_MS,FaceGateV3,GATE_SNAPSHOT_MS,GateBlockStats,HOLD_UPRIGHT_KEY,INSPECT_WAIT_MS,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MAX_OVERRUN_MS,MIME_CANDIDATES,PHONE_MAX_SHORT_SIDE,PROVENANCE_WAIT_MS,SECOND_FACE_AREA_RATIO,SHARP_REF,SHORT_CLIP_TOLERANCE_MS,STOP_GRACE_MS,TIMESLICE_MS,UPRIGHT_WATCH_MS,V3_GATE_DEFAULTS,VIDEO_BPS,betterTake,blockReasonOf,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,countExtraFaces,createDetector,detectFormFactor,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,needsRetake,pickMimeType,probeDevice,sharpness,toStreamPixels,trackFacingMode,uiCopy});
|