@aws-amplify/ui-react-liveness 1.0.6 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/esm/components/FaceLivenessDetector/FaceLivenessDetector.mjs +1 -1
  2. package/dist/esm/components/FaceLivenessDetector/FaceLivenessDetectorCore.mjs +1 -0
  3. package/dist/esm/components/FaceLivenessDetector/LivenessCheck/LivenessCameraModule.mjs +1 -1
  4. package/dist/esm/components/FaceLivenessDetector/displayText.mjs +1 -1
  5. package/dist/esm/components/FaceLivenessDetector/service/machine/index.mjs +1 -1
  6. package/dist/esm/components/FaceLivenessDetector/service/types/error.mjs +1 -1
  7. package/dist/esm/components/FaceLivenessDetector/service/utils/blazefaceFaceDetection.mjs +1 -1
  8. package/dist/esm/components/FaceLivenessDetector/service/utils/liveness.mjs +1 -1
  9. package/dist/esm/components/FaceLivenessDetector/service/utils/streamProvider.mjs +1 -1
  10. package/dist/esm/components/FaceLivenessDetector/shared/DefaultStartScreenComponents.mjs +1 -1
  11. package/dist/esm/components/FaceLivenessDetector/shared/FaceLivenessErrorModal.mjs +1 -1
  12. package/dist/esm/components/FaceLivenessDetector/shared/Hint.mjs +1 -1
  13. package/dist/esm/components/FaceLivenessDetector/shared/LandscapeErrorModal.mjs +1 -1
  14. package/dist/esm/components/FaceLivenessDetector/shared/LivenessIconWithPopover.mjs +1 -1
  15. package/dist/esm/components/FaceLivenessDetector/shared/Overlay.mjs +1 -1
  16. package/dist/esm/components/FaceLivenessDetector/shared/Toast.mjs +1 -1
  17. package/dist/esm/components/FaceLivenessDetector/types/classNames.mjs +1 -1
  18. package/dist/esm/components/FaceLivenessDetector/utils/getDisplayText.mjs +1 -1
  19. package/dist/esm/index.mjs +1 -1
  20. package/dist/esm/version.mjs +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/styles.css +135 -9
  23. package/dist/types/components/FaceLivenessDetector/FaceLivenessDetector.d.ts +1 -4
  24. package/dist/types/components/FaceLivenessDetector/FaceLivenessDetectorCore.d.ts +11 -0
  25. package/dist/types/components/FaceLivenessDetector/displayText.d.ts +2 -0
  26. package/dist/types/components/FaceLivenessDetector/index.d.ts +2 -0
  27. package/dist/types/components/FaceLivenessDetector/service/types/credentials.d.ts +16 -0
  28. package/dist/types/components/FaceLivenessDetector/service/types/error.d.ts +2 -1
  29. package/dist/types/components/FaceLivenessDetector/service/types/index.d.ts +1 -0
  30. package/dist/types/components/FaceLivenessDetector/service/types/liveness.d.ts +25 -5
  31. package/dist/types/components/FaceLivenessDetector/service/types/machine.d.ts +3 -3
  32. package/dist/types/components/FaceLivenessDetector/service/utils/blazefaceFaceDetection.d.ts +7 -0
  33. package/dist/types/components/FaceLivenessDetector/service/utils/liveness.d.ts +4 -1
  34. package/dist/types/components/FaceLivenessDetector/service/utils/streamProvider.d.ts +10 -1
  35. package/dist/types/components/FaceLivenessDetector/shared/FaceLivenessErrorModal.d.ts +2 -0
  36. package/dist/types/components/FaceLivenessDetector/types/classNames.d.ts +21 -0
  37. package/dist/types/index.d.ts +1 -1
  38. package/dist/types/version.d.ts +1 -1
  39. package/package.json +5 -6
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)}getVideoChunkSize(){return this._chunks.length}_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()} ui-react-liveness/1.0.6`,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,c;const l=(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)||(null===(o=t.data)||void 0===o?void 0:o.message),d=new Error(l);d.name=e.errorState,null===(c=(s=e.componentProps).onError)||void 0===c||c.call(s,d)})),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}}};if(0===a.videoRecorder.getVideoChunkSize())throw new Error("Video chunks not recorded successfully.");a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(e){return a.__awaiter(this,void 0,void 0,(function*(){const{onAnalysisComplete:t}=e.componentProps;yield t()}))}}}),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=({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)),Ee=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))},Te=({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"}))),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("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"}))),xe=({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)))};xe.displayName="LivenessIconWithPopover";const Se=({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)),Fe=({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(xe,null,a)),Re=({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(Ee,{variation:"success",caption:t},S.default.createElement(Te,{title:a})),S.default.createElement(Ee,{variation:"error",caption:i},S.default.createElement(Ce,{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)))))),ye="liveness-detector-start";function Me(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(u.Card,{className:ye,"data-testid":ye},F.createElement(u.Flex,{direction:"column"},(null==a?void 0:a.Header)?F.createElement(a.Header,null):F.createElement(Se,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?F.createElement(a.PhotosensitiveWarning,null):F.createElement(Fe,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?F.createElement(a.Instructions,null):F.createElement(Re,{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 Ae={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"},we=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"},Ae),De=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},Ae),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})},_e=e=>{const{children:t,onRetry:a,displayText:i}=e,n=Object.assign(Object.assign({},Ae),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))))},Ie=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},Oe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},be=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,ke=e=>e.context.faceMatchAssociatedParams.faceMatchState,Pe=S.default.createElement(u.Loader,{size:"large",className:se.Loader,"data-testid":"centered-loader"}),Le=S.default.memo((({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}))})),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=_e}=null!=s?s:{},{tokens:m}=u.useTheme(),[g,v]=re(),p=oe(Oe),E=oe(Ie),T=oe(be),x=oe(ke),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"},Pe):S.default.createElement(u.Flex,{className:w.default(se.CameraModule,a&&`${se.CameraModule}--mobile`),"data-testid":c},!k&&Pe,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(pe,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"})}},De({errorState:F,overrideErrorDisplayText:o})),B&&!V&&R.includes(x)?S.default.createElement(Le,{percentage:Math.ceil(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({},Ae),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({},we),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(Me,{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("tslib"),t=require("react"),a=require("@aws-amplify/core"),i=require("@xstate/react"),r=require("xstate"),n=require("@tensorflow/tfjs-core"),o=require("@tensorflow-models/blazeface"),s=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var 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"),v=require("classnames");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function p(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 E,T,C,S=g(t),F=p(t),x=p(n),y=p(o),R=p(s),M=g(v);class A{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(E||(E={})),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"}(T||(T={})),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",e.MULTIPLE_FACES_ERROR="MULTIPLE_FACES_ERROR"}(C||(C={}));function w(e,t,a){return e*(a-t)+t}function _(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,r=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:r},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:r}}function D(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),r=Math.min(e.right,t.right),n=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,r-a)*Math.max(0,n-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 O({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:r=.5}){const n=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=w(i,c,l),m=w(r,d,h);e>=t&&(o=3/4*n);const f=s*o,v=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(v)}}function I(e){const{leftEye:t,rightEye:a,mouth:i}=e,r=[];r[0]=(t[0]+a[0])/2,r[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(r[0]-i[0],2)+Math.pow(r[1]-i[1],2))}}function b(e,t){const{leftEye:a,rightEye:i,nose:r}=e,{height:n,centerY:o}=t,s=o-n/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=I(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+n)/2?(m=(c[0]+r[0])/2,f=(c[1]+r[1])/2):(m=c[0],f=c[1]);const v=m-h/2,g=f-u/2;return{left:v,top:g,right:v+h,bottom:g+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,r=8,n=new Array(r).fill(0);for(let e=0;e<i.length;e++){n[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<r;e++)n[e]>s&&(s=n[e],o=e);return t.remove(),0===o?E.DARK:o===r?E.BRIGHT:E.NORMAL}throw new Error("Cannot find Video Element.")}C.RUNTIME_ERROR,C.SERVER_ERROR,C.TIMEOUT,C.FACE_DISTANCE_ERROR,C.MULTIPLE_FACES_ERROR,C.CAMERA_FRAMERATE_ERROR,C.CAMERA_ACCESS_ERROR,C.MOBILE_LANDSCAPE_ERROR,C.FRESHNESS_TIMEOUT;function L({ctx:e,prevColor:t,nextColor:a,fraction:i}){const r=e.canvas.width,n=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,r,n*i),1!==i&&(e.fillStyle=t,e.fillRect(0,n*i,r,n*(1-i)))}const k=e=>!!e;function N(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function H({faceDetector:t,videoEl:a,ovalDetails:i,reduceThreshold:r=!1,isMobile:n=!1}){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield t.detectFaces(a);let o,s,c=!1;switch(e.length){case 0:s=C.FACE_DISTANCE_ERROR;break;case 1:{o=e[0];const t=i.width,{pupilDistance:a,faceHeight:l}=I(o),d=2;t&&(c=(d*a+1.8*l)/2/d/t<(r?n?.37:.4:.32),c||(s=C.FACE_DISTANCE_ERROR));break}default:s=C.MULTIPLE_FACES_ERROR}return{isDistanceBelowThreshold:c,error:s}}))}function B({deviceHeight:e,deviceWidth:t,height:a,width:i,top:r,left:n}){return{Height:a/e,Width:i/t,Top:r/e,Left:n/t}}const V=`https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow/tfjs-backend-wasm/${R.version_wasm}/`;class W extends A{constructor(e,t){super(),this.faceModelUrl=null!=t?t:"https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow-models/blazeface/0.0.7/model/model.json",this.binaryPath=null!=e?e:V}loadModels(){return e.__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 x.ready(),this._model=yield a.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(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._model.estimateFaces(t,!1,!0,!0),a=Date.now();return e.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:r,landmarks:n}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=n[0],m=n[1],f=n[2],v=n[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:r[0],rightEye:u,leftEye:m,mouth:v,nose:f}}))}))}_loadWebAssemblyBackend(){return e.__awaiter(this,void 0,void 0,(function*(){try{R.setWasmPaths(this.binaryPath),yield a.jitteredExponentialRetry((()=>e.__awaiter(this,void 0,void 0,(function*(){if(!(yield x.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 e.__awaiter(this,void 0,void 0,(function*(){yield x.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 e.__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)}getVideoChunkSize(){return this._chunks.length}_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({sessionId:e,region:t,stream:a,videoEl:i,credentialProvider:r}){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new j(a),this.credentialProvider=r,this.initPromise=this.init()}getResponseStream(){return e.__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 e.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return e.__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(){var t;return e.__awaiter(this,void 0,void 0,(function*(){const e=null!==(t=this.credentialProvider)&&void 0!==t?t:yield a.Credentials.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:`${a.getAmplifyUserAgent()} ui-react-liveness/2.0.1`,requestHandler:new d.WebSocketFetchHandler({connectionTimeout:1e4})};z&&(i.endpointProvider=()=>({url:new URL(z)})),this._client=new l.RekognitionStreamingClient(i),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(t){const a=this;return this._reader=t.getReader(),function(){return e.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:t,value:i}=yield e.__await(a._reader.read());if(t)return yield e.__await(void 0);if("stopVideo"===i)yield yield e.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const t=yield e.__await(i.arrayBuffer()),a=new Uint8Array(t);a.length>0&&(yield yield e.__await({VideoEvent:{VideoChunk:a,TimestampMillis:Date.now()}}))}else q(i)&&(yield yield e.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}))}}))}}startLivenessVideoConnection(){return e.__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 e.__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:r}=this.context.ovalAssociatedParams,{videoEl:n}=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:r,heightFraction:n,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=r,m=l*o+s,f=d*o+c,v=e.width,g=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,v,g),L({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.save(),p.beginPath(),p.rect(0,0,v,g),p.clip(),p.clearRect(0,0,v,g),p.globalAlpha=.9,L({ctx:p,prevColor:t,nextColor:a,fraction:n}),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,v,g),p.globalAlpha=.75,L({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:n,ovalDetails:i,heightFraction:t,scaleFactor:r}),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:r,challengeId:n}=this.context;r.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:n,ColorDisplayed:{CurrentColor:{RGB:N(t)},PreviousColor:{RGB:N(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=r.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"},RUNTIME_ERROR:{target:"error"},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:"notRecording",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},notRecording:{on:{START_RECORDING:"recording"},initial:"waitForSessionInfo",states:{waitForSessionInfo:{after:{0:{target:"#livenessMachine.recording",cond:"hasServerSessionInfo"},100:{target:"detectFaceDistanceDuringLoading"}}},detectFaceDistanceDuringLoading:{invoke:{src:"detectFaceDistanceWhileLoading",onDone:{target:"checkFaceDistanceDuringLoading",actions:["updateFaceDistanceWhileLoading"]}}},checkFaceDistanceDuringLoading:{always:[{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},{target:"waitForSessionInfo"}]},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:r.assign({responseStreamActorRef:()=>r.spawn(te)}),updateFailedAttempts:r.assign({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:r.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:r.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:r.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,r=new W(i,a);return r.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:r})}}),updateLivenessStreamProvider:r.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:r.assign({videoAssociatedParams:(e,t)=>{var a,i,r;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===(r=t.data)||void 0===r?void 0:r.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:r.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:r}=e,{recordingStartApiTimestamp:n,recorderStartTimestamp:o}=r.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-n)+n),{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:B({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:r.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:r.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateFaceDistanceWhileLoading:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording,errorState:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.error}}),updateOvalAndFaceDetailsPostDraw:r.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:r.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:r.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:r.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:r.assign({errorState:e=>{}}),updateErrorStateForTimeout:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||C.TIMEOUT}}),updateErrorStateForRuntime:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||C.RUNTIME_ERROR}}),updateErrorStateForServer:r.assign({errorState:e=>C.SERVER_ERROR}),clearErrorState:r.assign({errorState:e=>{}}),updateSessionInfo:r.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:r.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:r.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:r.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,r=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==r&&void 0!==t&&void 0!==a?{color:r,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(k);const i=new $(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:r.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:r.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:r.actions.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:r.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:r.actions.send({type:"TIMEOUT",data:{errorState:C.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:r.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:r.actions.send({type:"RUNTIME_ERROR",data:new Error("Avoid moving closer during countdown and ensure only one face is in front of camera.")},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:r.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:r.assign({errorState:(e,t)=>{var a,i;let r;r=t.data.message.includes("15 fps")?C.CAMERA_FRAMERATE_ERROR:C.CAMERA_ACCESS_ERROR;const n=t.data.message||t.data.Message,o={state:r,error:new Error(n)};return null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),r}}),callMobileLandscapeWarningCallback:r.assign({errorState:e=>C.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;null===(a=(e=t.componentProps).onUserCancel)||void 0===a||a.call(e)})),callUserTimeoutCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;const i=new Error("Client Timeout");i.name=t.errorState;const r={state:t.errorState,error:i};null===(a=(e=t.componentProps).onError)||void 0===a||a.call(e,r)})),callErrorCallback:(t,a)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,i,r;const n={state:t.errorState,error:(null===(e=a.data)||void 0===e?void 0:e.error)||a.data};null===(r=(i=t.componentProps).onError)||void 0===r||r.call(i,n)})),cleanUpResources:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;const{freshnessColorEl:a}=t.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(e=t.livenessStreamProvider)||void 0===e?void 0:e.endStream()})),freezeStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:e,videoEl:a}=t.videoAssociatedParams;t.isRecordingStopped=!0,null==a||a.pause(),null==e||e.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams;t.isRecordingStopped=!0,e.pause()})),resetContext:r.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===T.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===T.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==T.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===T.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===T.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(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:e}=t.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:e,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 r=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(r.length<1)throw new Error("No camera found with more than 15 fps");const n=r[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===n))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},e),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(t){return e.__awaiter(this,void 0,void 0,(function*(){const{config:e}=t.componentProps,{credentialProvider:a}=e,i=new U({sessionId:t.componentProps.sessionId,region:t.componentProps.region,stream:t.videoAssociatedParams.videoMediaStream,videoEl:t.videoAssociatedParams.videoEl,credentialProvider:a});return J=i.getResponseStream(),{livenessStreamProvider:i}}))},detectFace(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoEl:a}=t.videoAssociatedParams,{faceDetector:i}=t.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const r=yield function(t,a){return e.__awaiter(this,void 0,void 0,(function*(){let e;switch((yield t.detectFaces(a)).length){case 0:e=T.CANT_IDENTIFY;break;case 1:e=T.FACE_IDENTIFIED;break;default:e=T.TOO_MANY}return e}))}(i,a);return{faceMatchState:r}}))},detectFaceDistance(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=O({width:o,height:s}),{isDistanceBelowThreshold:l}=yield H({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l}}))},detectFaceDistanceWhileLoading(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=O({width:o,height:s}),{isDistanceBelowThreshold:l,error:d}=yield H({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l,error:d}}))},detectInitialFaceAndDrawOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e,livenessStreamProvider:a}=t,{videoEl:i,canvasEl:r,isMobile:n}=t.videoAssociatedParams,{faceDetector:o}=t.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=T.CANT_IDENTIFY,d=P(i);break;case 1:l=T.FACE_IDENTIFIED,c=s[0];break;default:l=T.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();n?(r.width=window.innerWidth,r.height=window.innerHeight):(r.width=h,r.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const r=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(!(r&&r.CenterX&&r.CenterY&&r.Width&&r.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-r.CenterX,centerX:r.CenterX,centerY:r.CenterY,width:r.Width,height:r.Height}}({sessionInformation:e,videoWidth:i.width}),v=b(c,f);return c.top=v.top,c.left=v.left,c.height=v.bottom-v.top,c.width=v.right-v.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:r,centerY:n,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(r,n,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:r,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e}=t,{videoEl:a}=t.videoAssociatedParams,{faceDetector:i,ovalDetails:r,initialFace:n}=t.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=b(n,r),{ovalBoundingBox:u}=_(r),m=D(h,u);switch(o.length){case 0:s=T.CANT_IDENTIFY,l=P(a);break;case 1:{c=o[0];const{faceMatchState:t,faceMatchPercentage:a}=function(e,t,a,i){var r,n;let o;const s=null===(n=null===(r=null==i?void 0:i.Challenge)||void 0===r?void 0:r.FaceMovementAndLightChallenge)||void 0===n?void 0:n.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=b(e,t),f=m.left,v=m.right,g=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:C,minOvalY:S,maxOvalX:F,maxOvalY:x}=_(t),y=D(m,E),R=c,M=t.width*d,A=t.height*l,w=t.width*u,O=t.height*h,I=100*Math.max(Math.min(1,.75*(y-a)/(R-a)+.25),0);return o=y>R&&Math.abs(C-f)<M&&Math.abs(F-v)<M&&Math.abs(x-p)<A?T.MATCHED:S-g>O||p-x>O||C-f>w&&v-F>w?T.TOO_CLOSE:T.TOO_FAR,{faceMatchState:o,faceMatchPercentage:I}}(c,r,m,e);s=t,d=a;break}default:s=T.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(t){return e.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:e,freshnessColorDisplay:a}=t.freshnessColorAssociatedParams;if(e)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(t){return e.__awaiter(this,void 0,void 0,(function*(){const{challengeId:e,livenessStreamProvider:a}=t,{videoMediaStream:i}=t.videoAssociatedParams,{initialFace:r,ovalDetails:n}=t.ovalAssociatedParams,{startFace:o,endFace:s}=t.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-r.left-r.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:e,InitialFace:{InitialFaceDetectedTimestamp:r.timestampMs,BoundingBox:B({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:B({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.centerY-n.height/2,left:n.centerX-n.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};if(0===a.videoRecorder.getVideoChunkSize())throw new Error("Video chunks not recorded successfully.");a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(t){return e.__awaiter(this,void 0,void 0,(function*(){const{onAnalysisComplete:e}=t.componentProps;yield e()}))}}}),te=t=>e.__awaiter(void 0,void 0,void 0,(function*(){var a,i,r,n,o;try{const d=yield J;try{for(var s,c=!0,l=e.__asyncValues(d);!(a=(s=yield l.next()).done);){n=s.value,c=!1;try{const e=n;(null==(o=e)?void 0:o.ServerSessionInformationEvent)?t({type:"SET_SESSION_INFO",data:{sessionInfo:e.ServerSessionInformationEvent.SessionInformation}}):G(e)?t({type:"DISCONNECT_EVENT"}):X(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ValidationException)}}):Z(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.InternalServerException)}}):K(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ThrottlingException)}}):Q(e)&&t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||a||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(e){let a=e;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(e)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&t({type:"SERVER_ERROR",data:{error:a}})}})),ae=S.default.createContext(null);function ie(t){var{children:a}=t,i=e.__rest(t,["children"]);return S.default.createElement(ae.Provider,{value:i},a)}function re(){const e=S.default.useContext(ae);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function ne(){const{service:e}=re();return i.useActor(e)}function oe(e){const{service:t}=re();return i.useSelector(t,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.ErrorModal="amplify-liveness-error-modal",e.ErrorModalHeading="amplify-liveness-error-modal__heading",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.Hint="amplify-liveness-hint",e.HintText="amplify-liveness-hint__text",e.LandscapeErrorModal="amplify-liveness-landscape-error-modal",e.LandscapeErrorModalButton="amplify-liveness-landscape-error-modal__button",e.LandscapeErrorModalHeader="amplify-liveness-landscape-error-modal__header",e.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.OpaqueOverlay="amplify-liveness-overlay-opaque",e.Overlay="amplify-liveness-overlay",e.Popover="amplify-liveness-popover",e.PopoverContainer="amplify-liveness-popover__container",e.PopoverAnchor="amplify-liveness-popover__anchor",e.PopoverAnchorSecondary="amplify-liveness-popover__anchor-secondary",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.StartScreenHeader="amplify-liveness-start-screen-header",e.StartScreenHeaderBody="amplify-liveness-start-screen-header__body",e.StartScreenHeaderHeading="amplify-liveness-start-screen-header__heading",e.StartScreenWarning="amplify-liveness-start-screen-warning",e.StartScreenInstructions="amplify-liveness-start-screen-instructions",e.StartScreenInstructionsHeading="amplify-liveness-start-screen-instructions__heading",e.Toast="amplify-liveness-toast",e.ToastContainer="amplify-liveness-toast__container",e.ToastMessage="amplify-liveness-toast__message",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(se||(se={}));const ce=({ariaLabel:e})=>{const[t,a]=ne();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=t=>{var{variation:a="default",size:i="medium",children:r}=t,n=e.__rest(t,["variation","size","children"]);return F.createElement(u.View,Object.assign({className:`${se.Toast} ${se.Toast}--${a} ${se.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},n),F.createElement(u.Flex,{className:se.ToastContainer},F.createElement(u.Flex,{className:se.ToastMessage},r)))},de=t=>{var{children:a,anchorOrigin:i={horizontal:"center",vertical:"center"},className:r}=t,n=e.__rest(t,["children","anchorOrigin","className"]);return F.createElement(u.Flex,Object.assign({className:`${se.Overlay} ${r}`,alignItems:i.horizontal,justifyContent:i.vertical},n),a)},he=e=>e.context.errorState,ue=e=>e.context.faceMatchAssociatedParams.faceMatchState,me=e=>e.context.faceMatchAssociatedParams.illuminationState,fe=e=>e.context.isFaceFarEnoughBeforeRecording,ve=e=>e.context.faceMatchStateBeforeStart,ge=({hintDisplayText:e})=>{const[t]=ne(),a=oe(he),i=oe(ue),r=oe(me),n=oe(ve),o=oe(fe),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("uploading"),m=t.matches("checkSucceeded"),f=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),g={[T.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[T.FACE_IDENTIFIED]:e.hintTooFarText,[T.TOO_MANY]:e.hintTooManyFacesText,[T.TOO_CLOSE]:e.hintTooCloseText,[T.TOO_FAR]:e.hintTooFarText,[T.MATCHED]:e.hintHoldFaceForFreshnessText},p={[E.BRIGHT]:e.hintIlluminationTooBrightText,[E.DARK]:e.hintIlluminationTooDarkText,[E.NORMAL]:e.hintIlluminationNormalText},C=(()=>{if(!(a||f||m)){if(!l){if(s)return n===T.TOO_MANY?F.createElement(le,null,g[n]):F.createElement(le,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return F.createElement(le,null,e.hintTooCloseText);if(d)return F.createElement(le,null,F.createElement(u.Flex,{className:se.HintText},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintConnectingText)));if(h)return F.createElement(de,{className:se.OpaqueOverlay,anchorOrigin:{horizontal:"center",vertical:"end"}},F.createElement(le,null,F.createElement(u.Flex,{className:se.HintText},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintVerifyingText))));if(r&&r!==E.NORMAL)return F.createElement(le,null,p[r])}return v?F.createElement(le,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?F.createElement(le,{size:"large",variation:i===T.TOO_CLOSE?"error":"primary"},i===T.TOO_CLOSE?g[T.TOO_CLOSE]:g[T.TOO_FAR]):null}})();return C||null},pe=({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)),Ee=t=>{var{children:a,caption:i,variation:r="default"}=t,n=e.__rest(t,["children","caption","variation"]);return S.default.createElement(u.Flex,Object.assign({as:"figure",className:`${se.Figure} ${se.Figure}--${r}`},n),S.default.createElement(u.View,{className:`${se.FigureImage} ${se.FigureImage}--${r}`},"success"===r?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"===r?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,a),S.default.createElement(u.View,{as:"figcaption",className:`${se.FigureCaption} ${se.FigureCaption}--${r}`},i))},Te=({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"}))),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("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 t=m.useThemeBreakpoint(),[a,i]=F.useState(!1),r=F.useRef(null),n="base"===t;return F.useEffect((()=>{function e(e){a&&r.current&&!r.current.contains(e.target)&&i(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,a]),F.createElement(u.Flex,{className:se.Popover,onClick:()=>i(!a),ref:r,testId:"popover-icon"},F.createElement(m.AlertIcon,{ariaHidden:!0,variation:"info"}),a&&F.createElement(F.Fragment,null,F.createElement(u.Flex,{className:se.PopoverAnchor}),F.createElement(u.Flex,{className:se.PopoverAnchorSecondary}),F.createElement(u.Flex,{className:se.PopoverContainer,left:n?-190:-108,"data-testid":"popover-text"},e)))};Se.displayName="LivenessIconWithPopover";const Fe=({headingText:e,bodyText:t})=>S.default.createElement(u.View,{className:se.StartScreenHeader},S.default.createElement(u.View,{className:se.StartScreenHeaderHeading},e),S.default.createElement(u.View,{className:se.StartScreenHeaderBody},t)),xe=({headingText:e,bodyText:t,infoText:a})=>S.default.createElement(u.Flex,{className:`${u.ComponentClassNames.Alert} ${se.StartScreenWarning}`},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:r,steps:n})=>S.default.createElement(u.Flex,{direction:"column"},S.default.createElement(u.Text,{className:se.StartScreenInstructionsHeading},e),S.default.createElement(u.Flex,{className:se.Figures},S.default.createElement(Ee,{variation:"success",caption:t},S.default.createElement(Te,{title:a})),S.default.createElement(Ee,{variation:"error",caption:i},S.default.createElement(Ce,{title:r}))),S.default.createElement(u.Flex,{as:"ol",className:se.InstructionList},n.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)))))),Re="liveness-detector-start";function Me(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(u.Card,{className:Re,"data-testid":Re},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(xe,{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 Ae={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fill oval within time limit. Try again and completely fill oval with face within 7 seconds.",faceDistanceHeaderText:"Forward movement detected",faceDistanceMessageText:"Avoid moving closer when connecting.",multipleFacesHeaderText:"Multiple faces detected",multipleFacesMessageText:"Ensure only one face is present in front of the camera when connecting.",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"},we=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"},Ae),_e=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},Ae),t);return e===C.CAMERA_ACCESS_ERROR||e===C.CAMERA_FRAMERATE_ERROR||e===C.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:r,faceDistanceHeaderText:n,faceDistanceMessageText:o,multipleFacesHeaderText:s,multipleFacesMessageText:c,clientHeaderText:l,clientMessageText:d,serverHeaderText:h,serverMessageText:f}=a;let v,g;switch(t){case C.TIMEOUT:v=i,g=r;break;case C.FACE_DISTANCE_ERROR:v=n,g=o;break;case C.MULTIPLE_FACES_ERROR:v=s,g=c;break;case C.RUNTIME_ERROR:v=l,g=d;break;case C.SERVER_ERROR:default:v=h,g=f}return S.default.createElement(S.default.Fragment,null,S.default.createElement(u.Flex,{className:se.ErrorModal},S.default.createElement(m.AlertIcon,{ariaHidden:!0,variation:"error"}),S.default.createElement(u.Text,{className:se.ErrorModalHeading},v)),g)})({error:e,displayText:a})},De=e=>{const{children:t,onRetry:a,displayText:i}=e,r=Object.assign(Object.assign({},Ae),i),{tryAgainText:n}=r;return S.default.createElement(de,{className:se.OpaqueOverlay},S.default.createElement(le,null,t,S.default.createElement(u.Flex,{justifyContent:"center"},S.default.createElement(u.Button,{variation:"primary",type:"button",onClick:a},n))))},Oe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},Ie=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},be=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"}),ke=S.default.memo((({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,r]=S.default.useState(t);S.default.useEffect((()=>{r(e<0?0:e>100?100:e)}),[e]);const n={"--percentage":`${i}%`};return S.default.createElement("div",{className:se.MatchIndicator,"data-testid":a},S.default.createElement("div",{className:`${se.MatchIndicator}__bar`,style:n}))})),Ne=e=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:r,hintDisplayText:n,errorDisplayText:o,components:s,testId:c}=e,{cancelLivenessCheckText:l,recordingIndicatorText:d}=r,{ErrorView:h=De}=null!=s?s:{},[m,v]=ne(),g=oe(Ie),p=oe(Oe),E=oe(be),C=oe(Pe),F=oe(he),x=[T.TOO_FAR,T.CANT_IDENTIFY,T.FACE_IDENTIFIED,T.MATCHED],{videoRef:y,videoWidth:R,videoHeight:A}=function(e,a){const i=a.height.ideal,r=a.width.ideal,n=t.useRef(null),[o,s]=t.useState(i),[c,l]=t.useState(r);return t.useEffect((()=>{if(e){f.isObject(n.current)&&(n.current.srcObject=e);const{height:t,width:a}=e.getTracks()[0].getSettings();s(t),l(a)}return()=>{e&&e.getTracks().forEach((t=>{e.removeTrack(t),t.stop()}))}}),[e]),{videoRef:n,videoHeight:o,videoWidth:c}}(g,p),w=t.useRef(null),_=t.useRef(null),[D,O]=t.useState(!1),I=m.matches("cameraCheck"),b=m.matches("recording"),P=m.matches("checkSucceeded"),L=m.matches({recording:"flashFreshnessColors"}),[k,N]=t.useState(R),[H,B]=t.useState(A),[V,W]=t.useState((()=>R&&A?R/A:0));S.default.useLayoutEffect((()=>{D&&v({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:y.current,canvasEl:w.current,freshnessColorEl:_.current,isMobile:a}}),y.current&&(N(y.current.videoWidth),B(y.current.videoHeight),W(y.current.videoWidth/y.current.videoHeight))}),[v,y,D,a]);return I?S.default.createElement(u.Flex,{height:A,width:"100%",position:"relative"},Le):S.default.createElement(u.Flex,{className:M.default(se.CameraModule,a&&`${se.CameraModule}--mobile`),"data-testid":c},!D&&Le,S.default.createElement(u.View,{as:"canvas",ref:_,className:se.FreshnessCanvas,hidden:!0}),S.default.createElement(u.View,{className:se.VideoAnchor,style:{aspectRatio:`${V}`}},S.default.createElement("video",{ref:y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:k,height:H,onCanPlay:()=>{O(!0)},"data-testid":"video",className:se.Video}),S.default.createElement(u.Flex,{className:M.default(se.OvalCanvas,a&&`${se.OvalCanvas}--mobile`,i&&se.FadeOut)},S.default.createElement(u.View,{as:"canvas",width:"100%",height:"100%",ref:w})),b&&S.default.createElement(u.View,{className:se.RecordingIconContainer},S.default.createElement(pe,null,d)),!P&&S.default.createElement(u.View,{className:se.CancelContainer},S.default.createElement(ce,{ariaLabel:l})),S.default.createElement(de,{anchorOrigin:{horizontal:"center",vertical:b&&!L?"start":"space-between"},className:se.InstructionOverlay},S.default.createElement(ge,{hintDisplayText:n}),F&&S.default.createElement(h,{onRetry:()=>{v({type:"CANCEL"})}},_e({errorState:F,overrideErrorDisplayText:o})),b&&!L&&x.includes(C)?S.default.createElement(ke,{percentage:Math.ceil(E)}):null)))};function He(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function Be(){return window.matchMedia("(orientation: landscape)")}const Ve=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:r,tryAgainText:n}=e,[o,s]=F.useState(!0);return F.useLayoutEffect((()=>{const e=Be();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),F.createElement(u.Flex,{className:se.LandscapeErrorModal,height:o?"auto":480},F.createElement(u.Text,{className:se.LandscapeErrorModalHeader},a),F.createElement(u.Text,null,o?r:i),o?null:F.createElement(u.Flex,{className:se.LandscapeErrorModalButton},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},n)))},We="liveness-detector-check",je=e=>e.context.errorState,ze=e=>e.context.isRecordingStopped,qe=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:r})=>{const[n,o]=ne(),s=oe(je),c=oe(ze),l=n.matches("permissionDenied"),d=He(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:m,cameraMinSpecificationsMessageText:f,cameraNotFoundHeadingText:v,cameraNotFoundMessageText:g,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;F.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=Be();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===C.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},Ae),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:r,tryAgainText:n}=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:r,tryAgainText:n,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===C.CAMERA_FRAMERATE_ERROR?m:v),F.createElement(u.Text,{maxWidth:300},s===C.CAMERA_FRAMERATE_ERROR?f:g),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:r})})())};const Ue="liveness-detector";function Ye(e){const{disableInstructionScreen:t=!1,components:a,config:r,displayText:n}=e,o=F.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},we),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S,cancelLivenessCheckText:F,recordingIndicatorText:x,hintMoveFaceFrontOfCameraText:y,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:O,hintVerifyingText:I,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:L,hintHoldFaceForFreshnessText:k,timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:V,multipleFacesHeaderText:W,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:q,serverHeaderText:U,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:y,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:O,hintVerifyingText:I,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:L,hintHoldFaceForFreshnessText:k},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g},streamDisplayText:{cancelLivenessCheckText:F,recordingIndicatorText:x},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:V,multipleFacesHeaderText:W,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:q,serverHeaderText:U,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}}}(n),m=i.useInterpret(ee,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=r?r:{}})}}),[f,v]=i.useActor(m),g=f.matches("start")||f.matches("userCancel"),p=F.useCallback((()=>{v({type:"BEGIN",data:{videoConstraints:{width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"}}})}),[v]);return F.useLayoutEffect((()=>{t&&g&&p()}),[p,t,g]),F.createElement(u.View,{className:Ue,testId:Ue},F.createElement(ie,{componentProps:e,service:m},F.createElement(u.Flex,{direction:"column",ref:o},g?F.createElement(Me,{beginLivenessCheck:p,components:a,instructionDisplayText:l}):F.createElement(qe,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:a}))))}const $e=()=>e.__awaiter(void 0,void 0,void 0,(function*(){return yield a.Credentials.get()}));exports.FaceLivenessDetector=function(t){const{config:a}=t,i=e.__rest(t,["config"]);return F.createElement(Ye,Object.assign({},i,{config:Object.assign({credentialProvider:$e},a)}))},exports.FaceLivenessDetectorCore=Ye;
package/dist/styles.css CHANGED
@@ -397,6 +397,7 @@
397
397
  --amplify-components-fieldcontrol-disabled-border-color: var(--amplify-colors-transparent);
