@aws-amplify/ui-react-liveness 1.0.2 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/components/FaceLivenessDetector/service/utils/streamProvider.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/shared/MatchIndicator.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/utils/platform.mjs +1 -0
- package/dist/esm/version.mjs +1 -0
- package/dist/index.js +1 -1
- package/dist/styles.css +6 -6
- package/dist/types/components/FaceLivenessDetector/utils/platform.d.ts +1 -0
- package/dist/types/version.d.ts +1 -1
- package/package.json +4 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncGenerator as i,__await as t}from"tslib";import{Credentials as o,getAmplifyUserAgent as n}from"@aws-amplify/core";import{AmazonAIInterpretPredictionsProvider as
|
|
1
|
+
import{__awaiter as e,__asyncGenerator as i,__await as t}from"tslib";import{Credentials as o,getAmplifyUserAgent as n}from"@aws-amplify/core";import{AmazonAIInterpretPredictionsProvider as r}from"@aws-amplify/predictions";import{RekognitionStreamingClient as s,StartFaceLivenessSessionCommand as d}from"@aws-sdk/client-rekognitionstreaming";import{WebSocketFetchHandler as a}from"@aws-sdk/middleware-websocket";import{VideoRecorder as l}from"./videoRecorder.mjs";import{getLivenessUserAgent as h}from"../../utils/platform.mjs";const c=process.env.NEXT_PUBLIC_STREAMING_API_URL,m=1e3;function v(e){return void 0!==e.Challenge}class u extends r{constructor(e,i,t,o){super(),this.sessionId=e,this.region=i,this._stream=t,this.videoEl=o,this.videoRecorder=new l(t),this.initPromise=this.init()}getResponseStream(){return e(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return e(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return e(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return e(this,void 0,void 0,(function*(){const e=yield o.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:`${n()} ${h}`,requestHandler:new a({connectionTimeout:1e4})};c&&(i.endpointProvider=()=>({url:new URL(c)})),this._client=new s(i),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const o=this;return this._reader=e.getReader(),function(){return i(this,arguments,(function*(){for(;;){const{done:e,value:i}=yield t(o._reader.read());if(e)return yield t(void 0);if("stopVideo"===i)yield yield t({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const e=yield t(i.arrayBuffer()),o=new Uint8Array(e);o.length>0&&(yield yield t({VideoEvent:{VideoChunk:o,TimestampMillis:Date.now()}}))}else v(i)&&(yield yield t({ClientSessionInformationEvent:{Challenge:i.Challenge}}))}}))}}startLivenessVideoConnection(){return e(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new d({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}export{u as LivenessStreamProvider,m as TIME_SLICE};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{LivenessClassNames as t}from"../types/classNames.mjs";const a=({percentage:a,initialPercentage:c=25,testId:s})=>{const[r,n]=e.useState(c);e.useEffect((()=>{n(a<0?0:a>100?100:a)}),[a]);const i={"--percentage":`${r}%`};return e.createElement("div",{className:t.MatchIndicator,"data-testid":s},e.createElement("div",{className:`${t.MatchIndicator}__bar`,style:i})
|
|
1
|
+
import e from"react";import{LivenessClassNames as t}from"../types/classNames.mjs";const a=({percentage:a,initialPercentage:c=25,testId:s})=>{const[r,n]=e.useState(c);e.useEffect((()=>{n(a<0?0:a>100?100:a)}),[a]);const i={"--percentage":`${r}%`};return e.createElement("div",{className:t.MatchIndicator,"data-testid":s},e.createElement("div",{className:`${t.MatchIndicator}__bar`,style:i}))};export{a as MatchIndicator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{VERSION as e}from"../../../version.mjs";const o=`ui-react-liveness/${e}`,r=()=>o;export{r as getLivenessUserAgent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="1.0.5";export{o as VERSION};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@xstate/react"),a=require("tslib"),i=require("xstate"),n=require("@tensorflow/tfjs-core"),r=require("@tensorflow-models/blazeface"),o=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var s=require("@aws-amplify/core"),c=require("@aws-amplify/predictions"),l=require("@aws-sdk/client-rekognitionstreaming"),d=require("@aws-sdk/middleware-websocket"),h=require("nanoid"),u=require("@aws-amplify/ui-react"),m=require("@aws-amplify/ui-react/internal"),f=require("@aws-amplify/ui"),g=require("react-countdown-circle-timer"),v=require("classnames");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function E(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var T,C,x,S=p(e),F=E(e),R=E(n),y=E(r),M=E(o),A=p(g),w=p(v);class D{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(T||(T={})),function(e){e.MATCHED="MATCHED",e.TOO_FAR="TOO FAR",e.TOO_CLOSE="TOO CLOSE",e.CANT_IDENTIFY="CANNOT IDENTIFY",e.FACE_IDENTIFIED="ONE FACE IDENTIFIED",e.TOO_MANY="TOO MANY FACES"}(C||(C={})),function(e){e.TIMEOUT="TIMEOUT",e.RUNTIME_ERROR="RUNTIME_ERROR",e.FRESHNESS_TIMEOUT="FRESHNESS_TIMEOUT",e.SERVER_ERROR="SERVER_ERROR",e.CAMERA_FRAMERATE_ERROR="CAMERA_FRAMERATE_ERROR",e.CAMERA_ACCESS_ERROR="CAMERA_ACCESS_ERROR",e.FACE_DISTANCE_ERROR="FACE_DISTANCE_ERROR",e.MOBILE_LANDSCAPE_ERROR="MOBILE_LANDSCAPE_ERROR"}(x||(x={}));function _(e,t,a){return e*(a-t)+t}function I(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,n=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:n},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:n}}function O(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,n-a)*Math.max(0,r-i));if(0===o)return 0;return o/(Math.abs((e.right-e.left)*(e.bottom-e.top))+Math.abs((t.right-t.left)*(t.bottom-t.top))-o)}function b(e){const{leftEye:t,rightEye:a,mouth:i}=e,n=[];n[0]=(t[0]+a[0])/2,n[1]=(t[1]+a[1])/2;return{pupilDistance:Math.sqrt(Math.pow(t[0]-a[0],2)+Math.pow(t[1]-a[1],2)),faceHeight:Math.sqrt(Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2))}}function k(e,t){const{leftEye:a,rightEye:i,nose:n}=e,{height:r,centerY:o}=t,s=o-r/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=b(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+r)/2?(m=(c[0]+n[0])/2,f=(c[1]+n[1])/2):(m=c[0],f=c[1]);const g=m-h/2,v=f-u/2;return{left:g,top:v,right:g+h,bottom:v+u}}function P(e){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const a=t.getContext("2d");if(a){a.drawImage(e,0,0,t.width,t.height);const i=a.getImageData(0,0,t.width,t.height).data,n=8,r=new Array(n).fill(0);for(let e=0;e<i.length;e++){r[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<n;e++)r[e]>s&&(s=r[e],o=e);return t.remove(),0===o?T.DARK:o===n?T.BRIGHT:T.NORMAL}throw new Error("Cannot find Video Element.")}const L={[x.RUNTIME_ERROR]:"RUNTIME_ERROR",[x.SERVER_ERROR]:"SERVER_ERROR",[x.TIMEOUT]:"TIMEOUT",[x.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[x.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[x.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[x.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[x.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function N({ctx:e,prevColor:t,nextColor:a,fraction:i}){const n=e.canvas.width,r=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,n,r*i),1!==i&&(e.fillStyle=t,e.fillRect(0,r*i,n,r*(1-i)))}const B=e=>!!e;function H(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function V({deviceHeight:e,deviceWidth:t,height:a,width:i,top:n,left:r}){return{Height:a/e,Width:i/t,Top:n/e,Left:r/t}}class W extends D{constructor(e,t){super(),this.faceModelUrl=t,this.binaryPath=null!=e?e:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${M.version_wasm}/dist/`}loadModels(){return a.__awaiter(this,void 0,void 0,(function*(){!function(){try{return!(!window.WebAssembly||!window.WebAssembly.compile&&!window.WebAssembly.compileStreaming)}catch(e){return!1}}()?yield this._loadCPUBackend():yield this._loadWebAssemblyBackend();try{yield R.ready(),this._model=yield s.jitteredExponentialRetry(y.load,[{modelUrl:this.faceModelUrl}])}catch(e){throw new Error("There was an error loading the blazeface model. If you are using a custom blazeface model url ensure that it is a fully qualified url that returns a json file.")}}))}detectFaces(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),a=Date.now();return t.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:n,landmarks:r}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=r[0],m=r[1],f=r[2],g=r[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:n[0],rightEye:u,leftEye:m,mouth:g,nose:f}}))}))}_loadWebAssemblyBackend(){return a.__awaiter(this,void 0,void 0,(function*(){try{M.setWasmPaths(this.binaryPath),yield s.jitteredExponentialRetry((()=>a.__awaiter(this,void 0,void 0,(function*(){if(!(yield R.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(e){throw new Error('There was an error loading the TFJS WASM backend. If you are using a custom WASM path ensure that it ends with "/" and that it is not the full URL as @tensorflow/tfjs-backend-wasm will append the wasm binary file name. Read more: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/src/backend_wasm.ts#L475.')}}))}_loadCPUBackend(){return a.__awaiter(this,void 0,void 0,(function*(){yield R.setBackend("cpu"),this.modelBackend="cpu"}))}}class j{constructor(e,t={}){if("undefined"==typeof MediaRecorder)throw Error("MediaRecorder is not supported by this browser");this._stream=e,this._options=t,this._chunks=[],this._recorder=new MediaRecorder(e,{bitsPerSecond:1e6}),this._setupCallbacks()}getState(){return this._recorder.state}start(e){this.clearRecordedData(),this.recordingStartApiTimestamp=Date.now(),this._recorder.start(e)}stop(){return a.__awaiter(this,void 0,void 0,(function*(){return"recording"===this.getState()&&this._recorder.stop(),this._recorderStopped}))}pause(){this._recorder.pause()}clearRecordedData(){this._chunks=[]}dispatch(e){this._recorder.dispatchEvent(e)}_setupCallbacks(){this.videoStream=new ReadableStream({start:e=>{this._recorder&&(this._recorder.ondataavailable=t=>{t.data&&t.data.size>0&&(0===this._chunks.length&&(this.firstChunkTimestamp=Date.now()),this._chunks.push(t.data),e.enqueue(t.data))},this._recorder.addEventListener("clientSesssionInfo",(t=>{e.enqueue(t.data.clientInfo)})),this._recorder.addEventListener("stopVideo",(()=>{e.enqueue("stopVideo")})),this._recorder.addEventListener("endStream",(()=>{e.close()})))}}),this.recorderStarted=new Promise((e=>{this._recorder.onstart=()=>{this.recorderStartTimestamp=Date.now(),e()}})),this._recorderStopped=new Promise((e=>{this._recorder.onstop=()=>{this.recorderEndTimestamp=Date.now(),e()}})),this._recorder.onerror=()=>{"stopped"!==this.getState()&&this.stop()}}}const z=process.env.NEXT_PUBLIC_STREAMING_API_URL;function q(e){return void 0!==e.Challenge}class U extends c.AmazonAIInterpretPredictionsProvider{constructor(e,t,a,i){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new j(a),this.initPromise=this.init()}getResponseStream(){return a.__awaiter(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return a.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return a.__awaiter(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return a.__awaiter(this,void 0,void 0,(function*(){const e=yield s.Credentials.get();if(!e)throw new Error("No credentials");const t={credentials:e,region:this.region,customUserAgent:s.getAmplifyUserAgent(),requestHandler:new d.WebSocketFetchHandler({connectionTimeout:1e4})};z&&(t.endpointProvider=()=>({url:new URL(z)})),this._client=new l.RekognitionStreamingClient(t),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const t=this;return this._reader=e.getReader(),function(){return a.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:e,value:i}=yield a.__await(t._reader.read());if(e)return yield a.__await(void 0);if("stopVideo"===i)yield yield a.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const e=yield a.__await(i.arrayBuffer()),t=new Uint8Array(e);t.length>0&&(yield yield a.__await({VideoEvent:{VideoChunk:t,TimestampMillis:Date.now()}}))}else q(i)&&(yield yield a.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}))}}))}}startLivenessVideoConnection(){return a.__awaiter(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new l.StartFaceLivenessSessionCommand({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}var Y;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(Y||(Y={}));class ${constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return a.__awaiter(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{setTimeout((()=>{this.displayNextColorTick(e,t)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=Y.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:n}=this.context.ovalAssociatedParams,{videoEl:r}=this.context.videoAssociatedParams,o=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:o,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let s=o-this.timeLastFlatOrScrollChange;if(a.style.display="block",(this.stage===Y.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===Y.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===Y.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:n,heightFraction:r,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=n,m=l*o+s,f=d*o+c,g=e.width,v=e.height,p=e.getContext("2d");if(!p)throw new Error("Cannot find Overlay Canvas.");p.canvas.width=window.innerWidth,p.canvas.height=window.innerHeight,p.clearRect(0,0,g,v),N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.save(),p.beginPath(),p.rect(0,0,g,v),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.9,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.beginPath(),p.ellipse(m,f,h*o/2,u*o/2,0,0,2*Math.PI),p.strokeStyle="white",p.lineWidth=8,p.stroke(),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.75,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:r,ovalDetails:i,heightFraction:t,scaleFactor:n}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===Y.FLAT)this.currColorIndex+=1,this.stage=Y.SCROLLING;else if(this.stage===Y.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=Y.FLAT:(this.stage=Y.SCROLLING,this.currColorIndex+=1)}this.currColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.timeLastFlatOrScrollChange=Date.now(),this.currColorSequence&&this.sendColorStartTime({tickStartTime:e,currColor:this.currColorSequence.color,prevColor:this.prevColorSequence.color,currColorIndex:this.stageIndex})}sendColorStartTime({tickStartTime:e,currColor:t,prevColor:a,currColorIndex:i}){const{livenessStreamProvider:n,challengeId:r}=this.context;n.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:r,ColorDisplayed:{CurrentColor:{RGB:H(t)},PreviousColor:{RGB:H(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const G=e=>!!(null==e?void 0:e.DisconnectionEvent),X=e=>!!(null==e?void 0:e.ValidationException),Z=e=>!!(null==e?void 0:e.InternalServerException),K=e=>!!(null==e?void 0:e.ThrottlingException),Q=e=>!!(null==e?void 0:e.ServiceQuotaExceededException);let J;const ee=i.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,ovalAssociatedParams:void 0,faceMatchAssociatedParams:{illuminationState:void 0,faceMatchState:void 0,faceMatchPercentage:25,currentDetectedFace:void 0,startFace:void 0,endFace:void 0,initialFaceMatchTime:void 0},freshnessColorAssociatedParams:{freshnessColorEl:void 0,freshnessColors:[],freshnessColorsComplete:!1,freshnessColorDisplay:void 0},errorState:void 0,livenessStreamProvider:void 0,responseStreamActorRef:void 0,shouldDisconnect:!1,faceMatchStateBeforeStart:void 0,isFaceFarEnoughBeforeRecording:void 0,isRecordingStopped:!1},on:{CANCEL:"userCancel",TIMEOUT:{target:"retryableTimeout",actions:"updateErrorStateForTimeout"},SET_SESSION_INFO:{internal:!0,actions:"updateSessionInfo"},DISCONNECT_EVENT:{internal:!0,actions:"updateShouldDisconnect"},SET_DOM_AND_CAMERA_DETAILS:{actions:"setDOMAndCameraDetails"},SERVER_ERROR:{target:"error",actions:"updateErrorStateForServer"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","initializeFaceDetector"],invoke:{src:"checkVirtualCameraAndGetStream",onDone:{target:"waitForDOMAndCameraDetails",actions:["updateVideoMediaStream"]},onError:{target:"permissionDenied"}}},waitForDOMAndCameraDetails:{after:{0:{target:"detectFaceBeforeStart",cond:"hasDOMAndCameraDetails"},500:{target:"waitForDOMAndCameraDetails"}}},detectFaceBeforeStart:{invoke:{src:"detectFace",onDone:{target:"checkFaceDetectedBeforeStart",actions:["updateFaceMatchBeforeStartDetails"]}}},checkFaceDetectedBeforeStart:{after:{0:{target:"detectFaceDistanceBeforeRecording",cond:"hasSingleFaceBeforeStart"},100:{target:"detectFaceBeforeStart"}}},detectFaceDistanceBeforeRecording:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceBeforeRecording",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceBeforeRecording:{after:{0:{target:"initializeLivenessStream",cond:"hasEnoughFaceDistanceBeforeRecording"},100:{target:"detectFaceDistanceBeforeRecording"}}},initializeLivenessStream:{invoke:{src:"openLivenessStreamConnection",onDone:{target:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},failure:{entry:"sendTimeoutAfterFaceDistanceDelay",type:"final"}}},recording:{entry:["clearErrorState","startRecording"],initial:"ovalDrawing",states:{ovalDrawing:{entry:["sendTimeoutAfterOvalDrawingDelay"],invoke:{src:"detectInitialFaceAndDrawOval",onDone:{target:"checkFaceDetected",actions:["updateOvalAndFaceDetailsPostDraw","sendTimeoutAfterOvalMatchDelay"]},onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},checkFaceDetected:{after:{0:{target:"checkRecordingStarted",cond:"hasSingleFace"},100:{target:"ovalDrawing"}}},checkRecordingStarted:{after:{0:{target:"ovalMatching",cond:"hasRecordingStarted",actions:["updateRecordingStartTimestampMs"]},100:{target:"checkRecordingStarted"}}},ovalMatching:{entry:["cancelOvalDrawingTimeout"],invoke:{src:"detectFaceAndMatchOval",onDone:{target:"checkMatch",actions:"updateFaceDetailsPostMatch"}}},checkMatch:{after:{0:{target:"flashFreshnessColors",cond:"hasFaceMatchedInOvalWithMinTime",actions:["updateEndFaceMatch","setupFlashFreshnessColors","cancelOvalMatchTimeout","cancelOvalDrawingTimeout"]},.1:{target:"ovalMatching",cond:"hasFaceMatchedInOval",actions:"setFaceMatchTimeAndStartFace"},1:{target:"ovalMatching",cond:"hasNotFaceMatchedInOval"}}},flashFreshnessColors:{invoke:{src:"flashColors",onDone:[{target:"success",cond:"hasFreshnessColorShown"},{target:"flashFreshnessColors",actions:"updateFreshnessDetails"}]}},success:{entry:["stopRecording"],type:"final"}},onDone:"uploading"},uploading:{initial:"pending",states:{pending:{entry:["sendTimeoutAfterWaitingForDisconnect","pauseVideoStream"],invoke:{src:"stopVideo",onDone:"waitForDisconnectEvent",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},waitForDisconnectEvent:{after:{0:{target:"getLivenessResult",cond:"getShouldDisconnect"},100:{target:"waitForDisconnectEvent"}}},getLivenessResult:{entry:["cancelWaitForDisconnectTimeout","freezeStream"],invoke:{src:"getLiveness",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForServer"}}}}},retryableTimeout:{entry:"updateFailedAttempts",always:[{target:"timeout",cond:"shouldTimeoutOnFailedAttempts"},{target:"notRecording"}]},permissionDenied:{entry:"callUserPermissionDeniedCallback",on:{RETRY_CAMERA_CHECK:"cameraCheck"}},mobileLandscapeWarning:{entry:"callMobileLandscapeWarningCallback",always:[{target:"error"}]},timeout:{entry:["cleanUpResources","callUserTimeoutCallback","freezeStream"]},error:{entry:["cleanUpResources","callErrorCallback","cancelOvalDrawingTimeout","cancelWaitForDisconnectTimeout","cancelOvalMatchTimeout","freezeStream"]},userCancel:{entry:["cleanUpResources","callUserCancelCallback","resetContext"],always:[{target:"start"}]}}},{actions:{spawnResponseStreamActor:i.assign({responseStreamActorRef:()=>i.spawn(te)}),updateFailedAttempts:i.assign({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:i.assign({videoAssociatedParams:(e,t)=>{var a,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(i=e.videoAssociatedParams)||void 0===i?void 0:i.videoConstraints)})}}),updateVideoMediaStream:i.assign({videoAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoMediaStream:null===(a=t.data)||void 0===a?void 0:a.stream})}}),initializeFaceDetector:i.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,n=new W(i,a);return n.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:n})}}),updateLivenessStreamProvider:i.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:i.assign({videoAssociatedParams:(e,t)=>{var a,i,n;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(i=t.data)||void 0===i?void 0:i.canvasEl,isMobile:null===(n=t.data)||void 0===n?void 0:n.isMobile})},freshnessColorAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorEl:null===(a=t.data)||void 0===a?void 0:a.freshnessColorEl})}}),updateRecordingStartTimestampMs:i.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:n}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:o}=n.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-r)+r),{width:d,height:h}=s.getTracks()[0].getSettings(),u=d-c.left-c.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:c.timestampMs,BoundingBox:V({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:i.assign({videoAssociatedParams:e=>{if(!e.serverSessionInformation)throw new Error("Session information was not received from response stream");return e.livenessStreamProvider.videoRecorder&&"recording"!==e.livenessStreamProvider.videoRecorder.getState()&&e.livenessStreamProvider.startRecordingLivenessVideo(),Object.assign({},e.videoAssociatedParams)}}),stopRecording:e=>{},updateFaceMatchBeforeStartDetails:i.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:i.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:i.assign({ovalAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.ovalAssociatedParams),{initialFace:t.data.initialFace,ovalDetails:t.data.ovalDetails,scaleFactor:t.data.scaleFactor}),faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,illuminationState:t.data.illuminationState})}),updateFaceDetailsPostMatch:i.assign({faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,faceMatchPercentage:t.data.faceMatchPercentage,illuminationState:t.data.illuminationState,currentDetectedFace:t.data.detectedFace})}),updateEndFaceMatch:i.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:i.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{startFace:void 0===e.faceMatchAssociatedParams.startFace?e.faceMatchAssociatedParams.currentDetectedFace:e.faceMatchAssociatedParams.startFace,initialFaceMatchTime:void 0===e.faceMatchAssociatedParams.initialFaceMatchTime?Date.now():e.faceMatchAssociatedParams.initialFaceMatchTime})}),resetErrorState:i.assign({errorState:e=>{}}),updateErrorStateForTimeout:i.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||x.TIMEOUT}}),updateErrorStateForRuntime:i.assign({errorState:e=>x.RUNTIME_ERROR}),updateErrorStateForServer:i.assign({errorState:e=>x.SERVER_ERROR}),clearErrorState:i.assign({errorState:e=>{}}),updateSessionInfo:i.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:i.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:i.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:i.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,n=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==n&&void 0!==t&&void 0!==a?{color:n,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(B);const i=new $(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:i.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:i.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:i.actions.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:i.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:i.actions.send({type:"TIMEOUT",data:{errorState:x.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:i.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:i.actions.send({type:"TIMEOUT",data:{errorState:x.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:i.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:i.assign({errorState:(e,t)=>{var a,i;let n;n=t.data.message.includes("15 fps")?x.CAMERA_FRAMERATE_ERROR:x.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,o=new Error(r);return o.name=n,null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),n}}),callMobileLandscapeWarningCallback:i.assign({errorState:e=>x.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;null===(a=(t=e.componentProps).onUserCancel)||void 0===a||a.call(t)})),callUserTimeoutCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;const i=new Error(L[e.errorState]);i.name=e.errorState,null===(a=(t=e.componentProps).onError)||void 0===a||a.call(t,i)})),callErrorCallback:(e,t)=>a.__awaiter(void 0,void 0,void 0,(function*(){var a,i,n,r,o,s;const c=(null===(i=null===(a=t.data)||void 0===a?void 0:a.error)||void 0===i?void 0:i.message)||(null===(r=null===(n=t.data)||void 0===n?void 0:n.error)||void 0===r?void 0:r.Message),l=new Error(c);l.name=e.errorState,null===(s=(o=e.componentProps).onError)||void 0===s||s.call(o,l)})),cleanUpResources:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t;const{freshnessColorEl:a}=e.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(t=e.livenessStreamProvider)||void 0===t?void 0:t.endStream()})),freezeStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:t,videoEl:a}=e.videoAssociatedParams;e.isRecordingStopped=!0,null==a||a.pause(),null==t||t.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams;e.isRecordingStopped=!0,t.pause()})),resetContext:i.assign({challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},ovalAssociatedParams:e=>{},errorState:e=>{},livenessStreamProvider:e=>{},responseStreamActorRef:e=>{},shouldDisconnect:!1,faceMatchStateBeforeStart:e=>{},isFaceFarEnoughBeforeRecording:e=>{},isRecordingStopped:!1})},guards:{shouldTimeoutOnFailedAttempts:e=>e.failedAttempts>=e.maxFailedAttempts,hasFaceMatchedInOvalWithMinTime:e=>{const{faceMatchState:t,initialFaceMatchTime:a}=e.faceMatchAssociatedParams,i=Date.now()-a;return t===C.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===C.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==C.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===C.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===C.FACE_IDENTIFIED,hasEnoughFaceDistanceBeforeRecording:e=>e.isFaceFarEnoughBeforeRecording,hasNotEnoughFaceDistanceBeforeRecording:e=>!e.isFaceFarEnoughBeforeRecording,hasLivenessCheckSucceeded:(e,t,a)=>a.state.event.data.isLive,hasFreshnessColorShown:e=>e.freshnessColorAssociatedParams.freshnessColorsComplete,hasServerSessionInfo:e=>void 0!==e.serverSessionInformation,hasDOMAndCameraDetails:e=>void 0!==e.videoAssociatedParams.videoEl&&void 0!==e.videoAssociatedParams.canvasEl&&void 0!==e.freshnessColorAssociatedParams.freshnessColorEl,getShouldDisconnect:e=>!!e.shouldDisconnect,hasRecordingStarted:e=>void 0!==e.livenessStreamProvider.videoRecorder.firstChunkTimestamp},services:{checkVirtualCameraAndGetStream(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:t}=e.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:t,audio:!1}),i=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!function(e){return e.label.toLowerCase().includes("virtual")}(e)));if(!i.length)throw new Error("No real video devices found");const n=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(n.length<1)throw new Error("No camera found with more than 15 fps");const r=n[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===r))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},t),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=new U(e.componentProps.sessionId,e.componentProps.region,e.videoAssociatedParams.videoMediaStream,e.videoAssociatedParams.videoEl);return J=t.getResponseStream(),{livenessStreamProvider:t}}))},detectFace(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams,{faceDetector:i}=e.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const n=yield function(e,t){return a.__awaiter(this,void 0,void 0,(function*(){let a;switch((yield e.detectFaces(t)).length){case 0:a=C.CANT_IDENTIFY;break;case 1:a=C.FACE_IDENTIFIED;break;default:a=C.TOO_MANY}return a}))}(i,t);return{faceMatchState:n}}))},detectFaceDistance(e){return a.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:t}=e,{videoEl:i,videoMediaStream:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.ovalAssociatedParams,{width:s,height:c}=n.getTracks()[0].getSettings(),l=function({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:n=.5}){const r=t;let o=e;const s=.8*a,c=Math.floor(7*e/16),l=Math.floor(9*e/16),d=Math.floor(7*t/16),h=Math.floor(9*t/16),u=_(i,c,l),m=_(n,d,h);e>=t&&(o=3/4*r);const f=s*o,g=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(g)}}({width:s,height:c}),d=yield function({faceDetector:e,videoEl:t,ovalDetails:i,reduceThreshold:n=!1,isMobile:r=!1}){return a.__awaiter(this,void 0,void 0,(function*(){const a=yield e.detectFaces(t);let o,s=!1;switch(a.length){case 0:break;case 1:{o=a[0];const e=i.width,{pupilDistance:t,faceHeight:c}=b(o),l=2;e&&(s=(l*t+1.8*c)/2/l/e<(n?r?.37:.4:.32));break}}return s}))}({faceDetector:o,videoEl:i,ovalDetails:l,reduceThreshold:t,isMobile:r});return{isFaceFarEnoughBeforeRecording:d}}))},detectInitialFaceAndDrawOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t,livenessStreamProvider:a}=e,{videoEl:i,canvasEl:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.ovalAssociatedParams;try{yield o.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const s=yield o.detectFaces(i);let c,l,d;switch(s.length){case 0:l=C.CANT_IDENTIFY,d=P(i);break;case 1:l=C.FACE_IDENTIFIED,c=s[0];break;default:l=C.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();r?(n.width=window.innerWidth,n.height=window.innerHeight):(n.width=h,n.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const n=null===(i=null===(a=null==e?void 0:e.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.OvalParameters;if(!(n&&n.CenterX&&n.CenterY&&n.Width&&n.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-n.CenterX,centerX:n.CenterX,centerY:n.CenterY,width:n.Width,height:n.Height}}({sessionInformation:t,videoWidth:i.width}),g=k(c,f);return c.top=g.top,c.left=g.left,c.height=g.bottom-g.top,c.width=g.right-g.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:n,centerY:r,width:o,height:s}=t,{width:c,height:l}=e.getBoundingClientRect(),d=e.getContext("2d");if(!d)throw new Error("Cannot find Canvas.");{d.clearRect(0,0,c,l),d.fillStyle="rgba(255, 255, 255, 1.0)",d.fillRect(0,0,c,l);const e={width:i.videoWidth,height:i.videoHeight},t={x:(c-e.width*a)/2,y:(l-e.height*a)/2};d.setTransform(a,0,0,a,t.x,t.y),d.beginPath(),d.ellipse(n,r,o/2,s/2,0,0,2*Math.PI),d.strokeStyle="#AEB3B7",d.lineWidth=3,d.stroke(),d.clip(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c,l)}}({canvas:n,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t}=e,{videoEl:a}=e.videoAssociatedParams,{faceDetector:i,ovalDetails:n,initialFace:r}=e.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=k(r,n),{ovalBoundingBox:u}=I(n),m=O(h,u);switch(o.length){case 0:s=C.CANT_IDENTIFY,l=P(a);break;case 1:{c=o[0];const{faceMatchState:e,faceMatchPercentage:a}=function(e,t,a,i){var n,r;let o;const s=null===(r=null===(n=null==i?void 0:i.Challenge)||void 0===n?void 0:n.FaceMovementAndLightChallenge)||void 0===r?void 0:r.ChallengeConfig;if(!(s&&s.OvalIouThreshold&&s.OvalIouHeightThreshold&&s.OvalIouWidthThreshold&&s.FaceIouHeightThreshold&&s.FaceIouWidthThreshold))throw new Error("Challenge information not returned from session information.");const{OvalIouThreshold:c,OvalIouHeightThreshold:l,OvalIouWidthThreshold:d,FaceIouHeightThreshold:h,FaceIouWidthThreshold:u}=s,m=k(e,t),f=m.left,g=m.right,v=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:T,minOvalY:x,maxOvalX:S,maxOvalY:F}=I(t),R=O(m,E),y=c,M=t.width*d,A=t.height*l,w=t.width*u,D=t.height*h,_=100*Math.max(Math.min(1,.75*(R-a)/(y-a)+.25),0);return o=R>y&&Math.abs(T-f)<M&&Math.abs(S-g)<M&&Math.abs(F-p)<A?C.MATCHED:x-v>D||p-F>D||T-f>w&&g-S>w?C.TOO_CLOSE:C.TOO_FAR,{faceMatchState:o,faceMatchPercentage:_}}(c,n,m,t);s=e,d=a;break}default:s=C.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(e){return a.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:t,freshnessColorDisplay:a}=e.freshnessColorAssociatedParams;if(t)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(e){return a.__awaiter(this,void 0,void 0,(function*(){const{challengeId:t,livenessStreamProvider:a}=e,{videoMediaStream:i}=e.videoAssociatedParams,{initialFace:n,ovalDetails:r}=e.ovalAssociatedParams,{startFace:o,endFace:s}=e.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-n.left-n.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,InitialFace:{InitialFaceDetectedTimestamp:n.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(e){return a.__awaiter(this,void 0,void 0,(function*(){const{livenessStreamProvider:t}=e,{onAnalysisComplete:a}=e.componentProps;t.endStream(),yield a()}))}}}),te=e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,i,n,r,o;try{const d=yield J;try{for(var s,c=!0,l=a.__asyncValues(d);!(t=(s=yield l.next()).done);){r=s.value,c=!1;try{const t=r;(null==(o=t)?void 0:o.ServerSessionInformationEvent)?e({type:"SET_SESSION_INFO",data:{sessionInfo:t.ServerSessionInformationEvent.SessionInformation}}):G(t)?e({type:"DISCONNECT_EVENT"}):X(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ValidationException)}}):Z(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.InternalServerException)}}):K(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ThrottlingException)}}):Q(t)&&e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}catch(t){let a=t;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(t)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&e({type:"SERVER_ERROR",data:{error:a}})}})),ae=S.default.createContext(null);function ie(e){var{children:t}=e,i=a.__rest(e,["children"]);return S.default.createElement(ae.Provider,{value:i},t)}function ne(){const e=S.default.useContext(ae);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function re(){const{service:e}=ne();return t.useActor(e)}function oe(e){const{service:a}=ne();return t.useSelector(a,e)}var se;!function(e){e.CameraModule="amplify-liveness-camera-module",e.CancelContainer="amplify-liveness-cancel-container",e.CancelButton="amplify-liveness-cancel-button",e.CountdownContainer="amplify-liveness-countdown-container",e.DescriptionBullet="amplify-liveness-description-bullet",e.DescriptionBulletIndex="amplify-liveness-description-bullet__index",e.DescriptionBulletIndexText="amplify-liveness-description-bullet__index__text",e.DescriptionBulletMessage="amplify-liveness-description-bullet__message",e.FadeOut="amplify-liveness-fade-out",e.FreshnessCanvas="amplify-liveness-freshness-canvas",e.InstructionList="amplify-liveness-instruction-list",e.InstructionOverlay="amplify-liveness-instruction-overlay",e.Figure="amplify-liveness-figure",e.FigureCaption="amplify-liveness-figure__caption",e.FigureIcon="amplify-liveness-figure__icon",e.FigureImage="amplify-liveness-figure__image",e.Figures="amplify-liveness-figures",e.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.Toast="amplify-liveness-toast",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(se||(se={}));const ce=({ariaLabel:e})=>{const[t,a]=re();return t.done?null:S.default.createElement(u.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:se.CancelButton,"aria-label":e},S.default.createElement(m.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},le=e=>{var{variation:t="default",size:i="medium",children:n}=e,r=a.__rest(e,["variation","size","children"]);return F.createElement(u.View,Object.assign({padding:"small",borderRadius:"medium",className:`${se.Toast} ${se.Toast}--${t} ${se.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},r),F.createElement(u.Flex,{gap:"xs",direction:"column",alignItems:"center"},F.createElement(u.Flex,{className:`${se.Toast}__message`,textAlign:"center",direction:"column"},n)))},de=e=>{var{children:t,anchorOrigin:i={horizontal:"center",vertical:"center"}}=e,n=a.__rest(e,["children","anchorOrigin"]);return F.createElement(u.Flex,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:i.horizontal,justifyContent:i.vertical,width:"100%",height:"100%",padding:"xl"},n),t)},he=e=>e.context.errorState,ue=e=>e.context.faceMatchAssociatedParams.faceMatchState,me=e=>e.context.faceMatchAssociatedParams.illuminationState,fe=e=>e.context.isFaceFarEnoughBeforeRecording,ge=e=>e.context.faceMatchStateBeforeStart,ve=({hintDisplayText:e})=>{const[t]=re(),a=oe(he),i=oe(ue),n=oe(me),r=oe(ge),o=oe(fe),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("waitForSessionInfo"),m=t.matches("uploading"),f=t.matches("checkSucceeded"),g=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),p={[C.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[C.FACE_IDENTIFIED]:e.hintTooFarText,[C.TOO_MANY]:e.hintTooManyFacesText,[C.TOO_CLOSE]:e.hintTooCloseText,[C.TOO_FAR]:e.hintTooFarText,[C.MATCHED]:e.hintHoldFaceForFreshnessText},E={[T.BRIGHT]:e.hintIlluminationTooBrightText,[T.DARK]:e.hintIlluminationTooDarkText,[T.NORMAL]:e.hintIlluminationNormalText},x=(()=>{if(!(a||g||f)){if(!l){if(s)return r===C.TOO_MANY?F.createElement(le,null,p[r]):F.createElement(le,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return F.createElement(le,null,e.hintTooCloseText);if(d)return F.createElement(le,null,e.hintHoldFacePositionCountdownText);if(h)return F.createElement(le,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintConnectingText)));if(m)return F.createElement(de,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},F.createElement(le,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintVerifyingText))));if(n&&n!==T.NORMAL)return F.createElement(le,null,E[n])}return v?F.createElement(le,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?F.createElement(le,{size:"large",variation:i===C.TOO_CLOSE?"error":"primary"},i===C.TOO_CLOSE?p[C.TOO_CLOSE]:p[C.TOO_FAR]):null}})();return x||null},pe=({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,n]=S.default.useState(t);S.default.useEffect((()=>{n(e<0?0:e>100?100:e)}),[e]);const r={"--percentage":`${i}%`};return S.default.createElement("div",{className:se.MatchIndicator,"data-testid":a},S.default.createElement("div",{className:`${se.MatchIndicator}__bar`,style:r}),S.default.createElement("div",{className:`${se.MatchIndicator}__pin`,style:r}))},Ee=({children:e})=>S.default.createElement(u.Flex,{className:se.RecordingIcon},S.default.createElement(u.Flex,{"data-testid":"rec-icon",justifyContent:"center"},S.default.createElement(u.Icon,{viewBox:{width:20,height:20},width:"20",height:"20"},S.default.createElement("circle",{cx:"10",cy:"10",r:"8",fill:"red"}))),S.default.createElement(u.Text,{as:"span",fontWeight:"bold"},e)),Te=e=>{var{children:t,caption:i,variation:n="default"}=e,r=a.__rest(e,["children","caption","variation"]);return S.default.createElement(u.Flex,Object.assign({as:"figure",className:`${se.Figure} ${se.Figure}--${n}`},r),S.default.createElement(u.View,{className:`${se.FigureImage} ${se.FigureImage}--${n}`},"success"===n?S.default.createElement("svg",{className:se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),S.default.createElement("path",{fill:"#FFF",d:"m9.435 15.62-4.054-4.055L4 12.936l5.435 5.435L21.101 6.704l-1.37-1.371z"}))):null,"error"===n?S.default.createElement("svg",{className:se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),S.default.createElement("path",{fill:"#FFF",d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}))):null,t),S.default.createElement(u.View,{as:"figcaption",className:`${se.FigureCaption} ${se.FigureCaption}--${n}`},i))},Ce=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(0 -.001)"},S.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",d:"M124.655 0c9.173 8.155 9.394 17.812 13.258 32.385l.053.336.108.726.11.796.112.864.114.931.174 1.515.117 1.087.18 1.739.12 1.23.183 1.944.123 1.36.186 2.13.187 2.232.313 3.928.25 3.31.25 3.443.31 4.463.245 3.679.36 5.658.345 5.778.33 5.841.26 4.876.199 3.883.187 3.849.217 4.738.16 3.712.178 4.515.097 2.63v34.977L.519 150 .517 41.97c3-13.353 9.664-29.4 23.841-41.97h100.297Z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",d:"m50.469 18.849.145.153c9.021 9.393 22.62 16.197 36.089 21.996l2.1.897 1.05.443 2.089.876 8.176 3.385 1.979.825 1.944.82c7.782 3.3 14.617 6.491 19.213 10.006 3.57 2.73 5.793 5.645 5.924 8.999v20.474l-.008.624-.016.669-.04 1.089-.04.777-.047.815-.06.853-.068.887-.08.918-.093.95-.104.978-.057.496-.123 1.016-.066.513-.144 1.049-.076.527-.165 1.077c-.057.36-.116.724-.178 1.086l-.193 1.103-.21 1.116-.11.557-.233 1.13c-.12.564-.247 1.13-.38 1.694l-.275 1.14c-1.037 4.147-2.426 8.3-4.271 11.978-6.17 9.34-12.996 16.035-19.28 20.691l-.8.584-.794.562-.784.539-1.165.77-1.147.724-.755.459c-.249.148-.497.294-.74.434l-.73.416-1.078.588-.702.367-1.033.517-.671.321-.657.303-.643.285-.541.23H68.149a75.81 75.81 0 0 1-.81-.284l-.918-.336a75.953 75.953 0 0 1-.935-.355l-.963-.382a85.513 85.513 0 0 1-1.988-.83l-1.032-.455c-.52-.233-1.05-.475-1.585-.727l-1.087-.517-1.113-.547c-.935-.465-1.893-.959-2.873-1.482l-1.193-.644a141.053 141.053 0 0 1-6.297-3.669l-1.33-.83c-17.11-10.783-22.636-33.458-23.66-49.98l-.071-1.267c-.02-.417-.038-.83-.053-1.235l-.037-1.212a86.317 86.317 0 0 1 .042-5.559l.047-1.002.06-.96.064-.843c1.09-2.51 2.164-4.304 3.296-5.882l.408-.558.415-.545.421-.538 2.026-2.492.481-.597.493-.624.507-.656.518-.69a61.722 61.722 0 0 0 3.769-5.754c4.03-6.917 7.127-14.806 9.544-21.668l.566-1.623.802-2.344 2.077-6.175.416-1.205.395-1.109.373-1.007.267-.682.253-.612c.47-.943.8-1.531 1.06-1.876l-.035.047Z"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m94.566 121.353.722.895c-6.828 5.51-14.13 7.462-21.382 6.447-5.417-.758-10.535-3.2-13.987-6.186l-.318-.282.77-.854c3.285 2.964 8.343 5.434 13.694 6.183 6.797.95 13.632-.819 20.089-5.876l.412-.327Z"}),S.default.createElement("ellipse",{cx:"51.331",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M42.539 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.556 1.005c-5.437-3.01-11.946-2.479-16.175-.153l-.262.148-.577-.995Z"}),S.default.createElement("ellipse",{cx:"103.281",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M94.492 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.557 1.005c-5.436-3.01-11.946-2.479-16.174-.153l-.262.148-.577-.995Zm-22.972 32.9c0 4.216 2.006 7.72 5.831 7.48l.232-.018.115 1.144c-4.774.477-7.239-3.571-7.326-8.345l-.003-.26 1.15-.001h.001Z"}),S.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M75.002.001H0v150h150v-150H75.002Zm0 0c25.627 0 46.402 33.579 46.402 75s-20.775 75-46.402 75c-25.627 0-46.402-33.579-46.402-75s20.775-75 46.402-75Z"}),S.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M120.921 75.001c0 20.555-5.214 39.117-13.589 52.507-8.386 13.406-19.838 21.493-32.313 21.493-12.476 0-23.928-8.087-32.312-21.493-8.377-13.39-13.59-31.952-13.59-52.507 0-20.555 5.214-39.116 13.589-52.507C51.091 9.09 62.543 1.001 75.018 1.001c12.476 0 23.928 8.088 32.314 21.493 8.375 13.39 13.588 31.952 13.588 52.507h.001Z"}))),xe=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("defs",null,S.default.createElement("linearGradient",{id:"a",x1:"50%",x2:"50%",y1:"0%",y2:"100%"},S.default.createElement("stop",{offset:"0%",stopColor:"#C2C2C2"}),S.default.createElement("stop",{offset:"100%",stopColor:"#C2C2C2",stopOpacity:"0"}))),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(2)"},S.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M3.997 0h136v150h-136z"}),S.default.createElement("path",{fill:"url(#a)",fillRule:"nonzero",d:"M4.333 0h138v150h-138z"}),S.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m22.515 58.137-1.895 82.434 98.784-2.343c0-8.798.813-16.271.813-31.497 0-15.748-2.345-55.36-3.766-64.125C108.16 11.338 74.737 5.03 56.707 11.04c-28.425 9.475-33.64 35.095-34.192 47.097Z"}),S.default.createElement("path",{fill:"#EF992A",fillRule:"nonzero",d:"M38.104 138.228c8.339-3.98 5.1-1.525 15.916-3.104H90.5c5.448 0 9.541 3.104 28.904 3.104 6.391 0 5.987 8.988-2.473 8.988-24.315 1.08-66.07 1.08-78.281 0-77.975-6.896-10.97-4.014-.546-8.988Z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m54.306 134.26 2.645-21.765h30.498l3.05 21.765c-15.778 14.791-30.703 6.163-36.193 0zm-27.59-54.458C25.42 66.68 33.467 67.18 37.653 69.07l2.837 25.314c-10.328-2.228-13.772-12.961-13.772-14.58zm89.512-.81c4.05-15.067-3.984-15.998-8.506-14.58L105.9 91.75c10.328-8.505 9.113-12.758 10.328-12.758z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"M53.564 109.804c-14.195-8.986-16.116-30.658-15.302-40.37 2.24-5.21 4.37-5.723 7.958-11.909 6.3-10.86 9.028-25.451 10.579-25.009 14.241 16.008 50.215 20.259 50.649 31.708v13.023c0 4.178-.911 14.358-4.558 21.65-8.986 13.674-20.131 18.612-24.58 19.372-2.334.922-10.55.521-24.746-8.465Z"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m83.935 98.402.85 1.052c-7.974 6.435-17.2 5.243-23.018.18l-.23-.204.905-1.004c5.273 4.756 13.744 5.998 21.175.227l.318-.251Z"}),S.default.createElement("ellipse",{cx:"56.448",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M50.664 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),S.default.createElement("ellipse",{cx:"89.709",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M83.926 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),S.default.createElement("path",{stroke:"#000",strokeWidth:"1.353",d:"M69.005 82.806c0 1.858.859 5.487 4.287 5.144"}),S.default.createElement("path",{fill:"#FFF",d:"M73.004 0H0v150h146V0H73.004Zm.496 0C98.629 0 119 33.579 119 75s-20.371 75-45.5 75S28 116.421 28 75 48.371 0 73.5 0Z"}),S.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M118.4 75c0 20.555-5.156 39.117-13.441 52.507C96.665 140.913 85.338 149 72.999 149c-12.34 0-23.667-8.087-31.961-21.493C32.753 114.117 27.597 95.555 27.597 75c0-20.555 5.156-39.117 13.44-52.507C49.333 9.087 60.66 1 72.999 1c12.34 0 23.667 8.087 31.961 21.493C113.244 35.883 118.4 54.445 118.4 75Z"}))),Se=({children:e})=>{const{tokens:t}=u.useTheme(),a=m.useThemeBreakpoint(),[i,n]=F.useState(!1),r=F.useRef(null),o="base"===a;return F.useEffect((()=>{function e(e){i&&r.current&&!r.current.contains(e.target)&&n(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,i]),F.createElement(u.Flex,{position:"relative",onClick:()=>n(!i),ref:r,style:{cursor:"pointer"},testId:"popover-icon"},F.createElement(m.AlertIcon,{ariaHidden:!0,variation:"info"}),i&&F.createElement(F.Fragment,null,F.createElement(u.Flex,{position:"absolute",top:26,left:3,style:{zIndex:3,borderStyle:"solid",borderWidth:"0 9px 9px 9px",borderColor:`transparent transparent ${t.colors.background.primary} transparent`}}),F.createElement(u.Flex,{position:"absolute",top:24,left:2,style:{zIndex:2,borderStyle:"solid",borderWidth:"0 10px 10px 10px",borderColor:`transparent transparent ${t.colors.border.secondary} transparent`}}),F.createElement(u.Flex,{position:"absolute",backgroundColor:`${t.colors.background.primary}`,color:`${t.colors.font.primary}`,direction:"row",fontSize:t.fontSizes.xs,padding:t.space.small,top:33,minWidth:240,left:o?-190:-108,border:`1px solid ${t.colors.border.secondary}`,borderRadius:2,"data-testid":"popover-text"},e)))};Se.displayName="LivenessIconWithPopover";const Fe=({headingText:e,bodyText:t})=>S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.View,{color:"font.primary"},t)),Re=({headingText:e,bodyText:t,infoText:a})=>S.default.createElement(u.Flex,{className:u.ComponentClassNames.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{className:u.ComponentClassNames.AlertHeading},e),S.default.createElement(u.View,{className:u.ComponentClassNames.AlertBody},t)),S.default.createElement(Se,null,a)),ye=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:n,steps:r})=>S.default.createElement(u.Flex,{direction:"column"},S.default.createElement(u.Text,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.Flex,{className:se.Figures},S.default.createElement(Te,{variation:"success",caption:t},S.default.createElement(Ce,{title:a})),S.default.createElement(Te,{variation:"error",caption:i},S.default.createElement(xe,{title:n}))),S.default.createElement(u.Flex,{as:"ol",className:se.InstructionList},r.map(((e,t)=>S.default.createElement(u.Flex,{as:"li",key:t+1},S.default.createElement(u.Text,{as:"span","aria-hidden":"true"},t+1,"."),S.default.createElement(u.Text,{as:"span"},e)))))),Me="liveness-detector-start";function Ae(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(u.Card,{className:Me,"data-testid":Me},F.createElement(u.Flex,{direction:"column"},(null==a?void 0:a.Header)?F.createElement(a.Header,null):F.createElement(Fe,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?F.createElement(a.PhotosensitiveWarning,null):F.createElement(Re,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?F.createElement(a.Instructions,null):F.createElement(ye,{headingText:i.instructionListHeadingText,goodFitCaptionText:i.goodFitCaptionText,goodFitAltText:i.goodFitAltText,tooFarCaptionText:i.tooFarCaptionText,tooFarAltText:i.tooFarAltText,steps:[i.instructionListStepOneText,i.instructionListStepTwoText,i.instructionListStepThreeText,i.instructionListStepFourText]}),F.createElement(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const we={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fill oval within time limit. Try again and completely fill oval with face within 7 seconds.",faceDistanceHeaderText:"Check failed during countdown",faceDistanceMessageText:"Avoid moving closer during countdown and ensure only one face is in front of camera.",clientHeaderText:"Client error",clientMessageText:"Check failed due to client issue",serverHeaderText:"Server issue",serverMessageText:"Cannot complete check due to server issue",landscapeHeaderText:"Landscape orientation not supported",landscapeMessageText:"Rotate your device to portrait (vertical) orientation.",portraitMessageText:"Ensure your device remains in portrait (vertical) orientation for the check’s duration.",tryAgainText:"Try again"},De=Object.assign({instructionsHeaderHeadingText:"Liveness check",instructionsHeaderBodyText:"You will go through a face verification process to prove that you are a real person.",instructionsBeginCheckText:"Begin check",photosensitivyWarningHeadingText:"Photosensitivity warning",photosensitivyWarningBodyText:"This check displays colored lights. Use caution if you are photosensitive.",photosensitivyWarningInfoText:"A small percentage of individuals may experience epileptic seizures when exposed to colored lights. Use caution if you, or anyone in your family, have an epileptic condition.",instructionListHeadingText:"Follow the instructions to complete the check:",goodFitCaptionText:"Good fit",goodFitAltText:"Ilustration of a person's face, perfectly fitting inside of an oval.",tooFarCaptionText:"Too far",tooFarAltText:"Illustration of a person's face inside of an oval; there is a gap between the perimeter of the face and the boundaries of the oval.",instructionListStepOneText:"When an oval appears, fill the oval with your face within 7 seconds.",instructionListStepTwoText:"Maximize your screen's brightness.",instructionListStepThreeText:"Make sure your face is not covered with sunglasses or a mask.",instructionListStepFourText:"Move to a well-lit place that is not in direct sunlight.",cameraMinSpecificationsHeadingText:"Camera does not meet minimum specifications",cameraMinSpecificationsMessageText:"Camera must support at least 320*240 resolution and 15 frames per second.",cameraNotFoundHeadingText:"Camera not accessible.",cameraNotFoundMessageText:"Check that camera is connected and camera permissions are enabled in settings before retrying.",retryCameraPermissionsText:"Retry",cancelLivenessCheckText:"Cancel Liveness check",recordingIndicatorText:"Rec",hintMoveFaceFrontOfCameraText:"Move face in front of camera",hintTooManyFacesText:"Ensure only one face is in front of camera",hintFaceDetectedText:"Face detected",hintCanNotIdentifyText:"Move face in front of camera",hintTooCloseText:"Move back",hintTooFarText:"Move closer",hintHoldFacePositionCountdownText:"Hold face position during countdown",hintConnectingText:"Connecting...",hintVerifyingText:"Verifying...",hintIlluminationTooBrightText:"Move to dimmer area",hintIlluminationTooDarkText:"Move to brighter area",hintIlluminationNormalText:"Lighting conditions normal",hintHoldFaceForFreshnessText:"Hold still"},we),_e=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},we),t);return e===x.CAMERA_ACCESS_ERROR||e===x.CAMERA_FRAMERATE_ERROR||e===x.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:n,faceDistanceHeaderText:r,faceDistanceMessageText:o,clientHeaderText:s,clientMessageText:c,serverHeaderText:l,serverMessageText:d}=a;let h,f;switch(t){case x.TIMEOUT:h=i,f=n;break;case x.FACE_DISTANCE_ERROR:h=r,f=o;break;case x.RUNTIME_ERROR:h=s,f=c;break;case x.SERVER_ERROR:default:h=l,f=d}return S.default.createElement(S.default.Fragment,null,S.default.createElement(u.Flex,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},S.default.createElement(m.AlertIcon,{ariaHidden:!0,variation:"error"}),S.default.createElement(u.Text,{fontWeight:"bold"},h)),f)})({error:e,displayText:a})},Ie=e=>{const{children:t,onRetry:a,displayText:i}=e,n=Object.assign(Object.assign({},we),i),{tryAgainText:r}=n;return S.default.createElement(de,{backgroundColor:"overlay.40"},S.default.createElement(le,null,t,S.default.createElement(u.Flex,{justifyContent:"center"},S.default.createElement(u.Button,{variation:"primary",type:"button",onClick:a},r))))},Oe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},be=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},ke=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,Pe=e=>e.context.faceMatchAssociatedParams.faceMatchState,Le=S.default.createElement(u.Loader,{size:"large",className:se.Loader,"data-testid":"centered-loader"}),Ne=t=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:n,hintDisplayText:r,errorDisplayText:o,components:s,testId:c}=t,{cancelLivenessCheckText:l,recordingIndicatorText:d}=n,{ErrorView:h=Ie}=null!=s?s:{},{tokens:m}=u.useTheme(),[g,v]=re(),p=oe(be),E=oe(Oe),T=oe(ke),x=oe(Pe),F=oe(he),R=[C.TOO_FAR,C.CANT_IDENTIFY,C.FACE_IDENTIFIED,C.MATCHED],{videoRef:y,videoWidth:M,videoHeight:D}=function(t,a){const i=a.height.ideal,n=a.width.ideal,r=e.useRef(null),[o,s]=e.useState(i),[c,l]=e.useState(n);return e.useEffect((()=>{if(t){f.isObject(r.current)&&(r.current.srcObject=t);const{height:e,width:a}=t.getTracks()[0].getSettings();s(e),l(a)}return()=>{t&&t.getTracks().forEach((e=>{t.removeTrack(e),e.stop()}))}}),[t]),{videoRef:r,videoHeight:o,videoWidth:c}}(p,E),_=e.useRef(null),I=e.useRef(null),[O,b]=e.useState(!1),[k,P]=e.useState(!1),L=g.matches("cameraCheck"),N=g.matches("notRecording"),B=g.matches("recording"),H=g.matches("checkSucceeded"),V=g.matches({recording:"flashFreshnessColors"}),[W,j]=e.useState(M),[z,q]=e.useState(D),[U,Y]=e.useState((()=>M&&D?M/D:0));S.default.useLayoutEffect((()=>{k&&v({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:y.current,canvasEl:_.current,freshnessColorEl:I.current,isMobile:a}}),y.current&&(j(y.current.videoWidth),q(y.current.videoHeight),Y(y.current.videoWidth/y.current.videoHeight))}),[v,y,k,a]);return L?S.default.createElement(u.Flex,{height:D,width:"100%",position:"relative"},Le):S.default.createElement(u.Flex,{className:w.default(se.CameraModule,a&&`${se.CameraModule}--mobile`),"data-testid":c},!k&&Le,S.default.createElement(u.View,{as:"canvas",ref:I,className:se.FreshnessCanvas,hidden:!0}),S.default.createElement(u.View,{className:se.VideoAnchor,style:{aspectRatio:`${U}`}},S.default.createElement("video",{ref:y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:W,height:z,onCanPlay:()=>{P(!0),b(!0)},"data-testid":"video",className:se.Video}),S.default.createElement(u.Flex,{className:w.default(se.OvalCanvas,a&&`${se.OvalCanvas}--mobile`,i&&se.FadeOut)},S.default.createElement(u.View,{as:"canvas",width:"100%",height:"100%",ref:_})),B&&S.default.createElement(u.View,{className:se.RecordingIconContainer},S.default.createElement(Ee,null,d)),!H&&S.default.createElement(u.View,{className:se.CancelContainer},S.default.createElement(ce,{ariaLabel:l})),O&&S.default.createElement(de,{anchorOrigin:{horizontal:"center",vertical:B&&!V?"start":"space-between"},className:se.InstructionOverlay},S.default.createElement(ve,{hintDisplayText:r}),F&&S.default.createElement(h,{onRetry:()=>{v({type:"CANCEL"})}},_e({errorState:F,overrideErrorDisplayText:o})),B&&!V&&R.includes(x)?S.default.createElement(pe,{percentage:T}):null,N&&S.default.createElement(u.View,{className:se.CountdownContainer,testId:"liveness-camera-countdown-timer"},S.default.createElement(A.default.CountdownCircleTimer,{isPlaying:N,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${m.colors.background.primary}`,onComplete:()=>{v({type:"START_RECORDING"})}},(({remainingTime:e})=>S.default.createElement(u.Text,{fontSize:"xxxl",fontWeight:"bold"},e)))))))};function Be(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function He(){return window.matchMedia("(orientation: landscape)")}const Ve=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:n,tryAgainText:r}=e,[o,s]=F.useState(!0);return F.useLayoutEffect((()=>{const e=He();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:o?"auto":480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},a),F.createElement(u.Text,null,o?n:i),o?null:F.createElement(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},r)))},We="liveness-detector-check",je=e=>e.context.errorState,ze=e=>e.context.isRecordingStopped,qe=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:n})=>{const[r,o]=re(),s=oe(je),c=oe(ze),l=r.matches("permissionDenied"),d=Be(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:m,cameraMinSpecificationsMessageText:f,cameraNotFoundHeadingText:g,cameraNotFoundMessageText:v,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;F.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=He();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[d,o]);return F.createElement(u.Flex,{direction:"column",position:"relative",testId:We,className:We},(()=>{if(s===x.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},we),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:n,tryAgainText:r}=e;return F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},F.createElement(Ve,{header:t,portraitMessage:a,landscapeMessage:n,tryAgainText:r,onRetry:()=>{o({type:"CANCEL"})}}))}return l?F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},s===x.CAMERA_FRAMERATE_ERROR?m:g),F.createElement(u.Text,{maxWidth:300},s===x.CAMERA_FRAMERATE_ERROR?f:v),F.createElement(u.Button,{variation:"primary",type:"button",onClick:h},p),F.createElement(u.View,{position:"absolute",top:"medium",right:"medium"},F.createElement(ce,{ariaLabel:E}))):F.createElement(Ne,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:n})})())};const Ue="liveness-detector";exports.FaceLivenessDetector=function(e){const{disableInstructionScreen:a=!1,components:i,config:n,displayText:r}=e,o=F.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},De),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x,cancelLivenessCheckText:S,recordingIndicatorText:F,hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v},streamDisplayText:{cancelLivenessCheckText:S,recordingIndicatorText:F},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}}}(r),m=t.useInterpret(ee,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=n?n:{}})}}),[f,g]=t.useActor(m),v=f.matches("start")||f.matches("userCancel"),p=F.useCallback((()=>{g({type:"BEGIN",data:{videoConstraints:{width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"}}})}),[g]);return F.useLayoutEffect((()=>{a&&v&&p()}),[p,a,v]),F.createElement(u.View,{className:Ue,testId:Ue},F.createElement(ie,{componentProps:e,service:m},F.createElement(u.Flex,{direction:"column",ref:o},v?F.createElement(Ae,{beginLivenessCheck:p,components:i,instructionDisplayText:l}):F.createElement(qe,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:i}))))};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@xstate/react"),a=require("tslib"),i=require("xstate"),n=require("@tensorflow/tfjs-core"),r=require("@tensorflow-models/blazeface"),o=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var s=require("@aws-amplify/core"),c=require("@aws-amplify/predictions"),l=require("@aws-sdk/client-rekognitionstreaming"),d=require("@aws-sdk/middleware-websocket"),h=require("nanoid"),u=require("@aws-amplify/ui-react"),m=require("@aws-amplify/ui-react/internal"),f=require("@aws-amplify/ui"),g=require("react-countdown-circle-timer"),v=require("classnames");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function E(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var T,C,x,S=p(e),F=E(e),R=E(n),y=E(r),M=E(o),A=p(g),w=p(v);class D{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(T||(T={})),function(e){e.MATCHED="MATCHED",e.TOO_FAR="TOO FAR",e.TOO_CLOSE="TOO CLOSE",e.CANT_IDENTIFY="CANNOT IDENTIFY",e.FACE_IDENTIFIED="ONE FACE IDENTIFIED",e.TOO_MANY="TOO MANY FACES"}(C||(C={})),function(e){e.TIMEOUT="TIMEOUT",e.RUNTIME_ERROR="RUNTIME_ERROR",e.FRESHNESS_TIMEOUT="FRESHNESS_TIMEOUT",e.SERVER_ERROR="SERVER_ERROR",e.CAMERA_FRAMERATE_ERROR="CAMERA_FRAMERATE_ERROR",e.CAMERA_ACCESS_ERROR="CAMERA_ACCESS_ERROR",e.FACE_DISTANCE_ERROR="FACE_DISTANCE_ERROR",e.MOBILE_LANDSCAPE_ERROR="MOBILE_LANDSCAPE_ERROR"}(x||(x={}));function _(e,t,a){return e*(a-t)+t}function I(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,n=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:n},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:n}}function O(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,n-a)*Math.max(0,r-i));if(0===o)return 0;return o/(Math.abs((e.right-e.left)*(e.bottom-e.top))+Math.abs((t.right-t.left)*(t.bottom-t.top))-o)}function b(e){const{leftEye:t,rightEye:a,mouth:i}=e,n=[];n[0]=(t[0]+a[0])/2,n[1]=(t[1]+a[1])/2;return{pupilDistance:Math.sqrt(Math.pow(t[0]-a[0],2)+Math.pow(t[1]-a[1],2)),faceHeight:Math.sqrt(Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2))}}function k(e,t){const{leftEye:a,rightEye:i,nose:n}=e,{height:r,centerY:o}=t,s=o-r/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=b(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+r)/2?(m=(c[0]+n[0])/2,f=(c[1]+n[1])/2):(m=c[0],f=c[1]);const g=m-h/2,v=f-u/2;return{left:g,top:v,right:g+h,bottom:v+u}}function P(e){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const a=t.getContext("2d");if(a){a.drawImage(e,0,0,t.width,t.height);const i=a.getImageData(0,0,t.width,t.height).data,n=8,r=new Array(n).fill(0);for(let e=0;e<i.length;e++){r[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<n;e++)r[e]>s&&(s=r[e],o=e);return t.remove(),0===o?T.DARK:o===n?T.BRIGHT:T.NORMAL}throw new Error("Cannot find Video Element.")}const L={[x.RUNTIME_ERROR]:"RUNTIME_ERROR",[x.SERVER_ERROR]:"SERVER_ERROR",[x.TIMEOUT]:"TIMEOUT",[x.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[x.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[x.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[x.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[x.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function N({ctx:e,prevColor:t,nextColor:a,fraction:i}){const n=e.canvas.width,r=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,n,r*i),1!==i&&(e.fillStyle=t,e.fillRect(0,r*i,n,r*(1-i)))}const B=e=>!!e;function H(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function V({deviceHeight:e,deviceWidth:t,height:a,width:i,top:n,left:r}){return{Height:a/e,Width:i/t,Top:n/e,Left:r/t}}class W extends D{constructor(e,t){super(),this.faceModelUrl=t,this.binaryPath=null!=e?e:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${M.version_wasm}/dist/`}loadModels(){return a.__awaiter(this,void 0,void 0,(function*(){!function(){try{return!(!window.WebAssembly||!window.WebAssembly.compile&&!window.WebAssembly.compileStreaming)}catch(e){return!1}}()?yield this._loadCPUBackend():yield this._loadWebAssemblyBackend();try{yield R.ready(),this._model=yield s.jitteredExponentialRetry(y.load,[{modelUrl:this.faceModelUrl}])}catch(e){throw new Error("There was an error loading the blazeface model. If you are using a custom blazeface model url ensure that it is a fully qualified url that returns a json file.")}}))}detectFaces(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),a=Date.now();return t.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:n,landmarks:r}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=r[0],m=r[1],f=r[2],g=r[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:n[0],rightEye:u,leftEye:m,mouth:g,nose:f}}))}))}_loadWebAssemblyBackend(){return a.__awaiter(this,void 0,void 0,(function*(){try{M.setWasmPaths(this.binaryPath),yield s.jitteredExponentialRetry((()=>a.__awaiter(this,void 0,void 0,(function*(){if(!(yield R.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(e){throw new Error('There was an error loading the TFJS WASM backend. If you are using a custom WASM path ensure that it ends with "/" and that it is not the full URL as @tensorflow/tfjs-backend-wasm will append the wasm binary file name. Read more: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/src/backend_wasm.ts#L475.')}}))}_loadCPUBackend(){return a.__awaiter(this,void 0,void 0,(function*(){yield R.setBackend("cpu"),this.modelBackend="cpu"}))}}class j{constructor(e,t={}){if("undefined"==typeof MediaRecorder)throw Error("MediaRecorder is not supported by this browser");this._stream=e,this._options=t,this._chunks=[],this._recorder=new MediaRecorder(e,{bitsPerSecond:1e6}),this._setupCallbacks()}getState(){return this._recorder.state}start(e){this.clearRecordedData(),this.recordingStartApiTimestamp=Date.now(),this._recorder.start(e)}stop(){return a.__awaiter(this,void 0,void 0,(function*(){return"recording"===this.getState()&&this._recorder.stop(),this._recorderStopped}))}pause(){this._recorder.pause()}clearRecordedData(){this._chunks=[]}dispatch(e){this._recorder.dispatchEvent(e)}_setupCallbacks(){this.videoStream=new ReadableStream({start:e=>{this._recorder&&(this._recorder.ondataavailable=t=>{t.data&&t.data.size>0&&(0===this._chunks.length&&(this.firstChunkTimestamp=Date.now()),this._chunks.push(t.data),e.enqueue(t.data))},this._recorder.addEventListener("clientSesssionInfo",(t=>{e.enqueue(t.data.clientInfo)})),this._recorder.addEventListener("stopVideo",(()=>{e.enqueue("stopVideo")})),this._recorder.addEventListener("endStream",(()=>{e.close()})))}}),this.recorderStarted=new Promise((e=>{this._recorder.onstart=()=>{this.recorderStartTimestamp=Date.now(),e()}})),this._recorderStopped=new Promise((e=>{this._recorder.onstop=()=>{this.recorderEndTimestamp=Date.now(),e()}})),this._recorder.onerror=()=>{"stopped"!==this.getState()&&this.stop()}}}const z=()=>"ui-react-liveness/1.0.5",q=process.env.NEXT_PUBLIC_STREAMING_API_URL;function U(e){return void 0!==e.Challenge}class Y extends c.AmazonAIInterpretPredictionsProvider{constructor(e,t,a,i){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new j(a),this.initPromise=this.init()}getResponseStream(){return a.__awaiter(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return a.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return a.__awaiter(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return a.__awaiter(this,void 0,void 0,(function*(){const e=yield s.Credentials.get();if(!e)throw new Error("No credentials");const t={credentials:e,region:this.region,customUserAgent:`${s.getAmplifyUserAgent()} ${z}`,requestHandler:new d.WebSocketFetchHandler({connectionTimeout:1e4})};q&&(t.endpointProvider=()=>({url:new URL(q)})),this._client=new l.RekognitionStreamingClient(t),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const t=this;return this._reader=e.getReader(),function(){return a.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:e,value:i}=yield a.__await(t._reader.read());if(e)return yield a.__await(void 0);if("stopVideo"===i)yield yield a.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const e=yield a.__await(i.arrayBuffer()),t=new Uint8Array(e);t.length>0&&(yield yield a.__await({VideoEvent:{VideoChunk:t,TimestampMillis:Date.now()}}))}else U(i)&&(yield yield a.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}))}}))}}startLivenessVideoConnection(){return a.__awaiter(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new l.StartFaceLivenessSessionCommand({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}var $;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}($||($={}));class G{constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return a.__awaiter(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{setTimeout((()=>{this.displayNextColorTick(e,t)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=$.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:n}=this.context.ovalAssociatedParams,{videoEl:r}=this.context.videoAssociatedParams,o=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:o,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let s=o-this.timeLastFlatOrScrollChange;if(a.style.display="block",(this.stage===$.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===$.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===$.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:n,heightFraction:r,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=n,m=l*o+s,f=d*o+c,g=e.width,v=e.height,p=e.getContext("2d");if(!p)throw new Error("Cannot find Overlay Canvas.");p.canvas.width=window.innerWidth,p.canvas.height=window.innerHeight,p.clearRect(0,0,g,v),N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.save(),p.beginPath(),p.rect(0,0,g,v),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.9,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.beginPath(),p.ellipse(m,f,h*o/2,u*o/2,0,0,2*Math.PI),p.strokeStyle="white",p.lineWidth=8,p.stroke(),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.75,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:r,ovalDetails:i,heightFraction:t,scaleFactor:n}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===$.FLAT)this.currColorIndex+=1,this.stage=$.SCROLLING;else if(this.stage===$.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=$.FLAT:(this.stage=$.SCROLLING,this.currColorIndex+=1)}this.currColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.timeLastFlatOrScrollChange=Date.now(),this.currColorSequence&&this.sendColorStartTime({tickStartTime:e,currColor:this.currColorSequence.color,prevColor:this.prevColorSequence.color,currColorIndex:this.stageIndex})}sendColorStartTime({tickStartTime:e,currColor:t,prevColor:a,currColorIndex:i}){const{livenessStreamProvider:n,challengeId:r}=this.context;n.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:r,ColorDisplayed:{CurrentColor:{RGB:H(t)},PreviousColor:{RGB:H(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const X=e=>!!(null==e?void 0:e.DisconnectionEvent),Z=e=>!!(null==e?void 0:e.ValidationException),K=e=>!!(null==e?void 0:e.InternalServerException),Q=e=>!!(null==e?void 0:e.ThrottlingException),J=e=>!!(null==e?void 0:e.ServiceQuotaExceededException);let ee;const te=i.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,ovalAssociatedParams:void 0,faceMatchAssociatedParams:{illuminationState:void 0,faceMatchState:void 0,faceMatchPercentage:25,currentDetectedFace:void 0,startFace:void 0,endFace:void 0,initialFaceMatchTime:void 0},freshnessColorAssociatedParams:{freshnessColorEl:void 0,freshnessColors:[],freshnessColorsComplete:!1,freshnessColorDisplay:void 0},errorState:void 0,livenessStreamProvider:void 0,responseStreamActorRef:void 0,shouldDisconnect:!1,faceMatchStateBeforeStart:void 0,isFaceFarEnoughBeforeRecording:void 0,isRecordingStopped:!1},on:{CANCEL:"userCancel",TIMEOUT:{target:"retryableTimeout",actions:"updateErrorStateForTimeout"},SET_SESSION_INFO:{internal:!0,actions:"updateSessionInfo"},DISCONNECT_EVENT:{internal:!0,actions:"updateShouldDisconnect"},SET_DOM_AND_CAMERA_DETAILS:{actions:"setDOMAndCameraDetails"},SERVER_ERROR:{target:"error",actions:"updateErrorStateForServer"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","initializeFaceDetector"],invoke:{src:"checkVirtualCameraAndGetStream",onDone:{target:"waitForDOMAndCameraDetails",actions:["updateVideoMediaStream"]},onError:{target:"permissionDenied"}}},waitForDOMAndCameraDetails:{after:{0:{target:"detectFaceBeforeStart",cond:"hasDOMAndCameraDetails"},500:{target:"waitForDOMAndCameraDetails"}}},detectFaceBeforeStart:{invoke:{src:"detectFace",onDone:{target:"checkFaceDetectedBeforeStart",actions:["updateFaceMatchBeforeStartDetails"]}}},checkFaceDetectedBeforeStart:{after:{0:{target:"detectFaceDistanceBeforeRecording",cond:"hasSingleFaceBeforeStart"},100:{target:"detectFaceBeforeStart"}}},detectFaceDistanceBeforeRecording:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceBeforeRecording",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceBeforeRecording:{after:{0:{target:"initializeLivenessStream",cond:"hasEnoughFaceDistanceBeforeRecording"},100:{target:"detectFaceDistanceBeforeRecording"}}},initializeLivenessStream:{invoke:{src:"openLivenessStreamConnection",onDone:{target:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},failure:{entry:"sendTimeoutAfterFaceDistanceDelay",type:"final"}}},recording:{entry:["clearErrorState","startRecording"],initial:"ovalDrawing",states:{ovalDrawing:{entry:["sendTimeoutAfterOvalDrawingDelay"],invoke:{src:"detectInitialFaceAndDrawOval",onDone:{target:"checkFaceDetected",actions:["updateOvalAndFaceDetailsPostDraw","sendTimeoutAfterOvalMatchDelay"]},onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},checkFaceDetected:{after:{0:{target:"checkRecordingStarted",cond:"hasSingleFace"},100:{target:"ovalDrawing"}}},checkRecordingStarted:{after:{0:{target:"ovalMatching",cond:"hasRecordingStarted",actions:["updateRecordingStartTimestampMs"]},100:{target:"checkRecordingStarted"}}},ovalMatching:{entry:["cancelOvalDrawingTimeout"],invoke:{src:"detectFaceAndMatchOval",onDone:{target:"checkMatch",actions:"updateFaceDetailsPostMatch"}}},checkMatch:{after:{0:{target:"flashFreshnessColors",cond:"hasFaceMatchedInOvalWithMinTime",actions:["updateEndFaceMatch","setupFlashFreshnessColors","cancelOvalMatchTimeout","cancelOvalDrawingTimeout"]},.1:{target:"ovalMatching",cond:"hasFaceMatchedInOval",actions:"setFaceMatchTimeAndStartFace"},1:{target:"ovalMatching",cond:"hasNotFaceMatchedInOval"}}},flashFreshnessColors:{invoke:{src:"flashColors",onDone:[{target:"success",cond:"hasFreshnessColorShown"},{target:"flashFreshnessColors",actions:"updateFreshnessDetails"}]}},success:{entry:["stopRecording"],type:"final"}},onDone:"uploading"},uploading:{initial:"pending",states:{pending:{entry:["sendTimeoutAfterWaitingForDisconnect","pauseVideoStream"],invoke:{src:"stopVideo",onDone:"waitForDisconnectEvent",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},waitForDisconnectEvent:{after:{0:{target:"getLivenessResult",cond:"getShouldDisconnect"},100:{target:"waitForDisconnectEvent"}}},getLivenessResult:{entry:["cancelWaitForDisconnectTimeout","freezeStream"],invoke:{src:"getLiveness",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForServer"}}}}},retryableTimeout:{entry:"updateFailedAttempts",always:[{target:"timeout",cond:"shouldTimeoutOnFailedAttempts"},{target:"notRecording"}]},permissionDenied:{entry:"callUserPermissionDeniedCallback",on:{RETRY_CAMERA_CHECK:"cameraCheck"}},mobileLandscapeWarning:{entry:"callMobileLandscapeWarningCallback",always:[{target:"error"}]},timeout:{entry:["cleanUpResources","callUserTimeoutCallback","freezeStream"]},error:{entry:["cleanUpResources","callErrorCallback","cancelOvalDrawingTimeout","cancelWaitForDisconnectTimeout","cancelOvalMatchTimeout","freezeStream"]},userCancel:{entry:["cleanUpResources","callUserCancelCallback","resetContext"],always:[{target:"start"}]}}},{actions:{spawnResponseStreamActor:i.assign({responseStreamActorRef:()=>i.spawn(ae)}),updateFailedAttempts:i.assign({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:i.assign({videoAssociatedParams:(e,t)=>{var a,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(i=e.videoAssociatedParams)||void 0===i?void 0:i.videoConstraints)})}}),updateVideoMediaStream:i.assign({videoAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoMediaStream:null===(a=t.data)||void 0===a?void 0:a.stream})}}),initializeFaceDetector:i.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,n=new W(i,a);return n.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:n})}}),updateLivenessStreamProvider:i.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:i.assign({videoAssociatedParams:(e,t)=>{var a,i,n;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(i=t.data)||void 0===i?void 0:i.canvasEl,isMobile:null===(n=t.data)||void 0===n?void 0:n.isMobile})},freshnessColorAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorEl:null===(a=t.data)||void 0===a?void 0:a.freshnessColorEl})}}),updateRecordingStartTimestampMs:i.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:n}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:o}=n.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-r)+r),{width:d,height:h}=s.getTracks()[0].getSettings(),u=d-c.left-c.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:c.timestampMs,BoundingBox:V({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:i.assign({videoAssociatedParams:e=>{if(!e.serverSessionInformation)throw new Error("Session information was not received from response stream");return e.livenessStreamProvider.videoRecorder&&"recording"!==e.livenessStreamProvider.videoRecorder.getState()&&e.livenessStreamProvider.startRecordingLivenessVideo(),Object.assign({},e.videoAssociatedParams)}}),stopRecording:e=>{},updateFaceMatchBeforeStartDetails:i.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:i.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:i.assign({ovalAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.ovalAssociatedParams),{initialFace:t.data.initialFace,ovalDetails:t.data.ovalDetails,scaleFactor:t.data.scaleFactor}),faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,illuminationState:t.data.illuminationState})}),updateFaceDetailsPostMatch:i.assign({faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,faceMatchPercentage:t.data.faceMatchPercentage,illuminationState:t.data.illuminationState,currentDetectedFace:t.data.detectedFace})}),updateEndFaceMatch:i.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:i.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{startFace:void 0===e.faceMatchAssociatedParams.startFace?e.faceMatchAssociatedParams.currentDetectedFace:e.faceMatchAssociatedParams.startFace,initialFaceMatchTime:void 0===e.faceMatchAssociatedParams.initialFaceMatchTime?Date.now():e.faceMatchAssociatedParams.initialFaceMatchTime})}),resetErrorState:i.assign({errorState:e=>{}}),updateErrorStateForTimeout:i.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||x.TIMEOUT}}),updateErrorStateForRuntime:i.assign({errorState:e=>x.RUNTIME_ERROR}),updateErrorStateForServer:i.assign({errorState:e=>x.SERVER_ERROR}),clearErrorState:i.assign({errorState:e=>{}}),updateSessionInfo:i.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:i.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:i.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:i.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,n=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==n&&void 0!==t&&void 0!==a?{color:n,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(B);const i=new G(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:i.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:i.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:i.actions.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:i.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:i.actions.send({type:"TIMEOUT",data:{errorState:x.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:i.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:i.actions.send({type:"TIMEOUT",data:{errorState:x.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:i.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:i.assign({errorState:(e,t)=>{var a,i;let n;n=t.data.message.includes("15 fps")?x.CAMERA_FRAMERATE_ERROR:x.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,o=new Error(r);return o.name=n,null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),n}}),callMobileLandscapeWarningCallback:i.assign({errorState:e=>x.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;null===(a=(t=e.componentProps).onUserCancel)||void 0===a||a.call(t)})),callUserTimeoutCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;const i=new Error(L[e.errorState]);i.name=e.errorState,null===(a=(t=e.componentProps).onError)||void 0===a||a.call(t,i)})),callErrorCallback:(e,t)=>a.__awaiter(void 0,void 0,void 0,(function*(){var a,i,n,r,o,s;const c=(null===(i=null===(a=t.data)||void 0===a?void 0:a.error)||void 0===i?void 0:i.message)||(null===(r=null===(n=t.data)||void 0===n?void 0:n.error)||void 0===r?void 0:r.Message),l=new Error(c);l.name=e.errorState,null===(s=(o=e.componentProps).onError)||void 0===s||s.call(o,l)})),cleanUpResources:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t;const{freshnessColorEl:a}=e.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(t=e.livenessStreamProvider)||void 0===t?void 0:t.endStream()})),freezeStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:t,videoEl:a}=e.videoAssociatedParams;e.isRecordingStopped=!0,null==a||a.pause(),null==t||t.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams;e.isRecordingStopped=!0,t.pause()})),resetContext:i.assign({challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},ovalAssociatedParams:e=>{},errorState:e=>{},livenessStreamProvider:e=>{},responseStreamActorRef:e=>{},shouldDisconnect:!1,faceMatchStateBeforeStart:e=>{},isFaceFarEnoughBeforeRecording:e=>{},isRecordingStopped:!1})},guards:{shouldTimeoutOnFailedAttempts:e=>e.failedAttempts>=e.maxFailedAttempts,hasFaceMatchedInOvalWithMinTime:e=>{const{faceMatchState:t,initialFaceMatchTime:a}=e.faceMatchAssociatedParams,i=Date.now()-a;return t===C.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===C.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==C.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===C.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===C.FACE_IDENTIFIED,hasEnoughFaceDistanceBeforeRecording:e=>e.isFaceFarEnoughBeforeRecording,hasNotEnoughFaceDistanceBeforeRecording:e=>!e.isFaceFarEnoughBeforeRecording,hasLivenessCheckSucceeded:(e,t,a)=>a.state.event.data.isLive,hasFreshnessColorShown:e=>e.freshnessColorAssociatedParams.freshnessColorsComplete,hasServerSessionInfo:e=>void 0!==e.serverSessionInformation,hasDOMAndCameraDetails:e=>void 0!==e.videoAssociatedParams.videoEl&&void 0!==e.videoAssociatedParams.canvasEl&&void 0!==e.freshnessColorAssociatedParams.freshnessColorEl,getShouldDisconnect:e=>!!e.shouldDisconnect,hasRecordingStarted:e=>void 0!==e.livenessStreamProvider.videoRecorder.firstChunkTimestamp},services:{checkVirtualCameraAndGetStream(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:t}=e.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:t,audio:!1}),i=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!function(e){return e.label.toLowerCase().includes("virtual")}(e)));if(!i.length)throw new Error("No real video devices found");const n=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(n.length<1)throw new Error("No camera found with more than 15 fps");const r=n[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===r))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},t),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=new Y(e.componentProps.sessionId,e.componentProps.region,e.videoAssociatedParams.videoMediaStream,e.videoAssociatedParams.videoEl);return ee=t.getResponseStream(),{livenessStreamProvider:t}}))},detectFace(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams,{faceDetector:i}=e.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const n=yield function(e,t){return a.__awaiter(this,void 0,void 0,(function*(){let a;switch((yield e.detectFaces(t)).length){case 0:a=C.CANT_IDENTIFY;break;case 1:a=C.FACE_IDENTIFIED;break;default:a=C.TOO_MANY}return a}))}(i,t);return{faceMatchState:n}}))},detectFaceDistance(e){return a.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:t}=e,{videoEl:i,videoMediaStream:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.ovalAssociatedParams,{width:s,height:c}=n.getTracks()[0].getSettings(),l=function({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:n=.5}){const r=t;let o=e;const s=.8*a,c=Math.floor(7*e/16),l=Math.floor(9*e/16),d=Math.floor(7*t/16),h=Math.floor(9*t/16),u=_(i,c,l),m=_(n,d,h);e>=t&&(o=3/4*r);const f=s*o,g=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(g)}}({width:s,height:c}),d=yield function({faceDetector:e,videoEl:t,ovalDetails:i,reduceThreshold:n=!1,isMobile:r=!1}){return a.__awaiter(this,void 0,void 0,(function*(){const a=yield e.detectFaces(t);let o,s=!1;switch(a.length){case 0:break;case 1:{o=a[0];const e=i.width,{pupilDistance:t,faceHeight:c}=b(o),l=2;e&&(s=(l*t+1.8*c)/2/l/e<(n?r?.37:.4:.32));break}}return s}))}({faceDetector:o,videoEl:i,ovalDetails:l,reduceThreshold:t,isMobile:r});return{isFaceFarEnoughBeforeRecording:d}}))},detectInitialFaceAndDrawOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t,livenessStreamProvider:a}=e,{videoEl:i,canvasEl:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.ovalAssociatedParams;try{yield o.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const s=yield o.detectFaces(i);let c,l,d;switch(s.length){case 0:l=C.CANT_IDENTIFY,d=P(i);break;case 1:l=C.FACE_IDENTIFIED,c=s[0];break;default:l=C.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();r?(n.width=window.innerWidth,n.height=window.innerHeight):(n.width=h,n.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const n=null===(i=null===(a=null==e?void 0:e.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.OvalParameters;if(!(n&&n.CenterX&&n.CenterY&&n.Width&&n.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-n.CenterX,centerX:n.CenterX,centerY:n.CenterY,width:n.Width,height:n.Height}}({sessionInformation:t,videoWidth:i.width}),g=k(c,f);return c.top=g.top,c.left=g.left,c.height=g.bottom-g.top,c.width=g.right-g.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:n,centerY:r,width:o,height:s}=t,{width:c,height:l}=e.getBoundingClientRect(),d=e.getContext("2d");if(!d)throw new Error("Cannot find Canvas.");{d.clearRect(0,0,c,l),d.fillStyle="rgba(255, 255, 255, 1.0)",d.fillRect(0,0,c,l);const e={width:i.videoWidth,height:i.videoHeight},t={x:(c-e.width*a)/2,y:(l-e.height*a)/2};d.setTransform(a,0,0,a,t.x,t.y),d.beginPath(),d.ellipse(n,r,o/2,s/2,0,0,2*Math.PI),d.strokeStyle="#AEB3B7",d.lineWidth=3,d.stroke(),d.clip(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c,l)}}({canvas:n,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t}=e,{videoEl:a}=e.videoAssociatedParams,{faceDetector:i,ovalDetails:n,initialFace:r}=e.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=k(r,n),{ovalBoundingBox:u}=I(n),m=O(h,u);switch(o.length){case 0:s=C.CANT_IDENTIFY,l=P(a);break;case 1:{c=o[0];const{faceMatchState:e,faceMatchPercentage:a}=function(e,t,a,i){var n,r;let o;const s=null===(r=null===(n=null==i?void 0:i.Challenge)||void 0===n?void 0:n.FaceMovementAndLightChallenge)||void 0===r?void 0:r.ChallengeConfig;if(!(s&&s.OvalIouThreshold&&s.OvalIouHeightThreshold&&s.OvalIouWidthThreshold&&s.FaceIouHeightThreshold&&s.FaceIouWidthThreshold))throw new Error("Challenge information not returned from session information.");const{OvalIouThreshold:c,OvalIouHeightThreshold:l,OvalIouWidthThreshold:d,FaceIouHeightThreshold:h,FaceIouWidthThreshold:u}=s,m=k(e,t),f=m.left,g=m.right,v=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:T,minOvalY:x,maxOvalX:S,maxOvalY:F}=I(t),R=O(m,E),y=c,M=t.width*d,A=t.height*l,w=t.width*u,D=t.height*h,_=100*Math.max(Math.min(1,.75*(R-a)/(y-a)+.25),0);return o=R>y&&Math.abs(T-f)<M&&Math.abs(S-g)<M&&Math.abs(F-p)<A?C.MATCHED:x-v>D||p-F>D||T-f>w&&g-S>w?C.TOO_CLOSE:C.TOO_FAR,{faceMatchState:o,faceMatchPercentage:_}}(c,n,m,t);s=e,d=a;break}default:s=C.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(e){return a.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:t,freshnessColorDisplay:a}=e.freshnessColorAssociatedParams;if(t)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(e){return a.__awaiter(this,void 0,void 0,(function*(){const{challengeId:t,livenessStreamProvider:a}=e,{videoMediaStream:i}=e.videoAssociatedParams,{initialFace:n,ovalDetails:r}=e.ovalAssociatedParams,{startFace:o,endFace:s}=e.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-n.left-n.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,InitialFace:{InitialFaceDetectedTimestamp:n.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(e){return a.__awaiter(this,void 0,void 0,(function*(){const{livenessStreamProvider:t}=e,{onAnalysisComplete:a}=e.componentProps;t.endStream(),yield a()}))}}}),ae=e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,i,n,r,o;try{const d=yield ee;try{for(var s,c=!0,l=a.__asyncValues(d);!(t=(s=yield l.next()).done);){r=s.value,c=!1;try{const t=r;(null==(o=t)?void 0:o.ServerSessionInformationEvent)?e({type:"SET_SESSION_INFO",data:{sessionInfo:t.ServerSessionInformationEvent.SessionInformation}}):X(t)?e({type:"DISCONNECT_EVENT"}):Z(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ValidationException)}}):K(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.InternalServerException)}}):Q(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ThrottlingException)}}):J(t)&&e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}catch(t){let a=t;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(t)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&e({type:"SERVER_ERROR",data:{error:a}})}})),ie=S.default.createContext(null);function ne(e){var{children:t}=e,i=a.__rest(e,["children"]);return S.default.createElement(ie.Provider,{value:i},t)}function re(){const e=S.default.useContext(ie);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function oe(){const{service:e}=re();return t.useActor(e)}function se(e){const{service:a}=re();return t.useSelector(a,e)}var ce;!function(e){e.CameraModule="amplify-liveness-camera-module",e.CancelContainer="amplify-liveness-cancel-container",e.CancelButton="amplify-liveness-cancel-button",e.CountdownContainer="amplify-liveness-countdown-container",e.DescriptionBullet="amplify-liveness-description-bullet",e.DescriptionBulletIndex="amplify-liveness-description-bullet__index",e.DescriptionBulletIndexText="amplify-liveness-description-bullet__index__text",e.DescriptionBulletMessage="amplify-liveness-description-bullet__message",e.FadeOut="amplify-liveness-fade-out",e.FreshnessCanvas="amplify-liveness-freshness-canvas",e.InstructionList="amplify-liveness-instruction-list",e.InstructionOverlay="amplify-liveness-instruction-overlay",e.Figure="amplify-liveness-figure",e.FigureCaption="amplify-liveness-figure__caption",e.FigureIcon="amplify-liveness-figure__icon",e.FigureImage="amplify-liveness-figure__image",e.Figures="amplify-liveness-figures",e.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.Toast="amplify-liveness-toast",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(ce||(ce={}));const le=({ariaLabel:e})=>{const[t,a]=oe();return t.done?null:S.default.createElement(u.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:ce.CancelButton,"aria-label":e},S.default.createElement(m.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},de=e=>{var{variation:t="default",size:i="medium",children:n}=e,r=a.__rest(e,["variation","size","children"]);return F.createElement(u.View,Object.assign({padding:"small",borderRadius:"medium",className:`${ce.Toast} ${ce.Toast}--${t} ${ce.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},r),F.createElement(u.Flex,{gap:"xs",direction:"column",alignItems:"center"},F.createElement(u.Flex,{className:`${ce.Toast}__message`,textAlign:"center",direction:"column"},n)))},he=e=>{var{children:t,anchorOrigin:i={horizontal:"center",vertical:"center"}}=e,n=a.__rest(e,["children","anchorOrigin"]);return F.createElement(u.Flex,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:i.horizontal,justifyContent:i.vertical,width:"100%",height:"100%",padding:"xl"},n),t)},ue=e=>e.context.errorState,me=e=>e.context.faceMatchAssociatedParams.faceMatchState,fe=e=>e.context.faceMatchAssociatedParams.illuminationState,ge=e=>e.context.isFaceFarEnoughBeforeRecording,ve=e=>e.context.faceMatchStateBeforeStart,pe=({hintDisplayText:e})=>{const[t]=oe(),a=se(ue),i=se(me),n=se(fe),r=se(ve),o=se(ge),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("waitForSessionInfo"),m=t.matches("uploading"),f=t.matches("checkSucceeded"),g=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),p={[C.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[C.FACE_IDENTIFIED]:e.hintTooFarText,[C.TOO_MANY]:e.hintTooManyFacesText,[C.TOO_CLOSE]:e.hintTooCloseText,[C.TOO_FAR]:e.hintTooFarText,[C.MATCHED]:e.hintHoldFaceForFreshnessText},E={[T.BRIGHT]:e.hintIlluminationTooBrightText,[T.DARK]:e.hintIlluminationTooDarkText,[T.NORMAL]:e.hintIlluminationNormalText},x=(()=>{if(!(a||g||f)){if(!l){if(s)return r===C.TOO_MANY?F.createElement(de,null,p[r]):F.createElement(de,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return F.createElement(de,null,e.hintTooCloseText);if(d)return F.createElement(de,null,e.hintHoldFacePositionCountdownText);if(h)return F.createElement(de,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintConnectingText)));if(m)return F.createElement(he,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},F.createElement(de,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintVerifyingText))));if(n&&n!==T.NORMAL)return F.createElement(de,null,E[n])}return v?F.createElement(de,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?F.createElement(de,{size:"large",variation:i===C.TOO_CLOSE?"error":"primary"},i===C.TOO_CLOSE?p[C.TOO_CLOSE]:p[C.TOO_FAR]):null}})();return x||null},Ee=({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,n]=S.default.useState(t);S.default.useEffect((()=>{n(e<0?0:e>100?100:e)}),[e]);const r={"--percentage":`${i}%`};return S.default.createElement("div",{className:ce.MatchIndicator,"data-testid":a},S.default.createElement("div",{className:`${ce.MatchIndicator}__bar`,style:r}))},Te=({children:e})=>S.default.createElement(u.Flex,{className:ce.RecordingIcon},S.default.createElement(u.Flex,{"data-testid":"rec-icon",justifyContent:"center"},S.default.createElement(u.Icon,{viewBox:{width:20,height:20},width:"20",height:"20"},S.default.createElement("circle",{cx:"10",cy:"10",r:"8",fill:"red"}))),S.default.createElement(u.Text,{as:"span",fontWeight:"bold"},e)),Ce=e=>{var{children:t,caption:i,variation:n="default"}=e,r=a.__rest(e,["children","caption","variation"]);return S.default.createElement(u.Flex,Object.assign({as:"figure",className:`${ce.Figure} ${ce.Figure}--${n}`},r),S.default.createElement(u.View,{className:`${ce.FigureImage} ${ce.FigureImage}--${n}`},"success"===n?S.default.createElement("svg",{className:ce.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),S.default.createElement("path",{fill:"#FFF",d:"m9.435 15.62-4.054-4.055L4 12.936l5.435 5.435L21.101 6.704l-1.37-1.371z"}))):null,"error"===n?S.default.createElement("svg",{className:ce.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),S.default.createElement("path",{fill:"#FFF",d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}))):null,t),S.default.createElement(u.View,{as:"figcaption",className:`${ce.FigureCaption} ${ce.FigureCaption}--${n}`},i))},xe=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(0 -.001)"},S.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",d:"M124.655 0c9.173 8.155 9.394 17.812 13.258 32.385l.053.336.108.726.11.796.112.864.114.931.174 1.515.117 1.087.18 1.739.12 1.23.183 1.944.123 1.36.186 2.13.187 2.232.313 3.928.25 3.31.25 3.443.31 4.463.245 3.679.36 5.658.345 5.778.33 5.841.26 4.876.199 3.883.187 3.849.217 4.738.16 3.712.178 4.515.097 2.63v34.977L.519 150 .517 41.97c3-13.353 9.664-29.4 23.841-41.97h100.297Z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",d:"m50.469 18.849.145.153c9.021 9.393 22.62 16.197 36.089 21.996l2.1.897 1.05.443 2.089.876 8.176 3.385 1.979.825 1.944.82c7.782 3.3 14.617 6.491 19.213 10.006 3.57 2.73 5.793 5.645 5.924 8.999v20.474l-.008.624-.016.669-.04 1.089-.04.777-.047.815-.06.853-.068.887-.08.918-.093.95-.104.978-.057.496-.123 1.016-.066.513-.144 1.049-.076.527-.165 1.077c-.057.36-.116.724-.178 1.086l-.193 1.103-.21 1.116-.11.557-.233 1.13c-.12.564-.247 1.13-.38 1.694l-.275 1.14c-1.037 4.147-2.426 8.3-4.271 11.978-6.17 9.34-12.996 16.035-19.28 20.691l-.8.584-.794.562-.784.539-1.165.77-1.147.724-.755.459c-.249.148-.497.294-.74.434l-.73.416-1.078.588-.702.367-1.033.517-.671.321-.657.303-.643.285-.541.23H68.149a75.81 75.81 0 0 1-.81-.284l-.918-.336a75.953 75.953 0 0 1-.935-.355l-.963-.382a85.513 85.513 0 0 1-1.988-.83l-1.032-.455c-.52-.233-1.05-.475-1.585-.727l-1.087-.517-1.113-.547c-.935-.465-1.893-.959-2.873-1.482l-1.193-.644a141.053 141.053 0 0 1-6.297-3.669l-1.33-.83c-17.11-10.783-22.636-33.458-23.66-49.98l-.071-1.267c-.02-.417-.038-.83-.053-1.235l-.037-1.212a86.317 86.317 0 0 1 .042-5.559l.047-1.002.06-.96.064-.843c1.09-2.51 2.164-4.304 3.296-5.882l.408-.558.415-.545.421-.538 2.026-2.492.481-.597.493-.624.507-.656.518-.69a61.722 61.722 0 0 0 3.769-5.754c4.03-6.917 7.127-14.806 9.544-21.668l.566-1.623.802-2.344 2.077-6.175.416-1.205.395-1.109.373-1.007.267-.682.253-.612c.47-.943.8-1.531 1.06-1.876l-.035.047Z"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m94.566 121.353.722.895c-6.828 5.51-14.13 7.462-21.382 6.447-5.417-.758-10.535-3.2-13.987-6.186l-.318-.282.77-.854c3.285 2.964 8.343 5.434 13.694 6.183 6.797.95 13.632-.819 20.089-5.876l.412-.327Z"}),S.default.createElement("ellipse",{cx:"51.331",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M42.539 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.556 1.005c-5.437-3.01-11.946-2.479-16.175-.153l-.262.148-.577-.995Z"}),S.default.createElement("ellipse",{cx:"103.281",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M94.492 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.557 1.005c-5.436-3.01-11.946-2.479-16.174-.153l-.262.148-.577-.995Zm-22.972 32.9c0 4.216 2.006 7.72 5.831 7.48l.232-.018.115 1.144c-4.774.477-7.239-3.571-7.326-8.345l-.003-.26 1.15-.001h.001Z"}),S.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M75.002.001H0v150h150v-150H75.002Zm0 0c25.627 0 46.402 33.579 46.402 75s-20.775 75-46.402 75c-25.627 0-46.402-33.579-46.402-75s20.775-75 46.402-75Z"}),S.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M120.921 75.001c0 20.555-5.214 39.117-13.589 52.507-8.386 13.406-19.838 21.493-32.313 21.493-12.476 0-23.928-8.087-32.312-21.493-8.377-13.39-13.59-31.952-13.59-52.507 0-20.555 5.214-39.116 13.589-52.507C51.091 9.09 62.543 1.001 75.018 1.001c12.476 0 23.928 8.088 32.314 21.493 8.375 13.39 13.588 31.952 13.588 52.507h.001Z"}))),Se=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("defs",null,S.default.createElement("linearGradient",{id:"a",x1:"50%",x2:"50%",y1:"0%",y2:"100%"},S.default.createElement("stop",{offset:"0%",stopColor:"#C2C2C2"}),S.default.createElement("stop",{offset:"100%",stopColor:"#C2C2C2",stopOpacity:"0"}))),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(2)"},S.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M3.997 0h136v150h-136z"}),S.default.createElement("path",{fill:"url(#a)",fillRule:"nonzero",d:"M4.333 0h138v150h-138z"}),S.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m22.515 58.137-1.895 82.434 98.784-2.343c0-8.798.813-16.271.813-31.497 0-15.748-2.345-55.36-3.766-64.125C108.16 11.338 74.737 5.03 56.707 11.04c-28.425 9.475-33.64 35.095-34.192 47.097Z"}),S.default.createElement("path",{fill:"#EF992A",fillRule:"nonzero",d:"M38.104 138.228c8.339-3.98 5.1-1.525 15.916-3.104H90.5c5.448 0 9.541 3.104 28.904 3.104 6.391 0 5.987 8.988-2.473 8.988-24.315 1.08-66.07 1.08-78.281 0-77.975-6.896-10.97-4.014-.546-8.988Z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m54.306 134.26 2.645-21.765h30.498l3.05 21.765c-15.778 14.791-30.703 6.163-36.193 0zm-27.59-54.458C25.42 66.68 33.467 67.18 37.653 69.07l2.837 25.314c-10.328-2.228-13.772-12.961-13.772-14.58zm89.512-.81c4.05-15.067-3.984-15.998-8.506-14.58L105.9 91.75c10.328-8.505 9.113-12.758 10.328-12.758z"}),S.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"M53.564 109.804c-14.195-8.986-16.116-30.658-15.302-40.37 2.24-5.21 4.37-5.723 7.958-11.909 6.3-10.86 9.028-25.451 10.579-25.009 14.241 16.008 50.215 20.259 50.649 31.708v13.023c0 4.178-.911 14.358-4.558 21.65-8.986 13.674-20.131 18.612-24.58 19.372-2.334.922-10.55.521-24.746-8.465Z"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m83.935 98.402.85 1.052c-7.974 6.435-17.2 5.243-23.018.18l-.23-.204.905-1.004c5.273 4.756 13.744 5.998 21.175.227l.318-.251Z"}),S.default.createElement("ellipse",{cx:"56.448",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M50.664 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),S.default.createElement("ellipse",{cx:"89.709",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M83.926 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),S.default.createElement("path",{stroke:"#000",strokeWidth:"1.353",d:"M69.005 82.806c0 1.858.859 5.487 4.287 5.144"}),S.default.createElement("path",{fill:"#FFF",d:"M73.004 0H0v150h146V0H73.004Zm.496 0C98.629 0 119 33.579 119 75s-20.371 75-45.5 75S28 116.421 28 75 48.371 0 73.5 0Z"}),S.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M118.4 75c0 20.555-5.156 39.117-13.441 52.507C96.665 140.913 85.338 149 72.999 149c-12.34 0-23.667-8.087-31.961-21.493C32.753 114.117 27.597 95.555 27.597 75c0-20.555 5.156-39.117 13.44-52.507C49.333 9.087 60.66 1 72.999 1c12.34 0 23.667 8.087 31.961 21.493C113.244 35.883 118.4 54.445 118.4 75Z"}))),Fe=({children:e})=>{const{tokens:t}=u.useTheme(),a=m.useThemeBreakpoint(),[i,n]=F.useState(!1),r=F.useRef(null),o="base"===a;return F.useEffect((()=>{function e(e){i&&r.current&&!r.current.contains(e.target)&&n(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,i]),F.createElement(u.Flex,{position:"relative",onClick:()=>n(!i),ref:r,style:{cursor:"pointer"},testId:"popover-icon"},F.createElement(m.AlertIcon,{ariaHidden:!0,variation:"info"}),i&&F.createElement(F.Fragment,null,F.createElement(u.Flex,{position:"absolute",top:26,left:3,style:{zIndex:3,borderStyle:"solid",borderWidth:"0 9px 9px 9px",borderColor:`transparent transparent ${t.colors.background.primary} transparent`}}),F.createElement(u.Flex,{position:"absolute",top:24,left:2,style:{zIndex:2,borderStyle:"solid",borderWidth:"0 10px 10px 10px",borderColor:`transparent transparent ${t.colors.border.secondary} transparent`}}),F.createElement(u.Flex,{position:"absolute",backgroundColor:`${t.colors.background.primary}`,color:`${t.colors.font.primary}`,direction:"row",fontSize:t.fontSizes.xs,padding:t.space.small,top:33,minWidth:240,left:o?-190:-108,border:`1px solid ${t.colors.border.secondary}`,borderRadius:2,"data-testid":"popover-text"},e)))};Fe.displayName="LivenessIconWithPopover";const Re=({headingText:e,bodyText:t})=>S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.View,{color:"font.primary"},t)),ye=({headingText:e,bodyText:t,infoText:a})=>S.default.createElement(u.Flex,{className:u.ComponentClassNames.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{className:u.ComponentClassNames.AlertHeading},e),S.default.createElement(u.View,{className:u.ComponentClassNames.AlertBody},t)),S.default.createElement(Fe,null,a)),Me=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:n,steps:r})=>S.default.createElement(u.Flex,{direction:"column"},S.default.createElement(u.Text,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.Flex,{className:ce.Figures},S.default.createElement(Ce,{variation:"success",caption:t},S.default.createElement(xe,{title:a})),S.default.createElement(Ce,{variation:"error",caption:i},S.default.createElement(Se,{title:n}))),S.default.createElement(u.Flex,{as:"ol",className:ce.InstructionList},r.map(((e,t)=>S.default.createElement(u.Flex,{as:"li",key:t+1},S.default.createElement(u.Text,{as:"span","aria-hidden":"true"},t+1,"."),S.default.createElement(u.Text,{as:"span"},e)))))),Ae="liveness-detector-start";function we(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(u.Card,{className:Ae,"data-testid":Ae},F.createElement(u.Flex,{direction:"column"},(null==a?void 0:a.Header)?F.createElement(a.Header,null):F.createElement(Re,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?F.createElement(a.PhotosensitiveWarning,null):F.createElement(ye,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?F.createElement(a.Instructions,null):F.createElement(Me,{headingText:i.instructionListHeadingText,goodFitCaptionText:i.goodFitCaptionText,goodFitAltText:i.goodFitAltText,tooFarCaptionText:i.tooFarCaptionText,tooFarAltText:i.tooFarAltText,steps:[i.instructionListStepOneText,i.instructionListStepTwoText,i.instructionListStepThreeText,i.instructionListStepFourText]}),F.createElement(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const De={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fill oval within time limit. Try again and completely fill oval with face within 7 seconds.",faceDistanceHeaderText:"Check failed during countdown",faceDistanceMessageText:"Avoid moving closer during countdown and ensure only one face is in front of camera.",clientHeaderText:"Client error",clientMessageText:"Check failed due to client issue",serverHeaderText:"Server issue",serverMessageText:"Cannot complete check due to server issue",landscapeHeaderText:"Landscape orientation not supported",landscapeMessageText:"Rotate your device to portrait (vertical) orientation.",portraitMessageText:"Ensure your device remains in portrait (vertical) orientation for the check’s duration.",tryAgainText:"Try again"},_e=Object.assign({instructionsHeaderHeadingText:"Liveness check",instructionsHeaderBodyText:"You will go through a face verification process to prove that you are a real person.",instructionsBeginCheckText:"Begin check",photosensitivyWarningHeadingText:"Photosensitivity warning",photosensitivyWarningBodyText:"This check displays colored lights. Use caution if you are photosensitive.",photosensitivyWarningInfoText:"A small percentage of individuals may experience epileptic seizures when exposed to colored lights. Use caution if you, or anyone in your family, have an epileptic condition.",instructionListHeadingText:"Follow the instructions to complete the check:",goodFitCaptionText:"Good fit",goodFitAltText:"Ilustration of a person's face, perfectly fitting inside of an oval.",tooFarCaptionText:"Too far",tooFarAltText:"Illustration of a person's face inside of an oval; there is a gap between the perimeter of the face and the boundaries of the oval.",instructionListStepOneText:"When an oval appears, fill the oval with your face within 7 seconds.",instructionListStepTwoText:"Maximize your screen's brightness.",instructionListStepThreeText:"Make sure your face is not covered with sunglasses or a mask.",instructionListStepFourText:"Move to a well-lit place that is not in direct sunlight.",cameraMinSpecificationsHeadingText:"Camera does not meet minimum specifications",cameraMinSpecificationsMessageText:"Camera must support at least 320*240 resolution and 15 frames per second.",cameraNotFoundHeadingText:"Camera not accessible.",cameraNotFoundMessageText:"Check that camera is connected and camera permissions are enabled in settings before retrying.",retryCameraPermissionsText:"Retry",cancelLivenessCheckText:"Cancel Liveness check",recordingIndicatorText:"Rec",hintMoveFaceFrontOfCameraText:"Move face in front of camera",hintTooManyFacesText:"Ensure only one face is in front of camera",hintFaceDetectedText:"Face detected",hintCanNotIdentifyText:"Move face in front of camera",hintTooCloseText:"Move back",hintTooFarText:"Move closer",hintHoldFacePositionCountdownText:"Hold face position during countdown",hintConnectingText:"Connecting...",hintVerifyingText:"Verifying...",hintIlluminationTooBrightText:"Move to dimmer area",hintIlluminationTooDarkText:"Move to brighter area",hintIlluminationNormalText:"Lighting conditions normal",hintHoldFaceForFreshnessText:"Hold still"},De),Ie=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},De),t);return e===x.CAMERA_ACCESS_ERROR||e===x.CAMERA_FRAMERATE_ERROR||e===x.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:n,faceDistanceHeaderText:r,faceDistanceMessageText:o,clientHeaderText:s,clientMessageText:c,serverHeaderText:l,serverMessageText:d}=a;let h,f;switch(t){case x.TIMEOUT:h=i,f=n;break;case x.FACE_DISTANCE_ERROR:h=r,f=o;break;case x.RUNTIME_ERROR:h=s,f=c;break;case x.SERVER_ERROR:default:h=l,f=d}return S.default.createElement(S.default.Fragment,null,S.default.createElement(u.Flex,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},S.default.createElement(m.AlertIcon,{ariaHidden:!0,variation:"error"}),S.default.createElement(u.Text,{fontWeight:"bold"},h)),f)})({error:e,displayText:a})},Oe=e=>{const{children:t,onRetry:a,displayText:i}=e,n=Object.assign(Object.assign({},De),i),{tryAgainText:r}=n;return S.default.createElement(he,{backgroundColor:"overlay.40"},S.default.createElement(de,null,t,S.default.createElement(u.Flex,{justifyContent:"center"},S.default.createElement(u.Button,{variation:"primary",type:"button",onClick:a},r))))},be=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},ke=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},Pe=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,Le=e=>e.context.faceMatchAssociatedParams.faceMatchState,Ne=S.default.createElement(u.Loader,{size:"large",className:ce.Loader,"data-testid":"centered-loader"}),Be=t=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:n,hintDisplayText:r,errorDisplayText:o,components:s,testId:c}=t,{cancelLivenessCheckText:l,recordingIndicatorText:d}=n,{ErrorView:h=Oe}=null!=s?s:{},{tokens:m}=u.useTheme(),[g,v]=oe(),p=se(ke),E=se(be),T=se(Pe),x=se(Le),F=se(ue),R=[C.TOO_FAR,C.CANT_IDENTIFY,C.FACE_IDENTIFIED,C.MATCHED],{videoRef:y,videoWidth:M,videoHeight:D}=function(t,a){const i=a.height.ideal,n=a.width.ideal,r=e.useRef(null),[o,s]=e.useState(i),[c,l]=e.useState(n);return e.useEffect((()=>{if(t){f.isObject(r.current)&&(r.current.srcObject=t);const{height:e,width:a}=t.getTracks()[0].getSettings();s(e),l(a)}return()=>{t&&t.getTracks().forEach((e=>{t.removeTrack(e),e.stop()}))}}),[t]),{videoRef:r,videoHeight:o,videoWidth:c}}(p,E),_=e.useRef(null),I=e.useRef(null),[O,b]=e.useState(!1),[k,P]=e.useState(!1),L=g.matches("cameraCheck"),N=g.matches("notRecording"),B=g.matches("recording"),H=g.matches("checkSucceeded"),V=g.matches({recording:"flashFreshnessColors"}),[W,j]=e.useState(M),[z,q]=e.useState(D),[U,Y]=e.useState((()=>M&&D?M/D:0));S.default.useLayoutEffect((()=>{k&&v({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:y.current,canvasEl:_.current,freshnessColorEl:I.current,isMobile:a}}),y.current&&(j(y.current.videoWidth),q(y.current.videoHeight),Y(y.current.videoWidth/y.current.videoHeight))}),[v,y,k,a]);return L?S.default.createElement(u.Flex,{height:D,width:"100%",position:"relative"},Ne):S.default.createElement(u.Flex,{className:w.default(ce.CameraModule,a&&`${ce.CameraModule}--mobile`),"data-testid":c},!k&&Ne,S.default.createElement(u.View,{as:"canvas",ref:I,className:ce.FreshnessCanvas,hidden:!0}),S.default.createElement(u.View,{className:ce.VideoAnchor,style:{aspectRatio:`${U}`}},S.default.createElement("video",{ref:y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:W,height:z,onCanPlay:()=>{P(!0),b(!0)},"data-testid":"video",className:ce.Video}),S.default.createElement(u.Flex,{className:w.default(ce.OvalCanvas,a&&`${ce.OvalCanvas}--mobile`,i&&ce.FadeOut)},S.default.createElement(u.View,{as:"canvas",width:"100%",height:"100%",ref:_})),B&&S.default.createElement(u.View,{className:ce.RecordingIconContainer},S.default.createElement(Te,null,d)),!H&&S.default.createElement(u.View,{className:ce.CancelContainer},S.default.createElement(le,{ariaLabel:l})),O&&S.default.createElement(he,{anchorOrigin:{horizontal:"center",vertical:B&&!V?"start":"space-between"},className:ce.InstructionOverlay},S.default.createElement(pe,{hintDisplayText:r}),F&&S.default.createElement(h,{onRetry:()=>{v({type:"CANCEL"})}},Ie({errorState:F,overrideErrorDisplayText:o})),B&&!V&&R.includes(x)?S.default.createElement(Ee,{percentage:T}):null,N&&S.default.createElement(u.View,{className:ce.CountdownContainer,testId:"liveness-camera-countdown-timer"},S.default.createElement(A.default.CountdownCircleTimer,{isPlaying:N,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${m.colors.background.primary}`,onComplete:()=>{v({type:"START_RECORDING"})}},(({remainingTime:e})=>S.default.createElement(u.Text,{fontSize:"xxxl",fontWeight:"bold"},e)))))))};function He(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function Ve(){return window.matchMedia("(orientation: landscape)")}const We=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:n,tryAgainText:r}=e,[o,s]=F.useState(!0);return F.useLayoutEffect((()=>{const e=Ve();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:o?"auto":480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},a),F.createElement(u.Text,null,o?n:i),o?null:F.createElement(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},r)))},je="liveness-detector-check",ze=e=>e.context.errorState,qe=e=>e.context.isRecordingStopped,Ue=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:n})=>{const[r,o]=oe(),s=se(ze),c=se(qe),l=r.matches("permissionDenied"),d=He(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:m,cameraMinSpecificationsMessageText:f,cameraNotFoundHeadingText:g,cameraNotFoundMessageText:v,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;F.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=Ve();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[d,o]);return F.createElement(u.Flex,{direction:"column",position:"relative",testId:je,className:je},(()=>{if(s===x.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},De),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:n,tryAgainText:r}=e;return F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},F.createElement(We,{header:t,portraitMessage:a,landscapeMessage:n,tryAgainText:r,onRetry:()=>{o({type:"CANCEL"})}}))}return l?F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},s===x.CAMERA_FRAMERATE_ERROR?m:g),F.createElement(u.Text,{maxWidth:300},s===x.CAMERA_FRAMERATE_ERROR?f:v),F.createElement(u.Button,{variation:"primary",type:"button",onClick:h},p),F.createElement(u.View,{position:"absolute",top:"medium",right:"medium"},F.createElement(le,{ariaLabel:E}))):F.createElement(Be,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:n})})())};const Ye="liveness-detector";exports.FaceLivenessDetector=function(e){const{disableInstructionScreen:a=!1,components:i,config:n,displayText:r}=e,o=F.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},_e),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x,cancelLivenessCheckText:S,recordingIndicatorText:F,hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v},streamDisplayText:{cancelLivenessCheckText:S,recordingIndicatorText:F},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}}}(r),m=t.useInterpret(te,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=n?n:{}})}}),[f,g]=t.useActor(m),v=f.matches("start")||f.matches("userCancel"),p=F.useCallback((()=>{g({type:"BEGIN",data:{videoConstraints:{width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"}}})}),[g]);return F.useLayoutEffect((()=>{a&&v&&p()}),[p,a,v]),F.createElement(u.View,{className:Ye,testId:Ye},F.createElement(ne,{componentProps:e,service:m},F.createElement(u.Flex,{direction:"column",ref:o},v?F.createElement(we,{beginLivenessCheck:p,components:i,instructionDisplayText:l}):F.createElement(Ue,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:i}))))};
|
package/dist/styles.css
CHANGED
|
@@ -528,16 +528,16 @@
|
|
|
528
528
|
--amplify-components-loader-large-font-size: var(--amplify-font-sizes-small);
|
|
529
529
|
--amplify-components-loader-linear-width: 100%;
|
|
530
530
|
--amplify-components-loader-linear-min-width: 5rem;
|
|
531
|
-
--amplify-components-loader-linear-font-size: var(--amplify-font-sizes-
|
|
532
|
-
--amplify-components-loader-linear-stroke-width: var(--amplify-font-sizes-
|
|
531
|
+
--amplify-components-loader-linear-font-size: var(--amplify-font-sizes-xxs);
|
|
532
|
+
--amplify-components-loader-linear-stroke-width: var(--amplify-font-sizes-xxs);
|
|
533
533
|
--amplify-components-loader-linear-stroke-filled: var(--amplify-colors-brand-primary-80);
|
|
534
534
|
--amplify-components-loader-linear-stroke-empty: var(--amplify-colors-neutral-20);
|
|
535
535
|
--amplify-components-loader-linear-stroke-linecap: round;
|
|
536
536
|
--amplify-components-loader-linear-animation-duration: 1s;
|
|
537
|
-
--amplify-components-loader-linear-small-stroke-width: var(--amplify-font-sizes-
|
|
538
|
-
--amplify-components-loader-linear-small-font-size: var(--amplify-font-sizes-
|
|
539
|
-
--amplify-components-loader-linear-large-stroke-width: var(--amplify-font-sizes-
|
|
540
|
-
--amplify-components-loader-linear-large-font-size: var(--amplify-font-sizes-
|
|
537
|
+
--amplify-components-loader-linear-small-stroke-width: var(--amplify-font-sizes-xxxs);
|
|
538
|
+
--amplify-components-loader-linear-small-font-size: var(--amplify-font-sizes-xxxs);
|
|
539
|
+
--amplify-components-loader-linear-large-stroke-width: var(--amplify-font-sizes-xs);
|
|
540
|
+
--amplify-components-loader-linear-large-font-size: var(--amplify-font-sizes-xs);
|
|
541
541
|
--amplify-components-loader-text-fill: var(--amplify-colors-font-primary);
|
|
542
542
|
--amplify-components-menu-background-color: var(--amplify-colors-background-primary);
|
|
543
543
|
--amplify-components-menu-border-radius: var(--amplify-radii-medium);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const getLivenessUserAgent: () => string;
|
package/dist/types/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "1.0.
|
|
1
|
+
export declare const VERSION = "1.0.5";
|
package/package.json
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aws-amplify/ui-react-liveness",
|
|
3
|
-
"
|
|
4
|
-
"version": "1.0.2",
|
|
3
|
+
"version": "1.0.5",
|
|
5
4
|
"main": "dist/index.js",
|
|
6
5
|
"module": "dist/esm/index.mjs",
|
|
7
6
|
"exports": {
|
|
@@ -49,8 +48,8 @@
|
|
|
49
48
|
"react-dom": ">= 16.14.0"
|
|
50
49
|
},
|
|
51
50
|
"dependencies": {
|
|
52
|
-
"@aws-amplify/ui": "5.6.
|
|
53
|
-
"@aws-amplify/ui-react": "5.0.
|
|
51
|
+
"@aws-amplify/ui": "5.6.6",
|
|
52
|
+
"@aws-amplify/ui-react": "5.0.3",
|
|
54
53
|
"@aws-sdk/client-rekognitionstreaming": "3.348.0",
|
|
55
54
|
"@tensorflow-models/blazeface": "0.0.7",
|
|
56
55
|
"@tensorflow/tfjs-backend-cpu": "3.11.0",
|
|
@@ -100,4 +99,4 @@
|
|
|
100
99
|
"limit": "275 kB"
|
|
101
100
|
}
|
|
102
101
|
]
|
|
103
|
-
}
|
|
102
|
+
}
|