@quadible/web-sdk
Version:
The web sdk for Quadible's behavioral authentication service.
2 lines • 128 kB
JavaScript
/*! For license information please see BehavioralAuthSDK.min.js.LICENSE.txt */
(()=>{var e={3011:(e,t,n)=>{var i;!function(s){var r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(){this._events={},this._conf&&a.call(this,this._conf)}function a(e){e?(this._conf=e,e.delimiter&&(this.delimiter=e.delimiter),this._maxListeners=e.maxListeners!==s?e.maxListeners:10,e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),this.wildcard&&(this.listenerTree={})):this._maxListeners=10}function c(e,t){var n="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";if(this.verboseMemoryLeak&&(n+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning){var i=new Error(n);i.name="MaxListenersExceededWarning",i.emitter=this,i.count=e,process.emitWarning(i)}else console.error(n),console.trace&&console.trace()}function l(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,a.call(this,e)}function u(e,t,n,i){if(!n)return[];var s,r,o,a,c,l,d,h=[],f=t.length,p=t[i],g=t[i+1];if(i===f&&n._listeners){if("function"==typeof n._listeners)return e&&e.push(n._listeners),[n];for(s=0,r=n._listeners.length;s<r;s++)e&&e.push(n._listeners[s]);return[n]}if("*"===p||"**"===p||n[p]){if("*"===p){for(o in n)"_listeners"!==o&&n.hasOwnProperty(o)&&(h=h.concat(u(e,t,n[o],i+1)));return h}if("**"===p){for(o in(d=i+1===f||i+2===f&&"*"===g)&&n._listeners&&(h=h.concat(u(e,t,n,f))),n)"_listeners"!==o&&n.hasOwnProperty(o)&&("*"===o||"**"===o?(n[o]._listeners&&!d&&(h=h.concat(u(e,t,n[o],f))),h=h.concat(u(e,t,n[o],i))):h=o===g?h.concat(u(e,t,n[o],i+2)):h.concat(u(e,t,n[o],i)));return h}h=h.concat(u(e,t,n[p],i+1))}if((a=n["*"])&&u(e,t,a,i+1),c=n["**"])if(i<f)for(o in c._listeners&&u(e,t,c,f),c)"_listeners"!==o&&c.hasOwnProperty(o)&&(o===g?u(e,t,c[o],i+2):o===p?u(e,t,c[o],i+1):((l={})[o]=c[o],u(e,t,{"**":l},i+1)));else c._listeners?u(e,t,c,f):c["*"]&&c["*"]._listeners&&u(e,t,c["*"],f);return h}function d(e,t){for(var n=0,i=(e="string"==typeof e?e.split(this.delimiter):e.slice()).length;n+1<i;n++)if("**"===e[n]&&"**"===e[n+1])return;for(var r=this.listenerTree,o=e.shift();o!==s;){if(r[o]||(r[o]={}),r=r[o],0===e.length)return r._listeners?("function"==typeof r._listeners&&(r._listeners=[r._listeners]),r._listeners.push(t),!r._listeners.warned&&this._maxListeners>0&&r._listeners.length>this._maxListeners&&(r._listeners.warned=!0,c.call(this,r._listeners.length,o))):r._listeners=t,!0;o=e.shift()}return!0}l.EventEmitter2=l,l.prototype.delimiter=".",l.prototype.setMaxListeners=function(e){e!==s&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},l.prototype.event="",l.prototype.once=function(e,t){return this._once(e,t,!1)},l.prototype.prependOnceListener=function(e,t){return this._once(e,t,!0)},l.prototype._once=function(e,t,n){return this._many(e,1,t,n),this},l.prototype.many=function(e,t,n){return this._many(e,t,n,!1)},l.prototype.prependMany=function(e,t,n){return this._many(e,t,n,!0)},l.prototype._many=function(e,t,n,i){var s=this;if("function"!=typeof n)throw new Error("many only accepts instances of Function");function r(){return 0==--t&&s.off(e,r),n.apply(this,arguments)}return r._origin=n,this._on(e,r,i),s},l.prototype.emit=function(){this._events||o.call(this);var e=arguments[0];if("newListener"===e&&!this._newListener&&!this._events.newListener)return!1;var t,n,i,s,r,a=arguments.length;if(this._all&&this._all.length){if(r=this._all.slice(),a>3)for(t=new Array(a),s=0;s<a;s++)t[s]=arguments[s];for(i=0,n=r.length;i<n;i++)switch(this.event=e,a){case 1:r[i].call(this,e);break;case 2:r[i].call(this,e,arguments[1]);break;case 3:r[i].call(this,e,arguments[1],arguments[2]);break;default:r[i].apply(this,t)}}if(this.wildcard){r=[];var c="string"==typeof e?e.split(this.delimiter):e.slice();u.call(this,r,c,this.listenerTree,0)}else{if("function"==typeof(r=this._events[e])){switch(this.event=e,a){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(a-1),s=1;s<a;s++)t[s-1]=arguments[s];r.apply(this,t)}return!0}r&&(r=r.slice())}if(r&&r.length){if(a>3)for(t=new Array(a-1),s=1;s<a;s++)t[s-1]=arguments[s];for(i=0,n=r.length;i<n;i++)switch(this.event=e,a){case 1:r[i].call(this);break;case 2:r[i].call(this,arguments[1]);break;case 3:r[i].call(this,arguments[1],arguments[2]);break;default:r[i].apply(this,t)}return!0}if(!this._all&&"error"===e)throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");return!!this._all},l.prototype.emitAsync=function(){this._events||o.call(this);var e=arguments[0];if("newListener"===e&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);var t,n,i,s,r,a=[],c=arguments.length;if(this._all){if(c>3)for(t=new Array(c),s=1;s<c;s++)t[s]=arguments[s];for(i=0,n=this._all.length;i<n;i++)switch(this.event=e,c){case 1:a.push(this._all[i].call(this,e));break;case 2:a.push(this._all[i].call(this,e,arguments[1]));break;case 3:a.push(this._all[i].call(this,e,arguments[1],arguments[2]));break;default:a.push(this._all[i].apply(this,t))}}if(this.wildcard){r=[];var l="string"==typeof e?e.split(this.delimiter):e.slice();u.call(this,r,l,this.listenerTree,0)}else r=this._events[e];if("function"==typeof r)switch(this.event=e,c){case 1:a.push(r.call(this));break;case 2:a.push(r.call(this,arguments[1]));break;case 3:a.push(r.call(this,arguments[1],arguments[2]));break;default:for(t=new Array(c-1),s=1;s<c;s++)t[s-1]=arguments[s];a.push(r.apply(this,t))}else if(r&&r.length){if(r=r.slice(),c>3)for(t=new Array(c-1),s=1;s<c;s++)t[s-1]=arguments[s];for(i=0,n=r.length;i<n;i++)switch(this.event=e,c){case 1:a.push(r[i].call(this));break;case 2:a.push(r[i].call(this,arguments[1]));break;case 3:a.push(r[i].call(this,arguments[1],arguments[2]));break;default:a.push(r[i].apply(this,t))}}else if(!this._all&&"error"===e)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(a)},l.prototype.on=function(e,t){return this._on(e,t,!1)},l.prototype.prependListener=function(e,t){return this._on(e,t,!0)},l.prototype.onAny=function(e){return this._onAny(e,!1)},l.prototype.prependAny=function(e){return this._onAny(e,!0)},l.prototype.addListener=l.prototype.on,l.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},l.prototype._on=function(e,t,n){if("function"==typeof e)return this._onAny(e,t),this;if("function"!=typeof t)throw new Error("on only accepts instances of Function");return this._events||o.call(this),this._newListener&&this.emit("newListener",e,t),this.wildcard?(d.call(this,e,t),this):(this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),n?this._events[e].unshift(t):this._events[e].push(t),!this._events[e].warned&&this._maxListeners>0&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,c.call(this,this._events[e].length,e))):this._events[e]=t,this)},l.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var n,i=[];if(this.wildcard){var o="string"==typeof e?e.split(this.delimiter):e.slice();i=u.call(this,null,o,this.listenerTree,0)}else{if(!this._events[e])return this;n=this._events[e],i.push({_listeners:n})}for(var a=0;a<i.length;a++){var c=i[a];if(n=c._listeners,r(n)){for(var l=-1,d=0,h=n.length;d<h;d++)if(n[d]===t||n[d].listener&&n[d].listener===t||n[d]._origin&&n[d]._origin===t){l=d;break}if(l<0)continue;return this.wildcard?c._listeners.splice(l,1):this._events[e].splice(l,1),0===n.length&&(this.wildcard?delete c._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(n===t||n.listener&&n.listener===t||n._origin&&n._origin===t)&&(this.wildcard?delete c._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return function e(t){if(t!==s){var n=Object.keys(t);for(var i in n){var r=n[i],o=t[r];o instanceof Function||"object"!=typeof o||null===o||(Object.keys(o).length>0&&e(t[r]),0===Object.keys(o).length&&delete t[r])}}}(this.listenerTree),this},l.prototype.offAny=function(e){var t,n=0,i=0;if(e&&this._all&&this._all.length>0){for(n=0,i=(t=this._all).length;n<i;n++)if(e===t[n])return t.splice(n,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(n=0,i=t.length;n<i;n++)this.emit("removeListenerAny",t[n]);this._all=[]}return this},l.prototype.removeListener=l.prototype.off,l.prototype.removeAllListeners=function(e){if(e===s)return!this._events||o.call(this),this;if(this.wildcard)for(var t="string"==typeof e?e.split(this.delimiter):e.slice(),n=u.call(this,null,t,this.listenerTree,0),i=0;i<n.length;i++)n[i]._listeners=null;else this._events&&(this._events[e]=null);return this},l.prototype.listeners=function(e){if(this.wildcard){var t=[],n="string"==typeof e?e.split(this.delimiter):e.slice();return u.call(this,t,n,this.listenerTree,0),t}return this._events||o.call(this),this._events[e]||(this._events[e]=[]),r(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]},l.prototype.eventNames=function(){return Object.keys(this._events)},l.prototype.listenerCount=function(e){return this.listeners(e).length},l.prototype.listenersAny=function(){return this._all?this._all:[]},(i=function(){return l}.call(t,n,t,e))===s||(e.exports=i)}()},4620:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(595),r=i(n(8183)),o=(...e)=>(window.__quadible_fetch||fetch)(...e);t.default=class{config;cid;constructor(e){this.config=e}async postFile(e,t){const n=this.getHeaders();return delete n["content-type"],await o(`${this.config.serviceUrl}${e}`,{method:"post",body:t,headers:n})}async deleteUser(){await this.request({url:"/v1/user",method:"DELETE"})}async authenticate(){return await this.request({url:"/v1/auth",retries:3})}async getRemoteConfig(){return await this.request({url:`/v1/user/config?cp=${encodeURIComponent(JSON.stringify({platform:"Web"}))}`,retries:3})}async pushEvents(e){const t={};let n=JSON.stringify({events:e});this.config.compression&&(n=await new Promise(((e,t)=>{(0,s.gzip)((new TextEncoder).encode(n),((n,i)=>{n?t(n):e(i)}))})),t["content-type"]="application/octet-stream"),await this.request({url:"/v1/events",method:"POST",payload:n,headers:t,retries:3})}async getConfiguredSdkVersion(){return await this.request({url:"/v1/websdk/version",retries:3})}async loadDependency(e){return await this.loadScript(`${this.config.serviceUrl}/v1/websdk/dependency?url=${encodeURIComponent(e)}`)}async loadSdk(e){return await this.loadScript(`${this.config.serviceUrl}/v1/websdk/version/${e}`)}setCid(e){this.cid=e}async request({url:e,method:t="GET",headers:n={},payload:i,retries:s}){let a=0;for(;;){a++;const c=await o(`${this.config.serviceUrl.replace(/\/+$/,"")}${e}`,{method:t,headers:{...this.getHeaders(),...n},body:i});if(c.ok)return c.headers.get("content-type")?.includes("application/json")?await c.json():await c.text();if(a>s)throw new Error(`Request failed with status ${c.status}`);await(0,r.default)(500*a)}}async loadScript(e){const t=document.createElement("script");return t.src=e,t.async=!0,document.head.appendChild(t),new Promise(((e,n)=>{t.onload=e,t.onerror=n}))}getHeaders(){return{"content-type":"application/json",authorization:`Bearer ${this.config.apiKey}`,"x-app-cid":this.cid}}}},5515:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(3011),r=i(n(4620)),o=i(n(8332)),a=i(n(290)),c=i(n(2947)),l=i(n(9805)),u=i(n(4179)),d=i(n(6429)),h=i(n(4367)),f=i(n(901)),p=n(0),g=i(n(7705)),m=i(n(4067)),v=i(n(4951)),y=i(n(8183)),b=n(3124),w=i(n(9497));class A extends s.EventEmitter2{configuration;static getClientId(){return A.ensureClientId(),localStorage.getItem(A.cidKey)}static ensureClientId(){localStorage.getItem(A.cidKey)||localStorage.setItem(A.cidKey,A.createUUID())}static createUUID(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^16*Math.random()>>e/4).toString(16)))}static defaultApiKey="#DEFAULT_API_KEY";static version="2.0.11";static storageKey="_bauthsdk_authorization";static cidKey="__q_cid";static isRUMInitialized=!1;api;messages={defaultLockScreenMessage:"Making sure it's you..."};videoWorker;webcamSession;collectors=[new l.default,new d.default,new h.default,new o.default(this),new u.default,new a.default,new c.default];dataPushIntervalIndex;status=w.default.Stopped;isFaceAuthenticated=!1;isScreenLocked=!1;lockScreenContainer=document.createElement("div");lockScreenText=document.createElement("div");unlockScheduleId;lastAuthResult=null;debugUI;constructor(e){super(),this.configuration=e,this.configuration.compression=this.defaultCompressionValue(e),this.registerCollectorErrorListeners(),this.configuration.serviceUrl=this.configuration.serviceUrl||"https://api.quadible.io",this.api=new r.default(this.configuration),this.videoWorker=new g.default(this.configuration.verbose,this.configuration.serviceUrl),this.videoWorker.on("error",(e=>this.emit("error",e))),this.webcamSession=new v.default(this.api,this.videoWorker),this.debugUI=this.configuration.debug&&new f.default(this),this.videoWorker.on("predictions",(e=>{this.emit("predictions",e)})),this.videoWorker.on("video-can-play",(()=>{this.log("Worker can play video stream.")})),this.videoWorker.on("video-play-start",(()=>{this.log("Worker video started playing.")})),this.webcamSession.on("face-auth-change",(({status:e,lastAuthResult:t})=>{this.isFaceAuthenticated=e,this.lastAuthResult=t,this.updateScreenLockStatus(),this.updateLockScreenMessageBasedOnFaceAuthResult()})),this.api.setCid(A.getClientId()),this.buildLockScreen(),e.pushIntervalMs||(e.pushIntervalMs=15e3),this.on("face-enrollment",this.startVideoAuthenticationLoopIfNeeded.bind(this))}defaultCompressionValue(e){return void 0===e.compression||e.compression}async start(e=!1){if(this.status===w.default.Stopped){this.setStatus(w.default.Starting),this.updateScreenLockStatus();try{if(!e){this.log("Checking for updates...");const{version:e}=await this.api.getConfiguredSdkVersion();if(A.version!==e)return this.log(`A different version is configured (${A.version} => ${e}). Getting...`),await this.loadVersion(e).catch((e=>{this.log("Failed to load new version. Using current version."),this.log(e),this.setStatus(w.default.Stopped)})),this.log(`Starting (${window.BehavioralAuthSDK.version}) ...`),await this.start(!0);this.log("SDK is up to date.")}const t=await this.api.getRemoteConfig();this.saveSessionInfo({...t}),await this.startAllAvailableCollectors(),this.startDataPushLoop(),this.setStatus(w.default.Started),this.startVideoAuthenticationLoopIfNeeded(),!this.getSessionInfo().faceEnrollmentStatus&&this.configuration.useWebcam&&this.assignPhotoToUserPopup({clickOutsideToClose:!0}).catch((e=>this.emit("error",new Error(`User canceled enrollment. (${e?.message} ${e?.stack})`))))}catch(e){this.emit("error",e),this.setStatus(w.default.Stopped)}}}async stop(){this.stopAllCollectors(),this.stopDataPushLoop(),this.webcamSession.stop(),this.setStatus(w.default.Stopped)}clearSession(){this.status!==w.default.Stopped&&this.stop(),this.lastAuthResult=null,localStorage.removeItem(A.storageKey)}async deleteUser(){await this.api.deleteUser()}setApiKey(e){this.configuration.apiKey=e}isCollecting(){return this.status===w.default.Starting||this.status===w.default.Started}async authenticate(){return await this.flushAll(),await this.api.authenticate()}async assignPhotoToUserPopup(e={clickOutsideToClose:!0}){await this.api.loadDependency("https://cdn.jsdelivr.net/npm/three@v0.156.1/build/three.min.js");const t=new m.default({serviceUrl:this.configuration.serviceUrl,videoWorker:await this.getVideoWorker(),...e});return t.show(),new Promise(((e,n)=>{t.on("canceled",n),t.on("submit",(async n=>{t.lockSubmit(),t.clearErrorMessage();try{await this.assignPhotoToUser(n),t.dispose(),e(void 0)}finally{t.showErrorMessage("There was an error, please try again."),t.unlockSubmit()}}))}))}async assignPhotoToUser(e){const t=await fetch(e),n=(0,p.createFormData)(),i=await t.blob();n.append("file",i);const s=await this.api.postFile("/v1/face/register",n);if(200!==s.status)throw new Error("Could not assign photo: "+await s.text());const r=this.getSessionInfo();r.faceEnrollmentStatus=!0,this.saveSessionInfo(r),this.emit("face-enrollment")}setUserDisplayName(e){const t=this.getSessionInfo();t.userDisplayName=e,this.saveSessionInfo(t)}getSessionInfo(){let e={};const t=localStorage.getItem(A.storageKey);if(t)try{e=JSON.parse(t)}catch(e){this.emit("warning",e)}return e}async loadVersion(e){await this.api.loadSdk(e);const t=window.BehavioralAuthSDK,n=new t(this.configuration);this.constructor=t,this.__proto__=n.__proto__;const i=this._listeners;Object.assign(this,n);for(const{event:e,listener:t}of i)this.on(e,t)}_listeners=[];on(e,t){return this._listeners.push({event:e,listener:t}),super.on(e,t),this}off(e,t){return this._listeners.splice(this._listeners.findIndex((n=>n.event===e&&t==t)),1),super.off(e,t),this}registerCollectorErrorListeners(){for(const e of this.collectors)e.on("error",(e=>this.emit("error",e)))}buildLockScreen(){const e=document.createElement("div"),t=document.createElement("div");this.lockScreenText.innerText="Making sure it's you...",this.lockScreenText.style.fontFamily="'Work Sans', sans-serif",t.innerHTML=b.spinnerHtml,t.querySelector(".qdbl-circle").style.margin="65px auto 30px",t.querySelector(".qdbl-circle").classList.add("white"),this.lockScreenText.style.textAlign="center",e.append(t,this.lockScreenText),this.lockScreenContainer.classList.add("qdbl-lock-screen"),this.lockScreenContainer.append(e),Object.assign(e.style,{width:"200px",height:"200px",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)"}),Object.assign(this.lockScreenContainer.style,{position:"fixed",top:"0px",left:"0px",width:"100%",height:"100%",background:"#00000080",color:"white",zIndex:9998})}updateScreenLockStatus(){this.configuration.lockScreenOnAuthLost&&(this.shouldLockScreen()?this.lockScreen():this.scheduleUnlockScreen())}shouldLockScreen(){return!this.isFaceAuthenticated&&(this.configuration.lockScreenOnFaceLost||!this.lastAuthResult||!this.lastAuthResult.authenticated&&this.lastAuthResult.detectedFaces)}lockScreen(){if(!this.isScreenLocked){this.isScreenLocked=!0,this.unlockScheduleId=null;const e=document.querySelectorAll("body > :not(.qdbl-lock-screen)"),t=document.querySelector(":focus");this.lockScreenText.innerText=this.messages.defaultLockScreenMessage,t?.blur(),e.forEach((e=>{})),document.body.append(this.lockScreenContainer)}}async scheduleUnlockScreen(){if(this.isScreenLocked){this.isScreenLocked=!1;const e=Math.random();this.unlockScheduleId=e,await(0,y.default)(2e3),this.unlockScheduleId===e&&this.unlockScreen(),this.lockScreenText.innerText=this.messages.defaultLockScreenMessage}}unlockScreen(){this.lockScreenContainer.remove(),document.querySelectorAll("body > *").forEach((e=>{e.style.filter="none"}))}async startVideoAuthenticationLoopIfNeeded(){this.shouldRunVideoAuthentication()&&!this.webcamSession.isStarted&&this.webcamSession.start()}updateLockScreenMessageBasedOnFaceAuthResult(){!this.lastAuthResult.authenticated&&this.lastAuthResult.detectedFaces?this.lockScreenText.innerText="You are not allowed to access this account.":this.lastAuthResult.authenticated&&this.isFaceAuthenticated?this.lockScreenText.innerText=`Welcome back, ${this.getSessionInfo().userDisplayName}!`:this.lockScreenText.innerText=this.messages.defaultLockScreenMessage}shouldRunVideoAuthentication(){return this.status===w.default.Started&&this.configuration.useWebcam&&this.getSessionInfo().faceEnrollmentStatus}async getVideoWorker(){return await this.videoWorker.init(),this.videoWorker}setStatus(e){this.status=e}stopAllCollectors(){for(const e of this.collectors)e.isCollecting&&e.stop?.()}startDataPushLoop(){this.dataPushIntervalIndex=setInterval(this.flushAll.bind(this),this.configuration.pushIntervalMs)}async flushAll(){const e=[];for(const t of this.collectors)if(t.isCollecting){const n=t.flush();n.length&&e.push(...n.map((e=>({kind:e.kind,timestamp:e.timestamp,payload:e}))))}e.length&&this.api.pushEvents(e)}stopDataPushLoop(){clearInterval(this.dataPushIntervalIndex)}saveSessionInfo(e){localStorage.setItem(A.storageKey,JSON.stringify(e))}async startAllAvailableCollectors(){const e=this.getSessionInfo(),t=new Set;for(const n of e.collectors)t.add(n.name);for(const e of this.collectors)t.has(e.name)&&(this.log(`Using collector: ${e.name}`),await this.tryStartCollectorIfAvailable(e));this.flushAll()}async tryStartCollectorIfAvailable(e){try{await e.isAvailable()&&!e.isCollecting&&await(e.start?.())}catch(e){console.error(e)}}log(...e){this.configuration.verbose&&console.debug(`[quadible] ${e.shift()}`,...e)}}t.default=A},8332:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011),s=n(7685),r=n(9095);class o extends i.EventEmitter2{sdk;name="WebDevice";data=[];isCollecting=!1;constructor(e){super(),this.sdk=e}async start(){this.isCollecting=!0,await this.collect()}stop(){this.isCollecting=!1}flush(){return this.data.splice(0)}async isAvailable(){return!0}async collect(){const e=navigator.userAgent;this.data.push({kind:"deviceinfo",timestamp:Date.now(),userAgent:e,viewportWidth:innerWidth,viewportHeight:innerHeight,themePreference:this.getThemePreference(),timezoneOffset:(new Date).getTimezoneOffset(),language:navigator?.language||navigator?.userLanguage,languages:navigator?.languages});try{const e=await(0,r.loadSources)(s.sources,{cache:{},debug:!0},[])();this.data.push({kind:"deviceproperties",timestamp:Date.now(),components:e})}catch(e){this.sdk.emit("error",e)}}getThemePreference(){let e="unknown";return window.matchMedia&&(e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"default"),e}}t.default=o},290:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{isCollecting=!1;name="WebGenericEvents";data=[];constructor(){super(),this.registerGamepadEventListeners(),this.registerClipboardListeners(),this.registerBatteryListeners()}flush(){return this.data.splice(0)}async isAvailable(){return!0}start(){this.isCollecting=!0,this.collect()}stop(){this.isCollecting=!1}async registerBatteryListeners(){const e=await(navigator?.getBattery?.());if(e){this.data.push({kind:"battery",timestamp:Date.now(),event:"battery",charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,level:e.level});const t=t=>{this.data.push({kind:t.type,timestamp:Date.now(),event:t.type,charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,level:e.level})};e.addEventListener?.("chargingchange",t),e.addEventListener?.("chargingtimechange",t),e.addEventListener?.("dischargingtimechange",t),e.addEventListener?.("levelchange",t)}}collect(){this.data.push({kind:"getgamepads",event:"get-gamepads",data:this.getGamepads(),timestamp:Date.now()})}registerClipboardListeners(){const e=e=>{if(this.isCollecting){const t=e.target;this.data.push({kind:e.type,name:e.type,timestamp:Date.now(),element:{tag:t?.tagName,class:t?.className,id:t?.id,name:t?.name,type:t?.type,width:t?.clientWidth,height:t?.clientHeight}})}};window.addEventListener("copy",e),window.addEventListener("paste",e),window.addEventListener("cut",e)}registerGamepadEventListeners(){const e=e=>{this.data.push({kind:e.type,event:e.type,timestamp:Date.now(),gamepad:this.getGamepadInfo(e.gamepad)})};window.addEventListener("gamepadconnected",e),window.addEventListener("gamepaddisconnected",e)}getGamepads(){const e=navigator.getGamepads(),t=[];if(e?.length)for(const n of e)n&&t.push(this.getGamepadInfo(n));return t}getGamepadInfo(e){return{id:e?.id,index:e?.index,mapping:e?.mapping,connected:e?.connected,axes:e?.axes,buttonCount:e?.buttons?.length,vibrationActuatorType:e?.vibrationActuator?.type}}}t.default=s},2947:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{static collectionIntervalMs=3e5;name="WebGeolocation";data=[];isCollecting=!1;lastCollectionAt;gestureListener=async()=>{if(this.isCollecting&&(!this.lastCollectionAt||Date.now()-this.lastCollectionAt>s.collectionIntervalMs)){this.lastCollectionAt=Date.now();const e=await this.getCurrentPosition().catch((e=>(this.emit("error",e),null)));e&&this.data.push({kind:"location",timestamp:Date.now(),coords:{accuracy:e.coords.accuracy,altitude:e.coords.altitude,altitudeAccuracy:e.coords.altitudeAccuracy,heading:e.coords.heading,latitude:e.coords.latitude,longitude:e.coords.longitude,speed:e.coords.speed}})}};start(){this.isCollecting=!0,this.registerGestureListeners()}stop(){this.isCollecting=!1,this.unregisterGestureListeners()}flush(){return this.data.splice(0)}async isAvailable(){return Boolean(navigator?.geolocation?.getCurrentPosition)}registerGestureListeners(){window.addEventListener("click",this.gestureListener),window.addEventListener("keydown",this.gestureListener)}unregisterGestureListeners(){window.removeEventListener("click",this.gestureListener),window.removeEventListener("keydown",this.gestureListener)}async getCurrentPosition(){return await new Promise(((e,t)=>navigator.geolocation.getCurrentPosition(e,t)))}}t.default=s},9805:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{static KEYBOARD_EVENTS=["keydown","keyup","keypress"];name="WebKeyboard";isCollecting=!1;data=[];constructor(){super(),this.registerEventListeners()}flush(){return this.data.splice(0)}async isAvailable(){return!0}start(){this.isCollecting=!0}stop(){this.isCollecting=!1}registerEventListeners(){for(const e of s.KEYBOARD_EVENTS)window.addEventListener(e,(t=>{const n=t.srcElement;this.isCollecting&&this.data.push({kind:e,name:e,element:{class:n?.className,name:n?.getAttribute?.("name"),id:n?.getAttribute?.("id"),type:n?.getAttribute?.("type"),tagName:n?.tagName,width:n?.clientWidth,height:n?.clientHeight},timestamp:Date.now(),key:t.key,keyCode:t.keyCode,charCode:t.charCode,code:t.code,type:t.type,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,location:t.location,which:t.which,isTrusted:t.isTrusted})}))}}t.default=s},4179:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{static MOUSE_EVENTS=["mousedown","mouseup","mouseenter","mouseleave","mousemove","mousewheel","contextmenu"];name="WebMouse";isCollecting=!1;data=[];lastMouseMoveTimestamp=0;constructor(){super(),this.registerMouseEventListeners(),this.registerScrollListener(),this.registerWindowFocusListeners(),this.registerElementFocusListeners()}flush(){return this.data.splice(0)}async isAvailable(){return!0}start(){this.isCollecting=!0}stop(){this.isCollecting=!1}registerElementFocusListeners(){const e=e=>{if(this.isCollecting){const t=e.target;this.data.push({kind:e.type,name:e.type,timestamp:Date.now(),element:{class:t?.className,name:t?.getAttribute?.("name"),id:t?.getAttribute?.("id"),type:t?.getAttribute?.("type"),tagName:t?.tagName,scrollTop:t?.scrollTop,width:t?.clientWidth,height:t?.clientHeight}})}};document.addEventListener("focusin",e),document.addEventListener("focusout",e)}registerWindowFocusListeners(){const e=e=>{this.isCollecting&&this.data.push({kind:`window${e.type}`,name:`window-${e.type}`,timestamp:Date.now()})};window.addEventListener("focus",e),window.addEventListener("blur",e)}registerScrollListener(){window.addEventListener("scroll",(e=>{if(this.isCollecting){const t=e.target;this.data.push({kind:"scroll",name:"scroll",timestamp:Date.now(),element:{class:t?.className,name:t?.getAttribute?.("name"),id:t?.getAttribute?.("id"),type:t?.getAttribute?.("type"),tagName:t?.tagName,scrollTop:t?.scrollTop,width:t?.clientWidth,height:t?.clientHeight}})}}))}registerMouseEventListeners(){for(const e of s.MOUSE_EVENTS)window.addEventListener(e,(t=>{this.isCollecting&&this.collect(e,t)}))}collect(e,t){const n=t.srcElement;let i="";if("mousemove"===e){if(Date.now()-this.lastMouseMoveTimestamp<150)return;this.lastMouseMoveTimestamp=Date.now()}"mouseup"!==e&&"mousedown"!==e||(i=this.tryGetXPathTo(n)),this.data.push({kind:e,name:e,type:t.type,x:t.x,y:t.y,offsetX:t.offsetX,offsetY:t.offsetY,element:{class:n?.className,name:n?.getAttribute?.("name"),id:n?.getAttribute?.("id"),type:n?.getAttribute?.("type"),tagName:n?.tagName,scrollTop:n?.scrollTop,width:n?.clientWidth,height:n?.clientHeight},timestamp:Date.now(),viewportWidth:innerWidth,viewportHeight:innerHeight,isTrusted:t.isTrusted,altKey:t.altKey,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,which:t.which,detail:t.detail,button:t.button,buttons:t.buttons,xpath:i})}getXPathTo(e){if("HTML"==e.tagName)return"/HTML[1]";if(e===document.body)return"/HTML[1]/BODY[1]";for(var t=0,n=e.parentNode.childNodes,i=0;i<n.length;i++){var s=n[i];if(s===e)return this.getXPathTo(e.parentNode)+"/"+e.tagName+"["+(t+1)+"]";1===s.nodeType&&s.tagName===e.tagName&&t++}}tryGetXPathTo(e){try{return this.getXPathTo(e)}catch(e){this.emit("error",e)}}}t.default=s},6429:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{name="WebState";isCollecting=!1;data=[];constructor(){super(),this.registerMouseEventListeners(),this.wrapStateChangers()}flush(){return this.data.splice(0)}async isAvailable(){return!0}start(){this.isCollecting=!0,this.collect()}stop(){this.isCollecting=!1}collect(){this.data.push({kind:"popstate",url:location.href,event:"popstate",timestamp:Date.now()})}registerMouseEventListeners(){window.addEventListener("popstate",(e=>{this.isCollecting&&this.collect()}))}wrapStateChangers(){const e=e=>{const t=history[e];history[e]=(...n)=>{const i=t.call(history,...n);return this.data.push({kind:e,url:location.href,event:e,timestamp:Date.now()}),i}};e("replaceState"),e("pushState")}}t.default=s},4367:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);class s extends i.EventEmitter2{static TOUCH_EVENTS=["touchstart","touchend","touchmove","touchcancel"];name="WebTouch";isCollecting=!1;data=[];constructor(){super(),this.registerMouseEventListeners()}flush(){return this.data.splice(0)}async isAvailable(){return"ontouchstart"in window}start(){this.isCollecting=!0}stop(){this.isCollecting=!1}registerMouseEventListeners(){for(const e of s.TOUCH_EVENTS)window.addEventListener(e,(t=>{this.isCollecting&&this.collect(e,t)}))}collect(e,t){const n=this.data[this.data.length-1];if("touchmove"===e&&"touchmove"===n?.eventName&&Date.now()-n.timestamp<100)return;const i=t.srcElement;this.data.push({kind:e,name:e,type:t.type,x:t.touches?.[0]?.pageX,y:t.touches?.[0]?.pageY,element:{class:i?.className,name:i?.getAttribute?.("name"),id:i?.getAttribute?.("id"),type:i?.getAttribute?.("type"),tagName:i?.tagName,width:i?.clientWidth,height:i?.clientHeight},timestamp:Date.now(),viewportWidth:innerWidth,viewportHeight:innerHeight})}}t.default=s},901:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=i(n(5515));t.default=class{client;html='\n <video id="qdbl_debug_ui_video"></video>\n <div id="qdbl_debug_ui"></div>\n ';debugEl=document.createElement("div");stats={localPredictionWithFaceCount:0,localPredictionWithoutFaceCount:0,apiPredictionSamePersonCount:0,apiPredictionNotSamePersonCount:0,apiPredictionNoFacesCount:0,trackingRequestCount:0,trackingEndRequestCount:0};isVisible=!1;constructor(e){this.client=e,this.build(),window.addEventListener("keydown",(e=>{"d"!==e.key||document.querySelector(":focus")||this.toggle()})),e.videoWorker.on("predictions",(({predictions:e})=>{e.length?(this.stats.localPredictionWithFaceCount++,this.debugEl.querySelector("#localPredictionWithFaceCount span").innerHTML=this.stats.localPredictionWithFaceCount.toString()):(this.stats.localPredictionWithoutFaceCount++,this.debugEl.querySelector("#localPredictionWithoutFaceCount span").innerHTML=this.stats.localPredictionWithoutFaceCount.toString())})),e.webcamSession.on("face-auth-response",(e=>{e.authenticated&&(this.stats.apiPredictionSamePersonCount++,this.debugEl.querySelector("#apiPredictionSamePersonCount span").innerHTML=this.stats.apiPredictionSamePersonCount.toString()),e.detectedFaces||(this.stats.apiPredictionNoFacesCount++,this.debugEl.querySelector("#apiPredictionNoFacesCount span").innerHTML=this.stats.apiPredictionNoFacesCount.toString()),e.detectedFaces&&!e.authenticated&&(this.stats.apiPredictionNotSamePersonCount++,this.debugEl.querySelector("#apiPredictionNotSamePersonCount span").innerHTML=this.stats.apiPredictionNotSamePersonCount.toString())})),e.webcamSession.on("tracking-sent",(()=>{this.stats.trackingRequestCount++,this.debugEl.querySelector("#trackingRequestCount span").innerHTML=this.stats.trackingRequestCount.toString()})),e.webcamSession.on("tracking-end-sent",(()=>{this.stats.trackingEndRequestCount++,this.debugEl.querySelector("#trackingEndRequestCount span").innerHTML=this.stats.trackingEndRequestCount.toString()}))}toggle(){this.isVisible?this.hide():this.show()}show(){this.isVisible=!0,document.body.append(this.debugEl)}hide(){this.isVisible=!1,this.debugEl.remove()}build(){this.debugEl.classList.add("qdblsdk-debug-ui"),this.buildVideoPlayer(),this.buildFields()}async buildVideoPlayer(){this.debugEl.append(this.client.videoWorker.canvas)}buildFields(){const e=[{name:"clientId",get:()=>s.default.getClientId()},{name:"apiKey",get:()=>this.client.configuration.apiKey},{name:"pushIntervalMs",get:()=>this.client.configuration.pushIntervalMs},{name:"useWebcam",get:()=>this.client.configuration.useWebcam},{name:"lockScreenOnAuthLost",get:()=>this.client.configuration.lockScreenOnAuthLost},{name:"lockScreenOnFaceLost",get:()=>this.client.configuration.lockScreenOnFaceLost},{name:"debug",get:()=>this.client.configuration.debug},{name:"verbose",get:()=>this.client.configuration.verbose},{name:"localPredictionWithFaceCount",get:()=>this.stats.localPredictionWithFaceCount},{name:"localPredictionWithoutFaceCount",get:()=>this.stats.localPredictionWithoutFaceCount},{name:"apiPredictionSamePersonCount",get:()=>this.stats.apiPredictionSamePersonCount},{name:"apiPredictionNotSamePersonCount",get:()=>this.stats.apiPredictionNotSamePersonCount},{name:"apiPredictionNoFacesCount",get:()=>this.stats.apiPredictionNoFacesCount},{name:"trackingRequestCount",get:()=>this.stats.trackingRequestCount},{name:"trackingEndRequestCount",get:()=>this.stats.trackingEndRequestCount}];for(const t of e){const e=document.createElement("div");e.id=t.name.toString(),e.classList.add("field-row"),e.innerHTML=`<b>${t.name}</b>: <span>${t.get()}</span>`,this.debugEl.append(e)}}}},0:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createFormData=void 0,t.createFormData=function(){return new(window.__quadible_FormData||window.FormData)}},7705:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(3011),r=i(n(8183));class o extends s.EventEmitter2{verbose;serviceUrl;video=document.createElement("video");canvas=document.createElement("canvas");get workerCode(){return`\n let canvas;\n let context;\n let model;\n\n let offscreenReadyResolver;\n let offscreenReady = new Promise(resolve => offscreenReadyResolver = resolve);\n\n main();\n\n async function main() {\n log('Worker started.');\n addEventListener('message', offscreenListener);\n\n await Promise.all([\n offscreenReady,\n loadBlazeface()\n ]);\n\n postMessage('ready');\n }\n\n function offscreenListener(event) {\n canvas = event.data.offscreen;\n context = canvas.getContext('2d');\n removeEventListener('message', offscreenListener);\n addEventListener('message', imageListener);\n offscreenReadyResolver();\n log('Worker got context.');\n }\n\n async function imageListener(event) {\n context.drawImage(event.data.imageBitmap, 0, 0, 320, 240);\n\n const [blob, predictions] = await Promise.all([\n canvas.convertToBlob(),\n model.estimateFaces(canvas, false)\n ]);\n\n postMessage({\n predictions,\n imageBase64: new FileReaderSync().readAsDataURL(blob)\n });\n }\n\n function log(...args) {\n if(${this.verbose}) {\n console.debug('[quadible][worker] ' + args.shift(), ...args);\n }\n }\n\n async function loadBlazeface() {\n log('Loading tfjs and blazeface...');\n \n const urls = [\n 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core@3.6.0/dist/tf-core.min.js',\n 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-webgl@3.6.0/dist/tf-backend-webgl.min.js',\n 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-converter@3.6.0/dist/tf-converter.min.js',\n 'https://cdn.jsdelivr.net/npm/@tensorflow-models/blazeface@0.0.7/dist/blazeface.min.js'\n ];\n\n importScripts(...urls.map(url => '${this.serviceUrl}/v1/websdk/dependency?url=' + encodeURIComponent(url)));\n\n log('Loading blazeface model...');\n model = await blazeface.load({ maxFaces: 1, scoreThreshold: 0.96 });\n log('Done.');\n }\n `}isInitialized=!1;constructor(e=!1,t){super(),this.verbose=e,this.serviceUrl=t}async init(){if(!this.isInitialized){this.isInitialized=!0;try{await this.bootstrapVideo(),this.assignCanPlayHandler()}catch(e){this.emit("error",e)}}}assignCanPlayHandler(){const e=()=>{this.video.removeEventListener("canplay",e),this.bootstrapWorker()};this.video.addEventListener("canplay",e)}async bootstrapVideo(){const e=await(navigator?.mediaDevices?.getUserMedia({video:!0}));this.video.width=320,this.video.height=240,this.video.autoplay=!1,this.video.loop=!0,this.video.srcObject=e}async bootstrapWorker(){this.emit("video-can-play"),this.canvas.width=this.video.width,this.canvas.height=this.video.height;const e=new Blob([this.workerCode],{}),t=URL.createObjectURL(e),n=new Worker(t),i=this.canvas.transferControlToOffscreen();n.postMessage({offscreen:i},[i]),n.addEventListener("message",(e=>{"ready"===e.data?this.video.play().catch((()=>{const e=["click","keydown","touchdown"],t=()=>{n(),this.video.play()},n=()=>{for(const n of e)removeEventListener(n,t)};for(const n of e)addEventListener(n,t)})):this.emit("predictions",e.data)})),this.video.addEventListener("play",(()=>{this.emit("video-play-start");const e=this.video.captureStream(),[t]=e.getVideoTracks(),i=new window.ImageCapture(t);let s;!async function e(){s=performance.now();const t=await async function(){for(;;)try{return await i.grabFrame()}catch(e){console.warn({message:`[quadible][VideoWorker] ${e.message}`,stack:e.stack}),await(0,r.default)(100)}}();n.addEventListener("message",(async function t(){n.removeEventListener("message",t);const i=performance.now()-s;i<100&&await(0,r.default)(100-i),e()})),n.postMessage({imageBitmap:t},[t])}()}))}}t.default=o},4067:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(3011),r=n(3509),o=n(3124),a=i(n(1581));class c extends s.EventEmitter2{options;container=document.createElement("div");dialog=document.createElement("div");video=document.createElement("video");wireframe=document.createElement("div");submit=document.createElement("button");error=document.createElement("div");webcamWireframe;isSubmitLocked=!1;constructor(e){super(),this.options=e}show(){this.buildDialog(),this.injectDialog(),this.video=this.options.videoWorker.video,this.webcamWireframe=new a.default({videoWorker:this.options.videoWorker,wrapper:this.wireframe,wireframe:{zoom:3.36,mOpac:1,wfOpac:.13,contrast:1.7,saturation:0,zDepth:100,noiseStrength:182,showOriginalVideo:!1}}),this.options.videoWorker.on("predictions",(({predictions:e})=>{this.submit.disabled=Boolean(!e.length)||this.isSubmitLocked}))}dispose(){this.container.remove(),this.webcamWireframe.dispose()}lockSubmit(){this.isSubmitLocked=!0,this.submit.disabled=!0}unlockSubmit(){this.isSubmitLocked=!1}clearErrorMessage(){this.error.style.display="none"}showErrorMessage(e){this.error.innerText=e,this.error.style.display="block"}buildDialog(){this.container.append(this.dialog),this.wireframe.innerHTML=o.spinnerHtml,this.dialog.append(this.wireframe),this.container.addEventListener("click",(e=>{e.target===this.container&&this.options.clickOutsideToClose&&(this.dispose(),this.emit("canceled"))})),this.submit.addEventListener("click",(e=>{this.emit("submit",this.webcamWireframe.lastFrameWithPredictions?.imageBase64)})),Object.assign(this.container.style,{position:"fixed",top:"0px",left:"0px",width:"100%",height:"100%",background:"rgb(0 0 0 / 42%)",zIndex:9999}),Object.assign(this.wireframe.style,{position:"absolute",width:"100%",height:"calc(100% - 50px)",borderRadius:"10px 10px 0 0",overflow:"hidden"}),Object.assign(this.dialog.style,{position:"absolute",top:"50%",left:"50%",width:"400px",height:"500px",background:"white",borderRadius:"10px",transform:"translate(-50%, -50%)",boxShadow:"0 15px 30px #00000024"}),Object.assign(this.video.style,{width:"200px",height:"200px",margin:"10px auto",display:"block",borderRadius:"10px",boxShadow:"0 8px 15px #00000078"});const e=document.createElement("div"),t=document.createElement("img"),n=document.createElement("span"),i="quadible-submit-btn";this.submit.innerText="Submit",this.submit.classList.add(i),this.submit.disabled=!0;const s=document.createElement("style");s.innerHTML=`\n @font-face {\n font-family: 'Work Sans';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('${this.options.serviceUrl}/v1/websdk/dependency?url=${encodeURIComponent("https://fonts.gstatic.com/s/worksans/v17/QGY_z_wNahGAdqQ43RhVcIgYT2Xz5u32K0nXNig.ttf")}') format('truetype');\n }\n .${i}:disabled {\n pointer-events: none;\n background-color: rgb(155 155 155) !important;\n background-image: linear-gradient(107deg, rgb(236 236 236) 0%, rgb(184 184 184) 100%) !important;\n }\n `,document.head.appendChild(s),Object.assign(this.submit.style,{backgroundColor:"#febb97",backgroundImage:"linear-gradient(107deg, #febb97 0%, #f73e6e 100%)",borderRadius:"25px 25px 25px 25px",fontFamily:'"Work Sans", Sans-serif',display:"inline-block",border:"none",float:"right",color:"white",textTransform:"uppercase",padding:"10px 20px",margin:"7px",outline:"none",cursor:"pointer"}),t.src=r.logoBase64DataUrl,n.innerText="Powered by",e.append(n,t,this.submit),Object.assign(n.style,{fontFamily:"'Work Sans', sans-serif",display:"inline-block",verticalAlign:"top",width:"91px",padding:"18px 0 0",height:"50px",fontSize:"14px"}),Object.assign(t.style,{display:"inline-block",width:"50px"}),Object.assign(e.style,{position:"absolute",width:"100%",top:"450px",height:"50px",boxSizing:"border-box",paddingLeft:"15px",verticalAlign:"top"}),Object.assign(this.error.style,{position:"absolute",bottom:"60px",color:"red",fontFamily:"'Work Sans'",background:"#000000bf",padding:"3px 5px",borderRadius:"5px",left:"50%",transform:"translate(-50%, 0)",textAlign:"center",display:"none"}),this.dialog.append(this.error,e)}injectDialog(){document.body.append(this.container)}}t.default=c},4951:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(3011),r=n(0),o=i(n(8183));class a extends s.EventEmitter2{api;worker;isStarted=!1;isAuthenticatingFrame=!1;isFaceAuthenticated=!1;lastAuthResult=null;nextVideoFrame;consecutiveNoFaceCount=0;consecutiveNoFaceThreshold=2;failedFaceAuthTries=0;failedFaceAuthRetryIntervalsMs=[0,1e3,1e3,2e3,2e3,5e3,5e3,1e4];lastTrackingUpdate=Date.now();predictionHandler=(e=>{this.nextVideoFrame=e,this.isAuthenticatingFrame||this.processNextFrame()}).bind(this);constructor(e,t){super(),this.api=e,this.worker=t}async start(){this.isStarted=!0,await this.worker.init(),this.worker.on("predictions",this.predictionHandler)}async stop(){this.isStarted=!1,this.worker.off("predictions",this.predictionHandler)}async processNextFrame(){try{for(this.isAuthenticatingFrame=!0;;){const e=this.nextVideoFrame;if(this.nextVideoFrame=void 0,!e)break;await this.processFrame(e)}}finally{this.isAuthenticatingFrame=!1}}async processFrame(e){let t=Boolean(e.predictions.length);if(t?this.consecutiveNoFaceCount=0:(this.consecutiveNoFaceCount++,this.consecutiveNoFaceCount<=this.consecutiveNoFaceThreshold&&(t=!0)),t)if(this.isFaceAuthenticated)this.sendTrackingIfNeeded();else{await(0,o.default)(this.getAuthRetryInterval());const t=this.nextVideoFrame||e;this.lastAuthResult=await this.authenticateFrame(t.imageBase64),this.setFaceAuthStatus(this.lastAuthResult.authenticated),this.incrementOrResetFaceAuthTries()}else this.sendTrackingEndIfNeeded(),this.setFaceAuthStatus(!1)}incrementOrResetFaceAuthTries(){this.isFaceAuthenticated?this.failedFaceAuthTries=0:this.failedFaceAuthTries++}getAuthRetryInterval(){let e=this.failedFaceAuthRetryIntervalsMs[this.failedFaceAuthTries];return isNaN(e)&&(e=this.failedFaceAuthRetryIntervalsMs[this.failedFaceAuthRetryIntervalsMs.length-1]),e}async authenticateFrame(e){const t=await fetch(e),n=(0,r.createFormData)(),i=await t.blob();n.append("file",i);const s=await(await this.api.postFile("/v1/face/authenticate",n)).json();return this.emit("face-auth-response",s),s}setFaceAuthStatus(e){const t=this.isFaceAuthenticated;this.isFaceAuthenticated=e,e&&!t&&this.emit("face-auth"),!e&&t&&this.emit("face-auth-lost"),e!==t&&this.emit("face-auth-change",{status:e,lastAuthResult:this.lastAuthResult})}sendTrackingEndIfNeeded(){this.isFaceAuthenticated&&(this.api.pushEvents([{kind:"facetracking",timestamp:Date.now(),payload:{trackingId:this.lastAuthResult.trackingId,isTrackingActive:!1}}]),this.emit("tracking-end-sent"))}sendTrackingIfNeeded(){const e=Date.now();this.lastTrackingUpdate+2e3<e&&(this.lastTrackingUpdate=e,this.api.pushEvents([{kind:"facetracking",timestamp:Date.now(),payload:{trackingId:this.lastAuthResult.trackingId,isTrackingActive:!0}}]),this.emit("tracking-sent"))}}t.default=a},1581:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3011);var s;!function(e){e.PerspectiveCamera=class{constructor(e,t,n,i){}position;aspect;updateProjectionMatrix(){}},e.Scene=class{add(e){}},e.WebGLRenderer=class{constructor(e){}domElement;setSize(e,t){}sortObjects;render(e,t){}},e.VideoTexture=class{constructor(e){}},e.Object3D=class{add(e){}scale;rotation},e.PlaneGeometry=class{constructor(e,t,n,i){}verticesNeedUpdate;getAttribute(e){return new t}},e.Mesh=class{constructor(e,t){}position},e.MeshBasicMaterial=class{constructor(e){}};class t{setZ(e,t){}getZ(e){return 0}needsUpdate}let n;e.BufferAttribute=t,e.Color=class{constructor(e){}r;g;b},n=e.AdditiveBlending||(e.AdditiveBlending={})}(s||(s={}));class r extends i.EventEmitter2{options;lastFrameWithPredictions;debug=!1;camera=new s.PerspectiveCamera(70,.8,1,5e3);scene=new s.Scene;renderer=new s.WebGLRenderer({antialias:!0});video;videoTexture;mainGroup=new s.Object3D;geometry=new s.PlaneGeometry(640,480,160,120);vidCanvas=document.createElement("canvas");ctx=this.vidCanvas.getContext("2d");fdCanvas=document.createElement("canvas");fdCtx=this.fdCanvas.getContext("2d");pixels=new Uint8ClampedArray;isDisposed=!1;wireMaterial=new s.MeshBasicMaterial({opacity:.1,color:16777215,wireframe:!0,blending:s.AdditiveBlending,transparent:!0});meshMaterial;constructor(e){s=window.THREE,super(),this.options=e,this.video=this.options.videoWorker.video,this.videoTexture=new s.VideoTexture(this.video),this.meshMaterial=new s.MeshBasicMaterial({opacity:1,map:this.options.wireframe.showOriginalVideo?this.videoTexture:void 0,color:"#333"}),this.scene.add(this.camera),this.camera.position.z=600,this.scene.add(this.mainGroup);const t=new s.Mesh(this.geometry,this.meshMaterial);this.mainGroup.add(t);const n=new s.Mesh(this.geometry,this.wireMaterial);this.mainGroup.add(n),n.position.z=5,this.renderer.sortObjects=!1,this.renderer.setSize(400,500),this.renderer.domElement.addEventListener("dblclick",this.toggleDebug.bind(this)),Object.assign(this.renderer.domElement.style,{position:"absolute",top:"0px",left:"0px",display:"block"}),Object.assign(this.vidCanvas.style,{display:"none"}),Object.assign(this.fdCanvas.style,{position:"absolute",top:"0px",left:"0px",width:"100%",display:"none"}),this.fdCanvas.width=400,this.fdCanvas.height