398
398
  --amplify-components-fieldcontrol-disabled-background-color: var(--amplify-colors-background-disabled);
399
399
  --amplify-components-fieldcontrol-error-border-color: var(--amplify-colors-border-error);
400
+ --amplify-components-fieldcontrol-error-color: var(--amplify-colors-font-error);
400
401
  --amplify-components-fieldcontrol-error-focus-box-shadow: 0px 0px 0px 1px var(--amplify-colors-border-error);
401
402
  --amplify-components-fieldgroup-gap: var(--amplify-space-zero);
402
403
  --amplify-components-fieldgroup-vertical-align-items: center;
@@ -806,7 +807,9 @@
806
807
  --amplify-components-switchfield-small-font-size: var(--amplify-font-sizes-small);
807
808
  --amplify-components-switchfield-label-padding: var(--amplify-space-xs);
808
809
  --amplify-components-switchfield-thumb-background-color: var(--amplify-colors-background-primary);
809
- --amplify-components-switchfield-thumb-border-color: var(--amplify-colors-border-tertiary);
810
+ --amplify-components-switchfield-thumb-border-color: transparent;
811
+ --amplify-components-switchfield-thumb-border-width: var(--amplify-border-widths-small);
812
+ --amplify-components-switchfield-thumb-border-style: solid;
810
813
  --amplify-components-switchfield-thumb-border-radius: var(--amplify-radii-xxxl);
811
814
  --amplify-components-switchfield-thumb-checked-transform: var(--amplify-transforms-slide-x-medium);
812
815
  --amplify-components-switchfield-thumb-transition-duration: var(--amplify-time-medium);
@@ -1221,14 +1224,6 @@ select {
1221
1224
  display: block;
1222
1225
  overflow: auto;
1223
1226
  }
1224
- .amplify-scrollview--horizontal {
1225
- overflow-x: scroll;
1226
- overflow-y: initial;
1227
- }
1228
- .amplify-scrollview--vertical {
1229
- overflow-x: initial;
1230
- overflow-y: scroll;
1231
- }
1232
1227
 
1233
1228
  .amplify-text {
1234
1229
  display: block;
@@ -2893,10 +2888,14 @@ html[dir=rtl] .amplify-field-group__inner-start {
2893
2888
 
2894
2889
  .amplify-liveness-toast {
2895
2890
  background-color: var(--amplify-colors-background-primary);
2891
+ padding: var(--amplify-space-small);
2892
+ border-radius: var(--amplify-radii-medium);
2896
2893
  }
2897
2894
 
2898
2895
  .amplify-liveness-toast__message {
2899
2896
  color: var(--amplify-colors-font-primary);
2897
+ text-align: center;
2898
+ flex-direction: column;
2900
2899
  }
2901
2900
 
2902
2901
  .amplify-liveness-toast--large {
@@ -2908,6 +2907,14 @@ html[dir=rtl] .amplify-field-group__inner-start {
2908
2907
  }
2909
2908
  .amplify-liveness-toast--primary .amplify-liveness-toast__message {
2910
2909
  color: var(--amplify-colors-font-inverse);
2910
+ text-align: center;
2911
+ flex-direction: column;
2912
+ }
2913
+
2914
+ .amplify-liveness-toast__container {
2915
+ gap: var(--amplify-space-xs);
2916
+ flex-direction: column;
2917
+ align-items: center;
2911
2918
  }
2912
2919
 
2913
2920
  .amplify-liveness-toast--error {
@@ -3023,6 +3030,117 @@ html[dir=rtl] .amplify-field-group__inner-start {
3023
3030
  top: 0;
3024
3031
  }
3025
3032
 
3033
+ .amplify-liveness-landscape-error-modal {
3034
+ background-color: var(--amplify-colors-background-primary);
3035
+ direction: column;
3036
+ text-align: center;
3037
+ align-items: center;
3038
+ justify-content: center;
3039
+ width: 100%;
3040
+ }
3041
+
3042
+ .amplify-liveness-landscape-error-modal__header {
3043
+ font-size: large;
3044
+ font-weight: var(--amplify-font-weights-bold);
3045
+ }
3046
+
3047
+ .amplify-liveness-landscape-error-modal__button {
3048
+ justify-content: center;
3049
+ }
3050
+
3051
+ .amplify-liveness-start-screen-header {
3052
+ display: flex;
3053
+ flex-direction: column;
3054
+ }
3055
+
3056
+ .amplify-liveness-start-screen-header__heading {
3057
+ color: var(--amplify-colors-font-primary);
3058
+ font-weight: var(--amplify-font-weights-bold);
3059
+ }
3060
+
3061
+ .amplify-liveness-start-screen-header__body {
3062
+ color: var(--amplify-colors-font-primary);
3063
+ }
3064
+
3065
+ .amplify-liveness-start-screen-warning {
3066
+ color: var(--amplify-colors-orange-80);
3067
+ background-color: var(--amplify-colors-orange-20);
3068
+ align-items: center;
3069
+ }
3070
+
3071
+ .amplify-liveness-start-screen-instructions__heading {
3072
+ color: var(--amplify-colors-font-primary);
3073
+ font-weight: var(--amplify-font-weights-bold);
3074
+ }
3075
+
3076
+ .amplify-liveness-overlay-opaque {
3077
+ background-color: var(--amplify-colors-overlay-40);
3078
+ }
3079
+
3080
+ .amplify-liveness-overlay {
3081
+ flex-direction: column;
3082
+ position: absolute;
3083
+ left: 0;
3084
+ top: 0;
3085
+ width: 100%;
3086
+ height: 100%;
3087
+ padding: var(--amplify-space-xl);
3088
+ }
3089
+
3090
+ .amplify-liveness-error-modal {
3091
+ gap: var(--amplify-space-xs);
3092
+ align-items: center;
3093
+ justify-content: center;
3094
+ color: var(--amplify-colors-font-error);
3095
+ }
3096
+
3097
+ .amplify-liveness-error-modal__heading {
3098
+ font-weight: var(--amplify-font-weights-bold);
3099
+ }
3100
+
3101
+ .amplify-liveness-hint__text {
3102
+ align-items: center;
3103
+ gap: var(--amplify-space-xs);
3104
+ }
3105
+
3106
+ .amplify-liveness-popover {
3107
+ position: relative;
3108
+ cursor: pointer;
3109
+ }
3110
+
3111
+ .amplify-liveness-popover__anchor {
3112
+ position: absolute;
3113
+ top: 26px;
3114
+ left: 3px;
3115
+ z-index: 3;
3116
+ border-style: solid;
3117
+ border-width: 0 9px 9px 9px;
3118
+ border-color: transparent transparent var(--amplify-colors-background-primary) transparent;
3119
+ }
3120
+
3121
+ .amplify-liveness-popover__anchor-secondary {
3122
+ position: absolute;
3123
+ top: 24px;
3124
+ left: 2px;
3125
+ z-index: 2;
3126
+ border-style: solid;
3127
+ border-width: 0 10px 10px 10px;
3128
+ border-color: transparent transparent var(--amplify-colors-border-secondary) transparent;
3129
+ }
3130
+
3131
+ .amplify-liveness-popover__container {
3132
+ position: absolute;
3133
+ background-color: var(--amplify-colors-background-primary);
3134
+ color: var(--amplify-colors-font-primary);
3135
+ flex-direction: row;
3136
+ font-size: var(--amplify-font-sizes-xs);
3137
+ padding: var(--amplify-space-small);
3138
+ top: 33px;
3139
+ width: 240px;
3140
+ border: 1px solid var(--amplify-colors-border-secondary);
3141
+ border-radius: 2px;
3142
+ }
3143
+
3026
3144
  .amplify-fileuploader__dropzone {
3027
3145
  background-color: var(--amplify-components-fileuploader-dropzone-background-color);
3028
3146
  border-color: var(--amplify-components-fileuploader-dropzone-border-color);
@@ -3323,6 +3441,11 @@ html[dir=rtl] .amplify-field-group__inner-start {
3323
3441
  );
3324
3442
  }
3325
3443
 
3444
+ .amplify-field__show-password--error {
3445
+ color: var(--amplify-components-fieldcontrol-error-color);
3446
+ border-color: var(--amplify-components-fieldcontrol-error-border-color);
3447
+ }
3448
+
3326
3449
  .amplify-phonenumberfield select:not(:focus) {
3327
3450
  border-right: none;
3328
3451
  }
@@ -3920,6 +4043,7 @@ html[dir=rtl] .amplify-field-group__inner-start {
3920
4043
  .amplify-switchfield {
3921
4044
  display: inline-block;
3922
4045
  font-size: var(--amplify-components-switchfield-font-size);
4046
+ cursor: pointer;
3923
4047
  }
3924
4048
  .amplify-switchfield--small {
3925
4049
  font-size: var(--amplify-components-switchfield-small-font-size);
@@ -3976,6 +4100,8 @@ html[dir=rtl] .amplify-field-group__inner-start {
3976
4100
  border-radius: var(--amplify-components-switchfield-thumb-border-radius);
3977
4101
  width: var(--amplify-components-switchfield-thumb-width);
3978
4102
  height: var(--amplify-components-switchfield-thumb-width);
4103
+ border-width: var(--amplify-components-switchfield-thumb-border-width);
4104
+ border-style: var(--amplify-components-switchfield-thumb-border-style);
3979
4105
  border-color: var(--amplify-components-switchfield-thumb-border-color);
3980
4106
  overflow-wrap: break-word;
3981
4107
  }
@@ -1,12 +1,9 @@
1
1
  /// <reference types="react" />
2
2
  import { FaceLivenessDetectorProps as FaceLivenessDetectorPropsFromUi } from './service';
3
- import { StartScreenComponents } from './shared/DefaultStartScreenComponents';
3
+ import { FaceLivenessDetectorComponents } from './FaceLivenessDetectorCore';
4
4
  import { LivenessDisplayText } from './displayText';
5
- import { CheckScreenComponents } from './shared/FaceLivenessErrorModal';
6
- type FaceLivenessDetectorComponents = StartScreenComponents & CheckScreenComponents;
7
5
  export interface FaceLivenessDetectorProps extends FaceLivenessDetectorPropsFromUi {
8
6
  components?: FaceLivenessDetectorComponents;
9
7
  displayText?: LivenessDisplayText;
10
8
  }
11
9
  export default function FaceLivenessDetector(props: FaceLivenessDetectorProps): JSX.Element;
12
- export {};
@@ -0,0 +1,11 @@
1
+ /// <reference types="react" />
2
+ import { FaceLivenessDetectorCoreProps as FaceLivenessDetectorPropsFromUi } from './service';
3
+ import { StartScreenComponents } from './shared/DefaultStartScreenComponents';
4
+ import { LivenessDisplayText } from './displayText';
5
+ import { CheckScreenComponents } from './shared/FaceLivenessErrorModal';
6
+ export type FaceLivenessDetectorComponents = StartScreenComponents & CheckScreenComponents;
7
+ export interface FaceLivenessDetectorCoreProps extends FaceLivenessDetectorPropsFromUi {
8
+ components?: FaceLivenessDetectorComponents;
9
+ displayText?: LivenessDisplayText;
10
+ }
11
+ export default function FaceLivenessDetectorCore(props: FaceLivenessDetectorCoreProps): JSX.Element;
@@ -46,6 +46,8 @@ export declare const defaultErrorDisplayText: {
46
46
  timeoutMessageText: string;
47
47
  faceDistanceHeaderText: string;
48
48
  faceDistanceMessageText: string;
49
+ multipleFacesHeaderText: string;
50
+ multipleFacesMessageText: string;
49
51
  clientHeaderText: string;
50
52
  clientMessageText: string;
51
53
  serverHeaderText: string;
@@ -1 +1,3 @@
1
1
  export { default as FaceLivenessDetector, FaceLivenessDetectorProps, } from './FaceLivenessDetector';
2
+ export { default as FaceLivenessDetectorCore, FaceLivenessDetectorCoreProps, } from './FaceLivenessDetectorCore';
3
+ export { AwsCredentialProvider, AwsTemporaryCredentials, AwsCredentials, } from './service';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * These types are copied over / adapted from the aws-sdk/types package as they do not semantic versioning and we do not want these changing unexpectedly.
3
+ * When Amplify Auth exports these types this file should be removed and the type definitions should come from the Amplify auth package
4
+ */
5
+ export interface AwsCredentials {
6
+ readonly accessKeyId: string;
7
+ readonly secretAccessKey: string;
8
+ }
9
+ export interface AwsTemporaryCredentials extends AwsCredentials {
10
+ readonly sessionToken?: string;
11
+ readonly expiration?: Date;
12
+ }
13
+ export interface IdentityProvider<IdentityT extends AwsTemporaryCredentials> {
14
+ (identityProperties?: Record<string, any>): Promise<IdentityT>;
15
+ }
16
+ export type AwsCredentialProvider = IdentityProvider<AwsTemporaryCredentials>;