@tsocial/tvweb-sdk
Version:
TV Web SDK - The Standalone SDK
335 lines (319 loc) • 237 kB
JavaScript
import{P as e,r as t,j as r,b as o,e as n,l as a,h as i,i as s,k as l,m as c,n as d,s as u,o as g,q as p,t as m,B as f,v as h,w as k,S as b,x as _,y as C,z as B,A as w,c as y,C as v,D as x,E as P,F as S,G as I,H as R,I as $,J as D,K as M,L as E,M as T,N as j,O as A,Q as L,R as F,T as z,U as O,V as W,W as V,X as N,Y as Q,Z as q,_ as U,$ as X,a0 as H,a1 as K,a2 as Z,a3 as G,a4 as J,a5 as Y,g as ee,p as et,a6 as er,u as eo,a7 as en,a8 as ea,a9 as ei}from"./chunk-554942c8.js";import{W as es,C as el,P as ec,O as ed}from"./chunk-2221afbd.js";import{d as eu,u as eg,a as ep,t as em,b as ef,m as eh,c as ek,D as eb,S as e_}from"./chunk-306b4e50.js";let eC="default",eB="error";function ew({className:e,width:o,height:n,type:a,strokeStyles:i,strokeWidth:s,radius:l,paddingStyle:c,defaultRectStyles:d,errorRectStyles:u,paddingCornerMultiplier:g=1.5}){let p=t.useMemo(()=>({[eC]:d,[eB]:u,...i}),[d,u,i]),m=l+s*g,f=p[a];return r.jsxs("svg",{width:o,height:n,className:e,children:[r.jsx("rect",{x:s/2,y:s/2,rx:l,ry:l,width:o-s,height:n-s,style:f}),r.jsx("path",{d:`M0,${m} Q0,0 ${m},0 L0,0 Z`,style:c}),r.jsx("path",{d:`M0,${n-m} Q0,${n} ${m},${n} L0,${n} Z`,style:c}),r.jsx("path",{d:`M${o-m},${n} Q${o},${n} ${o},${n-m} L${o},${n} Z`,style:c}),r.jsx("path",{d:`M${o-m},0 Q${o},0 ${o},${m} L${o},0 Z`,style:c})]})}ew.propTypes={className:e.string,width:e.number,height:e.number,strokeWidth:e.number,strokeStyles:e.shape({}),type:e.oneOf([eC,eB]),radius:e.number,paddingStyle:e.shape({}),defaultRectStyles:e.shape({}),errorRectStyles:e.shape({}),paddingCornerMultiplier:e.number},ew.defaultProps={className:"",width:eu.IDCapturing.rectangleMask.width,height:eu.IDCapturing.rectangleMask.height,strokeWidth:eu.IDCapturing.rectangleMask.strokeWidth,strokeStyles:eu.IDCapturing.rectangleMask.strokeStyles,type:eC,radius:eu.IDCapturing.rectangleMask.radius,paddingStyle:eu.IDCapturing.rectangleMask.paddingStyle,defaultRectStyles:eu.IDCapturing.rectangleMask.default,errorRectStyles:eu.IDCapturing.rectangleMask.error,paddingCornerMultiplier:1.5};let ey=o.isMobile?200:400,ev=o.isMobile?150:300,ex={ID_CARD:"id_card",QR_CODE:"qr_code"},eP=[{x:.02,y:.03,w:.46,h:.87},{x:.3,y:.03,w:.47,h:.87}],eS="raw",{Errors:eI}=u;async function eR(e,t){let r=i.getOpenCV(),o=e.getContext("2d").getImageData(0,0,e.width,e.height);return await r.fourPointTransform(o,t)}async function e$({canvas:e,paddingPercent:t=.04,glareThreshold:r}={}){let o=e.width,n=e.height,a=Math.floor(o*t),i=Math.floor(n*t),l=o-2*a,c=n-2*i,d=document.createElement("canvas"),u=d.getContext("2d");return d.width=l,d.height=c,u.drawImage(e,a,i,l,c,0,0,l,c),s.isCardGlare(d,r)}async function eD({blazefaceModel:e,predictedIdCardCanvas:t,frontSide:r}){let o=t.width,n=t.height,a=Math.floor(o/3),i=Math.floor(4*n/5),s=document.createElement("canvas"),d=s.getContext("2d");s.width=a,s.height=i,d.drawImage(t,0,Math.floor(n/5),a,i,0,0,a,i);let u=await l.getModelPredictions({model:e,sCanvas:s}),g=e=>e&&"function"==typeof e.arraySync?e.arraySync():e,p=e=>{e&&"function"==typeof e.dispose&&e.dispose()},m=u.map(e=>{let t={topLeft:g(e.topLeft),bottomRight:g(e.bottomRight),probability:g(e.probability),landmarks:g(e.landmarks)};return p(e.topLeft),p(e.bottomRight),p(e.probability),p(e.landmarks),t}).filter(({topLeft:e,bottomRight:t,probability:[r],landmarks:o})=>!(r<.9||o.length<4||.025>c.rectAreaRatio({small:{coords:[e,t]},big:{coords:[[0,0],[l.SIZE,l.SIZE]]}}))&&!0).length;if(r){if(0===m)return eI.id_detector_error_front_side_no_faces;if(m>1)return eI.id_detector_error_front_side_multiple_faces}else if(m>0)return eI.id_detector_error_back_side_has_faces;return null}async function eM({blazefaceModel:e,predictedIdCardCanvas:t,frontSide:r,hasFrontFace:o,hasBackFace:n,genericEnableCheckFrontFace:a,genericEnableCheckBackFace:i}){if(r&&!a||!r&&!i)return null;let{width:s,height:c}=t,d=document.createElement("canvas"),u=document.createElement("canvas");d.width=s/2,u.width=s/2,d.height=c,u.height=c;let g=d.getContext("2d"),p=u.getContext("2d");g.drawImage(t,0,0,s/2,c,0,0,s/2,c),p.drawImage(t,s/2,0,s/2,c,0,0,s/2,c);let m=e=>e&&"function"==typeof e.arraySync?e.arraySync():e,f=e=>{e&&"function"==typeof e.dispose&&e.dispose()},h=e=>{let t={probability:m(e.probability),landmarks:m(e.landmarks)};return f(e.topLeft),f(e.bottomRight),f(e.probability),f(e.landmarks),t},[k,b]=await Promise.all([l.getModelPredictions({model:e,sCanvas:d}),l.getModelPredictions({model:e,sCanvas:u})]),_=k.map(h),C=b.map(h),B=({probability:[e],landmarks:t})=>e>=.9&&t.length>=4,w=_.filter(B),y=C.filter(B),v=w.length>0||y.length>0;if(r){if(!v&&o||v&&!o)return eI.id_detector_error_front_side_no_faces}else if(!v&&n||v&&!n)return eI.id_detector_error_back_side_has_faces;return null}let eE=({canvas:e,cardPosition:t,quality:r=1})=>{if(!t||!t.corners||!Array.isArray(t.corners))return null;let[o,n,i]=t.corners,s=n?.location?.x-o?.location?.x-100,l=i?.location?.y-n?.location?.y-100,c=document.createElement("canvas");c.width=s,c.height=l,c.getContext("2d").drawImage(e,o?.location?.x+50,o?.location?.y+50,s,l,0,0,s,l);let d=c.toDataURL("image/jpeg",r);return a.base64ToMD5({base64:d}).toString()},eT=async({canvas:e,cardPosition:t,quality:r,count:o=3})=>{if(!t||!t.corners||!Array.isArray(t.corners))return[];let n=[];for(;n.length<o;){let a=performance.now(),i=eE({canvas:e,cardPosition:t,quality:r});if(n.push(i),n.length<o){let e=180-(a=Math.floor(performance.now()-a))>0?180-a:0;await new Promise(t=>setTimeout(t,e))}}return n},ej=(e,t)=>{if(null!=e)return parseFloat(e.toFixed(t))},eA=({currentFrameBlurScore:e,incomingFrameBlurScore:t,currentFrameGlareScore:r,incomingFrameGlareScore:o,settings:n,blurLargeThreshold:a,blurSmallThreshold:i})=>{if(null===e)return!0;let{enableBlurCheck:s,enableGlareCheck:l}=n,c=e?.small,d=e?.large,u=t?.small,g=t?.large;return(!s||!(u<i)&&!(g<a))&&(Math.abs(u-c)>Number.EPSILON?u>c:Math.abs(g-d)>Number.EPSILON?g>d:!!(l&&Math.abs(o-r)>Number.EPSILON)&&o>r)};function eL(e,t,r,o,n){r&&(r.strokeStyle=t,r.lineWidth=2,e.forEach(e=>{let[t,a,i,s]=e,l=(t+n.x)*o,c=(a+n.y)*o,d=(i+n.x)*o,u=(s+n.y)*o;r.strokeRect(l,c,d-l,u-c)}))}function eF(e){let t=e.find(e=>"top-left"===e.label).location,r=e.find(e=>"top-right"===e.label).location,o=e.find(e=>"bottom-right"===e.label).location,n=e.find(e=>"bottom-left"===e.label).location,a=Math.sqrt((o.x-n.x)**2+(o.y-n.y)**2),i=Math.sqrt((r.x-t.x)**2+(r.y-t.y)**2),s=Math.max(parseInt(a,10),parseInt(i,10)),l=Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2),c=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2);return{topLeft:t,topRight:r,bottomRight:o,bottomLeft:n,maxWidth:s,maxHeight:Math.max(parseInt(l,10),parseInt(c,10))}}let ez=g(ew)``,eO=g.img`
position: absolute;
top: 0;
left: 0;
/*
* Size the frame with real CSS, not just the width/height HTML attributes.
* Presentational attributes lose to a host's layered author CSS such as
* Tailwind Preflight (@layer base img,video max-width:100% height:auto),
* which would otherwise recompute the PNG height and desync it from the mask.
* styled-components emits unlayered CSS, so this wins the cascade, no !important.
*/
width: ${e=>e.width}px;
height: ${e=>e.height}px;
max-width: none;
`,{animationDuration:eW}=k,eV=g.div`
${p}
${m}
`,eN=g.img`
border-radius: 5px;
opacity: 0.7;
width: ${n("IDCapturing.cardIcon.width")};
height: ${n("IDCapturing.cardIcon.height")};
`,eQ=g.div`
cursor: pointer;
text-align: center;
width: ${n("IDCapturing.captureIcon.width")};
height: ${n("IDCapturing.captureIcon.height")};
img {
width: 100%;
}
z-index: ${f+20};
position: fixed;
${o.isMobile?h`
top: ${e=>e.y};
`:h`
bottom: ${10}px;
`}
${({disabled:e})=>e&&h`
opacity: 0.3;
pointer-events: none;
`}
`,eq=g.div`
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
margin: auto;
width: ${n("IDCapturing.loadingIcon.width")};
height: ${n("IDCapturing.loadingIcon.height")};
img {
width: 100%;
}
z-index: ${f+20};
`,eU=g.div`
color: #fff;
text-align: center;
`,eX=g.div`
transform: translateZ(1000px); // to fix rotating bug on safari
transform-style: preserve-3d;
position: absolute;
top: ${e=>e.y};
z-index: ${f+20};
`,eH=g.div`
display: flex;
align-items: center;
`,eK=g(eU)`
margin-left: 10px;
${({$isFront:e,$isQr:t,theme:r})=>{if(t)return h`
color: ${n("QRStep.title.color")({theme:r})};
font-size: ${n("QRStep.title.fontSize")({theme:r})};
font-weight: ${n("QRStep.title.fontWeight")({theme:r})};
background-color: ${n("QRStep.title.backgroundColor")({theme:r})};
`;let o=e?"Front":"Back";return h`
color: ${n(`IDCapturing.title${o}.color`)({theme:r})};
font-size: ${n(`IDCapturing.title${o}.fontSize`)({theme:r})};
font-weight: ${n(`IDCapturing.title${o}.fontWeight`)({theme:r})};
background-color: ${n(`IDCapturing.title${o}.backgroundColor`)({theme:r})};
`}};
`,eZ=g(eU)`
font-size: 20px;
margin-left: 10px;
color: green;
position: absolute;
left: 0;
top: 10px;
background: white;
z-index: ${f+30};
`,eG=g(eU)`
position: absolute;
text-align: center;
top: ${e=>e.y};
z-index: ${f+20};
padding: ${n("IDCapturing.instruction.padding")};
color: ${n("IDCapturing.instruction.color")};
font-size: ${n("IDCapturing.instruction.fontSize")};
font-weight: ${n("IDCapturing.instruction.fontWeight")};
background-color: ${n("IDCapturing.instruction.backgroundColor")};
border: ${n("IDCapturing.instruction.border")};
border-radius: ${n("IDCapturing.instruction.borderRadius")};
`;g(eG)`
padding: ${n("IDCapturing.error.padding")};
color: ${n("IDCapturing.error.color")};
font-size: ${n("IDCapturing.error.fontSize")};
font-weight: ${n("IDCapturing.error.fontWeight")};
background-color: ${n("IDCapturing.error.backgroundColor")};
border: ${n("IDCapturing.error.border")};
border-radius: ${n("IDCapturing.error.borderRadius")};
`;let eJ=g.div`
position: absolute;
top: ${e=>e.y};
z-index: ${f+20};
display: flex;
align-items: center;
`,eY=g(eU)`
color: ${n("IDCapturing.countdown.color")};
font-size: ${n("IDCapturing.countdown.fontSize")};
font-weight: ${n("IDCapturing.countdown.fontWeight")};
background-color: ${n("IDCapturing.countdown.backgroundColor")};
border: ${n("IDCapturing.countdown.border")};
border-radius: ${n("IDCapturing.countdown.borderRadius")};
margin: 0;
`;g(eY)`
position: absolute;
text-align: center;
padding: 5px 10px;
top: ${e=>e.y};
z-index: ${f+20};
`,g.div`
font-size: 18px;
text-align: center;
padding: 10px;
`;let e3=g.div`
position: fixed;
top: ${e=>e.y};
z-index: ${f+20};
display: flex;
align-items: center;
gap: ${n("IDCapturing.toggle.gap")};
color: ${n("IDCapturing.toggle.color")};
font-size: ${n("IDCapturing.toggle.fontSize")};
font-weight: ${n("IDCapturing.toggle.fontWeight")};
`,e2=e=>{let t,o,{width:a,height:i,type:s,...l}=e,c=_(),u=C.useAsset(`${d(c,"themeVersion")}/id_card_frame.png`),g=C.useAsset(`${d(c,"themeVersion")}/id_card_frame_error.png`),p=(t=e,o=c,{width:t.width??n("IDCapturing.rectangleMask.width")({theme:o}),height:t.height??n("IDCapturing.rectangleMask.height")({theme:o}),strokeWidth:t.strokeWidth??n("IDCapturing.rectangleMask.strokeWidth")({theme:o}),radius:t.radius??n("IDCapturing.rectangleMask.radius")({theme:o}),paddingStyle:t.paddingStyle??n("IDCapturing.rectangleMask.paddingStyle")({theme:o}),defaultRectStyles:t.default??n("IDCapturing.rectangleMask.default")({theme:o}),errorRectStyles:t.error??n("IDCapturing.rectangleMask.error")({theme:o})});return r.jsxs(eV,{width:a,height:i,children:[r.jsx(eO,{src:s===eB?g:u,width:a,height:i}),r.jsx(ez,{type:s,...l,...p})]})},e5=g.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 24px;
position: absolute;
top: ${e=>e.y};
z-index: ${f+20};
`,e0=g.span`
${({$isDone:e})=>{let t=e?"captured":"capturing";return h`
font-size: ${n(`IDCapturing.captureInstruction.${t}.fontSize`)};
color: ${n(`IDCapturing.captureInstruction.${t}.color`)};
font-weight: ${n(`IDCapturing.captureInstruction.${t}.fontWeight`)};
line-height: ${n(`IDCapturing.captureInstruction.${t}.lineHeight`)};
background: ${n(`IDCapturing.captureInstruction.${t}.background`)};
border-radius: ${n(`IDCapturing.captureInstruction.${t}.borderRadius`)};
border: ${n(`IDCapturing.captureInstruction.${t}.border`)};
padding: ${n(`IDCapturing.captureInstruction.${t}.padding`)};
backdrop-filter: blur(28px);
-webkit-backdrop-filter: blur(28px);
text-align: center;
display: inline-block;
`}}
`,e8=g.button`
width: 100%;
max-width: 294px;
height: 66px;
background-color: ${e=>e.theme.tsBlue};
border: 0;
outline: none;
border-radius: 3px;
color: #fff;
font-weight: normal;
cursor: pointer;
font-size: 1rem;
`;g.a`
color: ${e=>e.theme.tsBlue};
cursor: pointer;
`;let e9=g(e8)`
height: ${n("popup.primaryButton.height")};
color: ${n("popup.primaryButton.color")};
font-size: ${n("popup.primaryButton.fontSize")};
font-weight: ${n("popup.primaryButton.fontWeight")};
background-color: ${n("popup.primaryButton.backgroundColor")};
border: ${n("popup.primaryButton.border")};
border-radius: ${n("popup.primaryButton.borderRadius")};
outline: ${n("popup.primaryButton.outline")};
`,e4=g(e8)`
color: ${n("popup.secondaryButton.color")};
font-weight: ${n("popup.secondaryButton.fontWeight")};
font-size: ${n("popup.secondaryButton.fontSize")};
background-color: ${n("popup.secondaryButton.backgroundColor")};
border: ${n("popup.secondaryButton.border")};
border-radius: ${n("popup.secondaryButton.borderRadius")};
outline: ${n("popup.secondaryButton.outline")};
height: ${n("popup.secondaryButton.height")};
`,e1=g.div`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
border-radius: ${n("popup.borderRadius")}; // same border radius as popup
padding: ${n("popup.padding")};
`,e6=g.div`
color: ${n("popup.description.color")};
font-size: ${n("popup.description.fontSize")};
font-weight: ${n("popup.description.fontWeight")};
text-align: ${n("popup.description.textAlign")};
border: ${n("popup.description.border")};
border-radius: ${n("popup.description.borderRadius")};
`,e7=g(e9)`
margin-top: 20px;
width: 100%;
max-width: 160px;
cursor: pointer;
`,te=({onOk:e=()=>{},maxSessionTime:t=30})=>{let o=B();return r.jsxs(e1,{children:[r.jsx(e6,{className:"popup-message",children:o("timeout_instruction",{x:t})}),r.jsx(e7,{className:"popup-button",onClick:e,children:o("btn_ok")})]})},tt=()=>{let[e,r]=t.useState(!1),[o,n]=t.useState(null),[a,i]=t.useState({});return{showPopup:t.useCallback(({popupType:e,props:t={}})=>{i(t),n(e),null===e?r(!1):r(!0)},[]),popupShown:e,popupType:o,props:a}},tr="SESSION_TIMEOUT",to="CONFIRM",tn="QR_INVALID",ta="QR_INSTRUCTIONS",ti={blurScore:{small:void 0,large:void 0},blurVerdict:"clean",facePredictions:[],bboxes:void 0,debugInfo:{blur_small:void 0,blur_large:void 0,blur_verdict:"clean",blur_predict_ms:0,blur_detection_ms:0,blur_flow_type:"generic_front",bbox_calc_ms:0}},ts=e=>"number"==typeof e&&e>0,tl=class{getVideoChunks(){return this._videoChunks}clearVideoChunks(){this._stopDrawing=!0,this._videoChunks=[];try{this._stream instanceof MediaStream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null)}catch(e){console.error("Error stopping stream tracks:",e)}}_handleDataAvailable(e){if(e.data.size>0){let t=new Blob([e.data],{type:"video/mp4"});this._videoChunks.push(t),this._resolveSave&&this._resolveSave()}else console.error("No video data was recorded."),this._rejectSave&&this._rejectSave("No video data recorded.")}_drawToCanvas(e,t,r,o,n,a){if(this._animationFrameId&&cancelAnimationFrame(this._animationFrameId),!e||!a||this._stopDrawing)return;this._lastFrameTime=0;let{cropX:i,cropY:s,cropWidth:l,cropHeight:c}=a,d=1e3/n,u=n=>{if(this._stopDrawing){this._animationFrameId=null;return}n-this._lastFrameTime>=d&&(this._lastFrameTime=n,e.drawImage(t,i,s,l,c,0,0,r,o)),this._animationFrameId=requestAnimationFrame(u)};this._animationFrameId=requestAnimationFrame(u)}stopDrawing(){this._stopDrawing=!0,this._animationFrameId&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}async initiate({videoEl:e,resultAnalyzeVideoAndWindowSizes:t,recordVideoSettings:r}){let n,a;this.clearVideoChunks(),this._stopDrawing=!1;let{videoFrameWidth:i,videoFrameHeight:s,videoBitrate:l,fps:c}=r,d=c||this.DEFAULT_VIDEO_FPS,u=t.cropWidth/t.cropHeight;ts(i)?(n=i,a=i/u):ts(s)?(n=s*u,a=s):(n=400,a=800);let g=document.createElement("canvas");g.width=n,g.height=a;let p=g.getContext("2d");if(!p)return console.error("Could not get canvas context."),{mediaRecorder:null};try{let r={mimeType:"video/webm",videoBitsPerSecond:l},a=o.isIOS?"video/mp4":"video/webm";if(MediaRecorder.isTypeSupported(a)&&(this._stream&&this._stream.getTracks().forEach(e=>e.stop()),this._stopDrawing=!1,this._drawToCanvas(p,e,n,n/u,d,t),this._stream=g.captureStream(),r={mimeType:a,videoBitsPerSecond:Math.min(l,this.MAX_VIDEO_BITRATE)}),!this._stream)throw Error("Failed to create a media stream for recording.");this._mediaRecorder=new MediaRecorder(this._stream,r);let i=()=>new Promise((e,t)=>{if(!this._mediaRecorder)return t("MediaRecorder not initialized");this._resolveSave=e,this._rejectSave=t,this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),"inactive"!==this._mediaRecorder.state&&this._mediaRecorder.stop()}),s=async()=>{this.stopDrawing(),await i()},c=()=>{this.stopDrawing(),this._mediaRecorder&&"inactive"!==this._mediaRecorder.state&&this._mediaRecorder.stop()};return this._mediaRecorder.stopVideoRecording=s,this._mediaRecorder.discardRecording=c,{mediaRecorder:this._mediaRecorder}}catch(e){return console.error("Error setting up video recording:",e),this.clearVideoChunks(),{mediaRecorder:null}}}constructor(){this._videoChunks=[],this._stream=null,this._stopDrawing=!1,this._animationFrameId=null,this._lastFrameTime=0,this.MAX_VIDEO_BITRATE=1e6,this.DEFAULT_VIDEO_FPS=16,this._mediaRecorder=null,this._resolveSave=null,this._rejectSave=null}},tc=({shouldRecord:e})=>{let r=t.useRef(!1),o=t.useMemo(()=>new tl,[]),n=t.useRef(null),a=t.useRef(null),i=t.useCallback(async t=>{if(!r.current&&e)try{let{mediaRecorder:e}=await o.initiate(t);e&&(n.current=e,n.current.start()),r.current=!0,a.current=t}catch(e){console.error("Error starting recording:",e)}},[o,e]),s=t.useCallback(async()=>{if(!r.current||!n.current)return[];if(n.current)try{return await new Promise(e=>setTimeout(e,500)),await n.current.stopVideoRecording(),r.current=!1,o.getVideoChunks()}catch(e){console.error("Error stopping recording:",e)}return[]},[o]),l=t.useCallback(()=>{if(n.current&&r.current)try{o.clearVideoChunks(),n.current=null,r.current=!1}catch(e){console.error("Error resetting recording:",e),r.current=!1}},[o]),c=t.useCallback(()=>{if(n.current&&r.current)try{n.current.discardRecording(),r.current=!1}catch(e){console.error("Error discarding recording:",e),r.current=!1}},[]);return t.useEffect(()=>{let e=()=>{"hidden"===document.visibilityState?c():"visible"===document.visibilityState&&a.current&&i(a.current)};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[i,c]),{startRecording:i,stopRecording:s,resetRecording:l,discardRecording:c}},{Errors:td}=u,tu=()=>({imageBlob:null,takenAt:null,blurScore:null,detectedCard:null}),tg=()=>({imageBlob:null,blurScore:null,error:null,detectedCard:null,captureCount:0,captureDuration:0}),tp=g.label`
position: relative;
display: inline-block;
width: 60px;
height: 32px;
-webkit-tap-highlight-color: transparent;
pointer-events: ${({$disabled:e})=>e?"none":"all"};
opacity: ${({$disabled:e})=>e?.7:1};
input {
opacity: 0;
width: 0;
height: 0;
}
`,tm=g.span`
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: ${n("IDCapturing.toggle.inactive.backgroundColor")};
border-radius: 34px;
&:before {
position: absolute;
content: '';
height: 28px;
width: 28px;
left: 2px;
bottom: 2px;
background-color: ${n("IDCapturing.toggle.backgroundColor")};
border-radius: 50%;
}
input:checked + & {
background-color: ${n("IDCapturing.toggle.active.backgroundColor")};
}
input:checked + &:before {
transform: translateX(28px);
}
`,tf=({checked:e,onChange:t,disabled:o=!1})=>r.jsxs(tp,{$disabled:o,children:[r.jsx("input",{type:"checkbox",checked:e,onChange:t}),r.jsx(tm,{className:"slider"})]}),th=g.button`
position: fixed;
z-index: ${f+10};
left: ${n("IDUploadButton.leftOffset")};
display: inline-flex;
align-items: center;
justify-content: center;
background: ${n("IDUploadButton.background")};
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: ${n("IDUploadButton.border")};
border-radius: ${n("IDUploadButton.borderRadius")};
color: ${n("IDUploadButton.color")};
padding: ${n("IDUploadButton.padding")};
cursor: pointer;
${({$yButtonRow:e,$bottomOffset:t})=>o.isMobile&&null!=e?h`
top: calc(${e}px + (${n("IDCapturing.captureIcon.height")} - ${56}px) / 2);
`:h`
bottom: calc(
${t}px + (${n("IDCapturing.captureIcon.height")} - ${56}px) / 2
);
`}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid ${n("IDUploadButton.focusOutlineColor")};
outline-offset: 2px;
}
`,tk=g.svg`
width: 32px;
height: 32px;
display: block;
`,tb=({onClick:e,label:t,disabled:o=!1,yButtonRow:n,bottomOffset:a})=>r.jsx(th,{type:"button",onClick:e,disabled:o,"aria-label":t,"data-testid":"id-upload-button",$yButtonRow:n,$bottomOffset:a,children:r.jsx(tk,{viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:r.jsx("path",{d:"M7.07684 27.3334C6.40328 27.3334 5.83317 27.1001 5.3665 26.6334C4.89984 26.1668 4.6665 25.5966 4.6665 24.9231V7.0771C4.6665 6.40354 4.89984 5.83343 5.3665 5.36676C5.83317 4.9001 6.40328 4.66676 7.07684 4.66676H16.6665C17.0341 4.66676 17.3153 4.81587 17.5102 5.11409C17.7051 5.41254 17.7418 5.73865 17.6205 6.09243C17.5263 6.44465 17.4592 6.79465 17.4192 7.14243C17.379 7.49021 17.3588 7.84021 17.3588 8.19243C17.3588 10.3891 18.1387 12.2481 19.6985 13.7694C21.2583 15.2908 23.1365 16.0215 25.3332 15.9618C25.4425 15.9618 25.5587 15.9583 25.6818 15.9514C25.8049 15.9445 25.9212 15.9274 26.0305 15.9001C26.3707 15.8641 26.6728 15.9513 26.9368 16.1618C27.2011 16.372 27.3332 16.6403 27.3332 16.9668V24.9231C27.3332 25.5966 27.0998 26.1668 26.6332 26.6334C26.1665 27.1001 25.5964 27.3334 24.9228 27.3334H7.07684ZM10.2052 22.3334H21.8972C22.1383 22.3334 22.3169 22.224 22.4332 22.0051C22.5494 21.7864 22.5314 21.5745 22.3792 21.3694L19.1998 17.1104C19.0749 16.9498 18.9143 16.8694 18.7178 16.8694C18.5212 16.8694 18.3605 16.9498 18.2358 17.1104L14.9742 21.3591L12.7895 18.5591C12.6648 18.4069 12.5063 18.3308 12.3138 18.3308C12.1216 18.3308 11.9631 18.4112 11.8382 18.5721L9.73584 21.3694C9.57517 21.5745 9.55295 21.7864 9.66917 22.0051C9.78539 22.224 9.96406 22.3334 10.2052 22.3334ZM24.4282 12.9051C24.2366 12.7138 24.1408 12.4762 24.1408 12.1924V7.16409L22.3638 8.8821C22.1792 9.06676 21.9506 9.16254 21.6782 9.16943C21.4055 9.1761 21.17 9.08032 20.9715 8.8821C20.7871 8.69743 20.6948 8.46543 20.6948 8.1861C20.6948 7.90654 20.7871 7.67443 20.9715 7.48976L24.2845 4.1771C24.4092 4.05221 24.5429 3.96076 24.6858 3.90276C24.8285 3.84454 24.9802 3.81543 25.1408 3.81543C25.3015 3.81543 25.4511 3.84454 25.5895 3.90276C25.7279 3.96076 25.8596 4.05221 25.9845 4.1771L29.2972 7.48976C29.4818 7.67443 29.5776 7.9031 29.5845 8.17576C29.5912 8.44843 29.4954 8.68387 29.2972 8.8821C29.1125 9.06676 28.8805 9.1591 28.6012 9.1591C28.3216 9.1591 28.0895 9.06676 27.9048 8.8821L26.1408 7.16409V12.1924C26.1408 12.4762 26.0451 12.7138 25.8535 12.9051C25.6622 13.0967 25.4246 13.1924 25.1408 13.1924C24.8571 13.1924 24.6195 13.0967 24.4282 12.9051Z",fill:"currentColor"})})}),t_=(e,t)=>{let r=Math.min(1,1280/Math.max(e,t));return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}},tC=e=>{e.width=0,e.height=0};async function tB({canvas:e,qrModel:t}){let r=e.getContext("2d").getImageData(0,0,e.width,e.height);return await t.detectAndDecode(r)}let tw=(e,t)=>{let{width:r,height:o}=e,n=t.getContext("2d"),a=r/2,i=o/2,{width:s,height:l}=t_(a,i);t.width=s,t.height=l,n.drawImage(e,r/2,0,a,i,0,0,s,l)},ty=(e,t)=>{let{width:r,height:o}=e,n=t.getContext("2d"),{width:a,height:i}=t_(r,o);t.width=a,t.height=i,n.drawImage(e,0,0,a,i)},tv=async({blob:e,outputEncryptionSettings:t,cardSide:r,results:o,readFrom:n})=>{let a,i=await E.writeMergedExif({imageData:{blob:e},enableExifData:!0,additionalData:{qr_string:o[0],type:r===u.IDCardSide.FRONT?"qr_from_front_image":"qr_from_back_image",source:"background QR",qr_read_by:"wechat",qr_read_from:n}});return t?.key&&(a=await T.encrypt({blob:i,key:t.key})),{result:o[0],results:o,validateResult:{valid:!0},image:{blob:i,encrypted:a}}},tx=async({blob:e,outputEncryptionSettings:t,cardSide:r,cardQRConfig:o})=>{let{qrModel:n,noModel:a}=await A();if(a)return null;let{regions:i,isValidPayload:s,pickResults:l,strategy:c}=o,d=document.createElement("canvas");if(!await new Promise(t=>{let r=URL.createObjectURL(e),o=new Image;o.onload=function(){let{width:e,height:n}=t_(o.width,o.height);d.width=e,d.height=n,d.getContext("2d").drawImage(o,0,0,e,n),URL.revokeObjectURL(r),t(!0)},o.onerror=function(){URL.revokeObjectURL(r),t(!1)},o.src=r}))return null;let u=d.getContext("2d"),{width:g,height:p}=d,m="raw"===c?e=>n.detectAndDecodeRaw(e):e=>n.detectAndDecode(e).then(e=>e?[e]:[]),f=await Promise.all(i.map(e=>m((({x:e,y:t,w:r,h:o})=>u.getImageData(Math.round(e*g),Math.round(t*p),Math.round(r*g),Math.round(o*p)))(e))));tC(d);let h=l(f.flat().filter(s));return h&&0!==h.length?tv({blob:e,outputEncryptionSettings:t,cardSide:r,results:h,readFrom:"image"}):null},tP=async(e,t,r=u.IDCardSide.FRONT,o=tw)=>{let{qrModel:n,noModel:a}=await A();if(a)return null;let i=document.createElement("canvas");if(!await new Promise(t=>{let r=URL.createObjectURL(e),n=new Image;n.onload=function(){o(n,i),URL.revokeObjectURL(r),t(!0)},n.onerror=function(){URL.revokeObjectURL(r),t(!1)},n.src=r}))return null;let s=await tB({canvas:i,qrModel:n});return(tC(i),s)?tv({blob:e,outputEncryptionSettings:t,cardSide:r,results:[s],readFrom:"image"}):null},tS=e=>!!e&&("image/png"===e.type||/\.png$/i.test(e.name||"")),tI=async e=>{try{return(await createImageBitmap(e)).close(),!0}catch{return!1}},tR=async(e,t=.92)=>{let r=await createImageBitmap(e),o=document.createElement("canvas");try{o.width=r.width,o.height=r.height;let n=o.getContext("2d");if(!n)throw Error("reEncodeToJpeg: failed to get 2D canvas context");n.fillStyle="#ffffff",n.fillRect(0,0,o.width,o.height),n.drawImage(r,0,0),r.close();let a=await new Promise(e=>{o.toBlob(e,"image/jpeg",t)});if(!a)throw Error("reEncodeToJpeg: canvas.toBlob returned null");let i=`${e.name.replace(/\.[^.]+$/,"")}.jpg`;return new File([a],i,{type:"image/jpeg"})}finally{r.close(),o.width=0,o.height=0}},t$=async({file:e,settings:t,outputEncryptionSettings:r,startTime:o})=>{let n;t?.enableExifData&&(E.addExifData("image_source","upload"),E.addExifData("user_action.start_id_card",o),E.addExifData("user_action.end_id_card",Date.now()),E.addExifData("upload_meta.original_name",e.name),E.addExifData("upload_meta.original_size",e.size),E.addExifData("upload_meta.mime_type",e.type));let a=e;tS(e)&&(a=await tR(e));let i=await E.writeMergedExif({imageData:{blob:a},enableExifData:t?.enableExifData});if(!await tI(i))try{let e=await tR(a);i=await E.writeMergedExif({imageData:{blob:e},enableExifData:t?.enableExifData})}catch(e){console.warn("buildUploadImage: canvas re-encode failed, keeping original blob",e)}return r?.key&&(n=await T.encrypt({blob:i,key:r.key})),{blob:i,encrypted:n,detectedCard:null}},tD=async({blob:e,settings:t,outputEncryptionSettings:r,cardSide:o})=>{if(!t?.enableScanQrViaImage)return null;let n=r??null,a=o??"front";return t?.isVietnameseCardFlow?tP(e,n,a):t?.cardQRConfig?tx({blob:e,outputEncryptionSettings:n,cardSide:a,cardQRConfig:t.cardQRConfig}):tP(e,n,a,ty)},tM="undefined"!=typeof window&&"undefined"!=typeof HTMLInputElement&&"oncancel"in HTMLInputElement.prototype,tE=g.button`
position: fixed;
// Above the scan card alert (BASE_Z_INDEX + 20) so the toast stays readable when the two
// overlap — e.g. a multi-line card alert extending down into a multi-line toast.
z-index: ${f+21};
left: 50%;
max-width: calc(100% - ${n("IDUploadErrorToast.maxWidthInset")});
padding: ${n("IDUploadErrorToast.padding")};
background: ${n("IDUploadErrorToast.background")};
color: ${n("IDUploadErrorToast.color")};
border: none;
border-radius: ${n("IDUploadErrorToast.borderRadius")};
font-size: ${n("IDUploadErrorToast.fontSize")};
line-height: 1.4;
text-align: center;
cursor: pointer;
${({$yButtonRow:e,$bottomOffset:t})=>o.isMobile&&null!=e?h`
top: calc(
${e}px + (${n("IDCapturing.captureIcon.height")} - ${56}px) / 2 -
${16}px
);
transform: translate(-50%, -100%);
`:h`
bottom: calc(
${t}px + (${n("IDCapturing.captureIcon.height")} - ${56}px) / 2 +
${56}px + ${16}px
);
transform: translateX(-50%);
`}
`,tT=({uploadFromDevice:e,uploadFlowAPI:o,scanControl:n,isCaptureInFlight:a,shouldShowSpinner:i,yButtonRow:s,bottomOffset:l})=>{let c=B(),d=!!e?.enable,{inputRef:u,handleUploadClick:g,handleFileChange:p,handleInputCancel:m,isProcessing:f,errorCode:h,dismissError:k}=(({enabled:e,enableConfirmPopup:r,uploadFlowAPI:o,scanControl:n})=>{let a=t.useRef(null),[i,s]=t.useState(!1),[l,c]=t.useState(null),{sendEvent:d}=$.useSDKTracking();t.useEffect(()=>{if(null===l)return;let e=setTimeout(()=>c(null),4e3);return()=>clearTimeout(e)},[l]);let u=t.useCallback(()=>c(null),[]),g=t.useCallback(()=>{e&&!i&&(c(null),d({tag:"id_upload",event:"upload_button_clicked",log:{}}),n.setUploadInProgress(!0),tM&&n.pauseScan(),a.current?.click())},[e,i,d,n]),p=t.useCallback(()=>{d({tag:"id_upload",event:"upload_picker_cancelled",log:{}}),n.resumeScan(),n.setUploadInProgress(!1)},[d,n]);return{inputRef:a,handleUploadClick:g,handleFileChange:t.useCallback(async e=>{let t=e.target?.files?.[0];if(e.target&&(e.target.value=""),t){var a;let e;if(!((e=a=t)&&("image/jpeg"===e.type||/\.jpe?g$/i.test(e.name||""))||tS(a))){d({tag:"id_upload",event:"upload_file_invalid",log:{reason:"wrong_type",mime_type:t.type}}),c("upload_invalid_file_type"),n.pauseScan(),await n.restartSession();return}d({tag:"id_upload",event:"upload_file_selected",log:{size:t.size,mime_type:t.type}}),s(!0),o.setShouldShowSpinner(!0);try{let e=await t$({file:t,settings:o.settings,outputEncryptionSettings:o.outputEncryptionSettings,startTime:Date.now()}),a=await tD({blob:e.blob,settings:o.settings,outputEncryptionSettings:o.outputEncryptionSettings,cardSide:o.stepConfig?.cardSide});if(r){tM||n.pauseScan(),o.commitUploaded({image:e,qrScannedResult:a});let t=a?!!a?.validateResult?.valid:null;o.showPopup({popupType:to,props:{imageTaken:e,hasValidQR:t,error:null}})}else o.commitUploaded({image:e,qrScannedResult:a}),await o.handleStepDone()}catch(e){console.warn("upload flow failed",e),d({tag:"id_upload",event:"upload_processing_failed",log:{error:e instanceof Error?e.message:String(e)}}),o.closePopup(),c("upload_processing_failed"),await n.restartSession()}finally{s(!1),o.setShouldShowSpinner(!1)}}},[r,d,o,n]),handleInputCancel:p,isProcessing:i,supportsInputCancelEvent:tM,errorCode:l,dismissError:u}})({enabled:d,enableConfirmPopup:e?.enableConfirmPopup!==!1,uploadFlowAPI:o,scanControl:n});if(t.useEffect(()=>{let e=u.current;if(e)return e.addEventListener("cancel",m),()=>e.removeEventListener("cancel",m)},[u,m]),!d)return null;let b=c("upload_button_label"),_=h?c(h):"";return r.jsxs(r.Fragment,{children:[h&&r.jsx(tE,{type:"button",onClick:k,"aria-live":"polite","aria-label":_,"data-testid":"id-upload-error-toast",$yButtonRow:s,$bottomOffset:l,children:_}),r.jsx(tb,{onClick:g,label:b,disabled:i||f||a,yButtonRow:s,bottomOffset:l}),r.jsx("input",{ref:u,type:"file",accept:"image/jpeg,image/png",onChange:p,style:{display:"none"},"aria-hidden":"true","data-testid":"id-upload-input"})]})},tj=t.forwardRef((e,a)=>{let{description:s,usePortraitMask:l,windowAndVideoInfo:g,refVideo:p,frontSide:m,allowedCardTypes:f,settings:h,onCaptureDone:k,onUISpacingChange:b,outputEncryptionSettings:C,isShowingSpinner:A,uploadFromDevice:W,uploadFlowAPI:V}=e,N=_(),[Q,q]=t.useState({}),{yMessage:U,yButtonRow:X,yToggleButton:H,yInstruction:K,yCountdown:Z}=Q,G=L("IDCapturing.captureIcon.src","ic_camera.svg"),J=L("IDCapturing.captureIcon.disabled.src","ic_camera.svg"),Y=n("IDCapturing.countdown.color")({theme:N}),ee=L("IDCapturing.loadingIcon.src","ic_loading.gif"),[et,er]=t.useState(""),eo=B(),[en,ea]=t.useState(null),[ei,ed]=t.useState(""),[eu,em]=t.useState(""),[ef,eh]=t.useState(null),{showPopup:ek,popupShown:eb,popupType:e_}=tt(),ew=ep(),[ex,eP]=t.useState(!1),eI=t.useRef(()=>{}),ez=t.useCallback(e=>{if(null===e)ed(""),em("");else{let t=e?.code;em(t||""),ed(eo(t,{side:m?eo("front"):eo("back")}))}},[eo,m]),eO=t.useCallback(()=>{ea(""),eI.current()},[]),eW=t.useCallback((...e)=>{ea(""),k(...e)},[k]),{warmupDone:eV,isPostProcessing:eN,isAutoCapturing:eU,isProcessing:eX,takePictureManually:eH,restartSession:eK,resetIsProcessingImageBlobTaken:e8,isAutoCaptureModeOn:e9,onToggleAutoCaptureMode:e4,autoCaptureDuration:e1,pauseScan:e6,resumeScan:e7,setUploadInProgress:to}=(({shouldStart:e,refVideo:r,cropArea:o,settings:n,onModelErrorChange:a,frontSide:s,onDebugInfoChange:l,onAboutToTimeout:g,onSessionTimeout:p,onCaptureDone:m,outputEncryptionSettings:f,quality:h})=>{let k=t.useRef(!1),b=t.useRef(!1),[_,C]=t.useState(!1),B=t.useRef(()=>{}),{sendEvent:A}=$.useSDKTracking(),L=t.useRef(),F=t.useRef(),z=t.useRef(),O=ep(),{enableAntiDebug:W}=y.useSDKSettings(),{onErrorCallback:V}=eg(),{playVoice:N}=D.useVoicePlayer(),[Q,q]=t.useState(d(n,"enableAutoCapture")),U=t.useCallback(()=>{q(e=>!e)},[]),{autoCaptureWaitForBestImageTimeMs:X,manualCaptureWaitForBestImageTimeMs:H}=n,K=Q?X:H;t.useEffect(()=>{W&&M.enableAntiDebug()},[W]);let Z=t.useCallback(async e=>{A({tag:s?"id_front":"id_back",event:"sdk_ui.auto_capture",log:{}}),C(!1),await B.current(e)},[A,s]),G=t.useCallback((...e)=>{a(...e);let t=d(e,"0.code");t&&t!==L.current&&(A({tag:s?"id_front":"id_back",event:"sdk_ui.show_alert",log:{alert:t}}),L.current=t)},[a,s,A]),J=t.useMemo(()=>Q?n.blurSmallThresholdAuto:n.blurSmallThresholdManual,[Q,n.blurSmallThresholdAuto,n.blurSmallThresholdManual]),Y=t.useMemo(()=>n.enableAutoCapture||Q?n.blurLargeThresholdAuto:n.blurLargeThresholdManual,[Q,n.blurLargeThresholdAuto,n.blurLargeThresholdManual,n.enableAutoCapture]),{isCapturing:ee,refWorkingCanvas:et,stopCheckFrame:er,checkFrame:eo,resumeCheckFrame:en,warmupDone:ea,takePictureManually:ei,refAbleToRunBurstMode:es,refVirtualFrames:el,refCardCoordinates:ec,refBlurScores:ed,refGlareScores:eu,resetState:em,resetRecordVideo:ef,getQRDebugInfo:eh}=function({isAutoCapture:e,blurSmallThreshold:r,blurLargeThreshold:o,refVideo:n,shouldStart:a,cropArea:s,settings:l,onError:g,frontSide:p,onAutoCaptureSuccess:m,quality:f,debug:h}){let k=t.useRef(null);null===k.current&&(k.current=document.createElement("canvas"));let b=t.useRef([]),_=t.useRef({}),C=t.useRef(!1),B=t.useRef([]),R=t.useRef(!1),$=t.useRef(null),[D,M]=t.useState(!1),E=t.useRef(tu()),T=t.useRef(tg()),j=t.useRef(null),A=t.useRef(!1),L=t.useRef(!1),F=t.useRef(null),z=t.useRef(!1),O=t.useRef({}),{customUrls:W}=y.useSDKSettings(),{onErrorCallback:V}=eg(),[N,Q]=t.useState(!0),q=t.useRef([]),U=t.useRef([]),X=t.useRef(e),{allowedCards:H}=l,K=t.useRef(null),[Z,G]=t.useState(!1),J=t.useRef(!1),{scanFrame:Y,reset:ee,getScannedResult:et,getDebugInfo:er}=function({cardQRConfig:e,quality:r}){let o=t.useRef(new Set),n=t.useRef(null),a=t.useRef(!1),s=t.useRef(!1),l=t.useRef(0),c=t.useCallback(()=>{o.current=new Set,n.current=null,a.current=!1,s.current=!1,l.current=0},[]),d=t.useCallback((t,c)=>{if(!e||a.current||s.current)return;a.current=!0,l.current+=1;let{regions:d,isValidPayload:u,strategy:g}=e,p=i.getOpenCV(),{width:m,height:f}=t,h=t.getContext("2d"),k=c.getContext("2d").getImageData(0,0,c.width,c.height),b=g===eS?e=>p.detectAndDecodeRaw(e):e=>p.detectAndDecode(e).then(e=>e?[e]:[]);Promise.all(d.map(e=>b((({x:e,y:t,w:r,h:o})=>h.getImageData(Math.round(e*m),Math.round(t*f),Math.round(r*m),Math.round(o*f)))(e)))).then(t=>{let i=t.flat(),l=o.current.size>0;if(i.forEach(e=>{u(e)&&o.current.add(e)}),!l&&o.current.size>0&&null===n.current){let e=document.createElement("canvas");e.width=k.width,e.height=k.height,e.getContext("2d").putImageData(k,0,0),e.toBlob(e=>{n.current=e},"image/jpeg",r)}!s.current&&e.pickResults([...o.current]).length>0&&(s.current=!0),a.current=!1}).catch(e=>{console.warn("QR scan failed",e),a.current=!1})},[e,r]),u=t.useCallback(()=>{let t=[...o.current];return{results:e?.pickResults?e.pickResults(t):t,imageBlob:n.current}},[e]);return{scanFrame:d,reset:c,getScannedResult:u,getDebugInfo:t.useCallback(()=>({qr_scan_attempts:l.current,qr_found:o.current.size,qr_scan_running:a.current}),[])}}({cardQRConfig:l?.cardQRConfig,quality:f}),{checkBlur:eo,getBlurRuntimeSummary:en}=function({blazefaceModel:e,blurDetector:r}){let o=t.useRef(null),n=t.useRef({totalDetectionMs:0,totalPredictMs:0,totalBboxCalcMs:0,count:0,flowType:"generic_front"}),a=t.useCallback(()=>{let{totalDetectionMs:e,totalPredictMs:t,totalBboxCalcMs:r,count:o,flowType:a}=n.current;return 0===o?{avg_detection_ms:0,avg_predict_ms:0,avg_bbox_calc_ms:0,check_count:0,flow_type:a}:{avg_detection_ms:Math.round(e/o),avg_predict_ms:Math.round(t/o),avg_bbox_calc_ms:Math.round(r/o),check_count:o,flow_type:a}},[]);return{checkBlur:t.useCallback(async({workingCanvas:t,result:a,frontSide:i,blurSmallThreshold:s,blurLargeThreshold:l,isVietnameseCardFlow:c,blurSmallDecimal:g,blurLargeDecimal:p,blurFullFaceImageRatio:m})=>{let f,h;if(!r)return ti;let k=performance.now(),b="generic_back";c?b="vn":i&&(b="generic_front");let _=d(a,"card.label"),C=d(a,"card.corners"),B=[],w=0;if(c)h={canvas:t,cardCorners:C,bboxes:f=_?u.VnCardsBboxes[_]:void 0,smallThreshold:s,largeThreshold:l};else if(i){let r=[],n=performance.now();try{if(e){let{width:n,height:a}=t,i=Math.max(n,a);o.current||(o.current=document.createElement("canvas"));let s=o.current;s.width=i,s.height=i;let l=s.getContext("2d");l.fillStyle="#000",l.fillRect(0,0,i,i),l.drawImage(t,0,0,n,a),B=await e.estimateFaces(s);let c=eF(C);if(B.length>0){let e=B[0],t=function(e,t,r){let{topLeft:o,bottomRight:n}=e,a=n[0]-o[0],i=n[1]-o[1],s=[o[0]-t.left*a,o[1]-t.top*i],l=[n[0]+t.right*a,n[1]+t.bottom*i],{topLeft:c,bottomRight:d}=eF(r);return s[0]=Math.max(s[0],c.x),s[1]=Math.max(s[1],c.y),l[0]=Math.min(l[0],d.x),l[1]=Math.min(l[1],d.y),{portraitTopLeft:s,portraitBottomRight:l}}(e,m,C),o=function(e,t){let{cv:r}=window;if(!r)throw Error("Opencv not found!");let{topLeft:o,topRight:n,bottomRight:a,bottomLeft:i,maxWidth:s,maxHeight:l}=t,{portraitTopLeft:c,portraitBottomRight:d}=e,g=r.matFromArray(4,1,r.CV_32FC2,[o.x,o.y,n.x,n.y,a.x,a.y,i.x,i.y]),p=r.matFromArray(4,1,r.CV_32FC2,[0,0,s-1,0,s-1,l-1,0,l-1]),m=r.getPerspectiveTransform(g,p),f=e=>{let t=r.matFromArray(1,1,r.CV_32FC2,[e[0],e[1]]),o=new r.Mat;r.perspectiveTransform(t,o,m);let n=o.data32F;t.delete(),o.delete();let a=Math.max(0,Math.min(n[0]*(u.RESIZE_IMAGE_WIDTH/s),s));return[a,Math.max(0,Math.min(n[1]*(u.RESIZE_IMAGE_HEIGHT/l),l))]},h=f(c),k=f(d);return g.delete(),p.delete(),m.delete(),[parseInt(h[0],10),parseInt(h[1],10),parseInt(k[0],10),parseInt(k[1],10)]}(t,c);r.push({lapType:"small",bboxes:[o]})}}}catch(e){console.error(e)}w=Math.round(performance.now()-n),h={canvas:t,cardCorners:C,bboxes:[],ignoreBboxes:r,isFront:!0,smallThreshold:s,largeThreshold:l}}else h={canvas:t,cardCorners:C,bboxes:[],ignoreBboxes:[],isFront:!1,smallThreshold:s,largeThreshold:l};let y=performance.now(),[v,x]=await r.predict(h),P=Math.round(performance.now()-y),S=Math.round(performance.now()-k),I={small:ej(x?.[0],g),large:ej(x?.[1],p)};return n.current.totalDetectionMs+=S,n.current.totalPredictMs+=P,n.current.totalBboxCalcMs+=w,n.current.count+=1,n.current.flowType=b,{blurScore:I,blurVerdict:v,facePredictions:B,bboxes:f,debugInfo:{blur_small:I.small,blur_large:I.large,blur_verdict:v,blur_predict_ms:P,blur_detection_ms:S,blur_flow_type:b,bbox_calc_ms:w}}},[e,r]),getBlurRuntimeSummary:a}}({blazefaceModel:O.current?.blazefaceModel,blurDetector:O.current?.blurDetector}),ea=t.useCallback(e=>eo({...e,blurSmallThreshold:r,blurLargeThreshold:o}),[eo,r,o]),{checkCardValidity:ei}=function({settings:e,frontSide:r,blazefaceModel:o,checkBlur:n,getBlurRuntimeSummary:a}){let{enableBlurCheck:i,enableGlareCheck:s,glareThreshold:l,isVietnameseCardFlow:d,hasFrontFace:u,hasBackFace:g,genericEnableCheckFrontFace:p,genericEnableCheckBackFace:m,enableCardTypeCheck:f,allowedCards:h,blurSmallDecimal:k,blurLargeDecimal:b,blurFullFaceImageRatio:_}=e;return{checkCardValidity:t.useCallback(async({result:e,workingCanvas:t,cropDimensions:C})=>{let B,{cropWidth:y,cropHeight:v,cropWidthWithoutPadding:x,cropHeightWithoutPadding:P}=C,S={error:null,detectedCard:null,predictedIdCardCanvas:null,blurScore:void 0,glareScore:void 0,runtime:void 0,facePredictions:void 0,bboxes:void 0,blurDebugInfo:void 0,glareDebugInfo:void 0},I=e=>({...S,error:{code:e}});if(!e.card)return I(r?"id_detector_front_no_cards":"id_detector_back_no_cards");if(S.detectedCard=e.card,!await w.validatePadding({corners:e.card.corners,width:y,height:v}))return I("id_detector_error_incomplete");if(!await w.validateAngles(e.card.corners))return I("id_detector_validate_angle_error");let R=await eR(t,e.card.corners),$=c.rectAreaRatio({small:{area:R.width*R.height},big:{area:x*P}});if($<.5)return I("id_detector_card_too_small");if($>.95)return I("id_detector_error_incomplete");if(d&&f){let{isAllowed:t,cardType:r}=((e,t)=>{let r=e.split(".")?.[0];if(r!==t[0].split(".")?.[0])return{isAllowed:!1,cardType:""};if(t.includes("vn.national_id"))return{isAllowed:!0,cardType:e.replace(/\.front|\.back/g,"")};if(e.includes("vn.cmnd_new.back")&&t.includes("vn.cccd")||e.includes("vn.cccd.back")&&t.includes("vn.cmnd_new"))return{isAllowed:!0,cardType:"vn.cccd"};let o=t.map(e=>e.replace("vn.","")),n=e.split(".")?.filter(e=>"front"!==e&&"back"!==e&&"vn"!==e);return o.some(e=>n.includes(e))?{isAllowed:!0,cardType:`vn.${n.join(".")}`}:{isAllowed:!1,cardType:""}})(e.card?.label??"",h.map(e=>e.code));if(!t)return I("not_allowed_card_types");S.detectedCard={...S.detectedCard,cardType:r}}d||(S.detectedCard={...S.detectedCard,cardType:h?.[0]?.code});let D=document.createElement("canvas"),M=D.getContext("2d");D.width=R.width,D.height=R.height,M.putImageData(R,0,0),S.predictedIdCardCanvas=D;let[E,T]=s?await e$({canvas:D,glareThreshold:l}):[!1];if(S.glareScore=T,S.glareDebugInfo={glare_score:T,is_glare:E},E)return I("glare_detected");if(B=d?await eD({blazefaceModel:o,predictedIdCardCanvas:D,frontSide:r}):await eM({blazefaceModel:o,predictedIdCardCanvas:D,frontSide:r,hasFrontFace:u,hasBackFace:g,genericEnableCheckFrontFace:p,genericEnableCheckBackFace:m}))return I(B?.code);if(d){let t=e.card?.label??"",o=w.isFrontSide(t)||w.isBackSide(t);if(o&&r&&w.isBackSide(t))return I("id_detector_invalid_front_card");if(o&&!r&&w.isFrontSide(t))return I("id_detector_invalid_back_card")}if(i){let o=await n({workingCanvas:t,result:e,frontSide:r,isVietnameseCardFlow:d,blurSmallDecimal:k,blurLargeDecimal:b,blurFullFaceImageRatio:_});if(S.facePredictions=o.facePredictions,S.bboxes=o.bboxes,S.blurDebugInfo=o.debugInfo,S.blurScore=o.blurScore,S.runtime={blur_detection:a()},"blurry"===o.blurVerdict)return I("id_detector_error_blurry")}return S},[i,s,l,d,u,g,p,m,f,h,k,b,_,r,n,a,o])}}({settings:l,frontSide:p,blazefaceModel:O.current?.blazefaceModel,checkBlur:ea,getBlurRuntimeSummary:en}),es=t.useMemo(()=>({videoFrameWidth:l.recordVideoFrameWidth,videoFrameHeight:l.recordVideoFrameHeight,videoBitrate:l.recordVideoBitrate,fps:l.recordVideoFps}),[l.recordVideoBitrate,l.recordVideoFps,l.recordVideoFrameHeight,l.recordVideoFrameWidth]),{startRecording:el,stopRecording:ec,resetRecording:ed}=tc({shouldRecord:t.useMemo(()=>p?l.enableRecordCapturingFront:l.enableRecordCapturingBack,[p,l.enableRecordCapturingBack,l.enableRecordCapturingFront])}),{startRecording:eu,stopRecording:ep,resetRecording:em}=tc({shouldRecord:t.useMemo(()=>p?l.enableRecordFullSessionFront:l.enableRecordFullSessionBack,[p,l.enableRecordFullSessionBack,l.enableRecordFullSessionFront])}),{turnOnFlashlight:ef,turnOffFlashlight:eh}=v(),ek=t.useRef(!1);t.useEffect(()=>{J.current=!1},[p]),t.useEffect(()=>{let e=!1;return async function t(){if(l&&!D){if(l.enableIdDetection){let e=((e,t)=>{if(0===e.length)return{isValid:!1};let r=[];return(e.forEach(e=>{let o=t[e];if(o)return void r.push(o);let n=e.split("."),a=t[`${n[0]}.*`];a?r.push(a):r.push({model:u.IdCardModelName.model_vn,force_off_detection:!1})}),r.every(e=>e.model===r[0].model))?{isValid:!0,cardModel:r[0].model,forceOffDetection:r[0].force_off_detection}:{isValid:!1}})(H.map(e=>e.code),l?.cardTypeModelMapping);if(!e.isValid){V(td.invalid_card_type_config),Q(!1),M(!0);return}let t=W.idCardModelUrls[e.cardModel];O.current=await P({...W,idCardModelUrl:t},e.cardModel),await S.initTensorFlow(),F.current=l.enableBlurCheck&&O.current.ableToUseModel,Q(!e.forceOffDetection)}else Q(!1),F.current=!1;e||M(!0)}}(),()=>{e=!0}},[D,l,W,H,V]),t.useEffect(()=>{X.current=e},[e]);let eb=t.useCallback(async e=>{b.current=await eT({canvas:k.current,cardPosition:e,quality:f})},[f]),e_=t.useCallback(()=>{Z||(ed(),em())},[Z,ed,em]),eC=t.useCallback(async()=>{let e={capturingVideo:{blob:null},fullVideo:{blob:null}},t=await ec();e.capturingVideo.blob=t?.[0]??null;let r=await ep();return e.fullVideo.blob=r?.[0]??null,e},[ec,ep]),eB=t.useMemo(()=>p?l.enableFlashlightFront:l.enableFlashlightBack,[p,l.enableFlashlightBack,l.enableFlashlightFront]),ew=t.useMemo(()=>p?l.flashlightActivationDelayFront:l.flashlightActivationDelayBack,[p,l.flashlightActivationDelayBack,l.flashlightActivationDelayFront]),ex=t.useMemo(()=>p?l.flashlightDurationFront:l.flashlightDurationBack,[p,l.flashlightDurationBack,l.flashlightDurationFront]),eP=t.useCallback(()=>{!ek.current&&eB&&(ek.current=!0,setTimeout(()=>{ef(ex)},ew))},[ew,ex,eB,ef]),eI=t.useCallback(async()=>{ek.current&&await eh()},[eh]),ez=t.useCallback(()=>{!0===R.current&&(R.current=!1)},[]),eO=t.useCallback(()=>{e_(),q.current=[],U.current=[],j.current=null,z.current=!1,J.current=!1,ee()},[e_,ee]),eW=t.useCallback(async({blurScore:e,detectedCard:t,glareScore:a,runtime:i})=>{await el({videoEl:n.current,resultAnalyzeVideoAndWindowSizes:$.current,recordVideoSettings:es}),eP();let s=E.current,c=T.current;if(C.current=!1,eA({currentFrameBlurScore:s.blurScore,incomingFrameBlurScore:e,currentFrameGlareScore:s.glareScore,incomingFrameGlareScore:a,settings:l,blurLargeThreshold:o,blurSmallThreshold:r})){if(null===s.imageBlob&&(j.current=Date.now()),z.current)s.imageBlob=c.imageBlob;else{let e=k.current;s.hash=eE({canvas:e,cardPosition:t,quality:f}),s.imageBlob=await x.takePicture({canvas:e,quality:f}),s.captureTime=Date.now()}s.takenAt=new Date().getTime(),s.blurScore=e,s.glareScore=a,s.detectedCard=t,s.captureType="auto",s.runtime=i,s.qrScannedResults=et()}l.enableBlurCheck&&q.current.push(e),l.enableGlareCheck&&U.current.push(a)},[el,n,es,eP,l,o,r,f,et]),eV=t.useCallback(async({blurScore:e,detectedCard:t,glareScore:n,runtime:a})=>{L.current=!0;let i=T.current;if(l.enableBlurCheck&&q.current.push(e),l.enableGlareCheck&&U.current.push(n),eA({currentFrameBlurScore:i.blurScore,currentFrameGlareScore:i.glareScore,incomingFrameBlurScore:e,incomingFrameGlareScore:n,settings:l,blurLargeThreshold:o,blurSmallThreshold:r})){let r=k.current;i.hash=eE({canvas:r,cardPosition:t,quality:f}),i.imageBlob=await x.takePicture({canvas:r,quality:f}),i.captureDuration+=Date.now()-i.captureTime,i.captureTime=Date.now(),i.blurScore=e,i.glareScore=n,i.detectedCard=t,i.captureCount++,i.captureType="manual",i.runtime=a,i.qrScannedResults=et(),z.current=!0}L.current=!1},[o,r,f,l,et]),eN=t.useCallback(async()=>{let{autoCaptureWaitForBestImageTimeMs:e}=l,t=E.current;if(null!==t.imageBlob&&new Date().getTime()-j.current>e){let e=await eC();await eI(),await m({...t,...e}),G(!1),j.current=null}},[l,eC,eI,m]),eQ=t.useCallback(()=>{A.current=!0},[]),eq=t.useCallback(()=>new Promise(e=>{A.current=!1;let t=setInterval(()=>{L.current||(clearInterval(t),e())},150)}),[]),eU=t.useCallback(async()=>(await el({videoEl:n.current,resultAnalyzeVideoAndWindowSizes:$.current,recordVideoSettings:es}),eP(),new Promise(e=>{let{enableVirtualCamHashes:t,manualCaptureWaitForBestImageTimeMs:n}=l,a=T.current;if(a.captureTime=Date.now(),F.current)G(!0),eQ(),setTimeout(()=>{eq().then(async()=>{await eI(),(a.blurScore?.small<=r||a.blurScore?.large<=o)&&(a.error=td.id_detector_error_blur);let n=k.current;if(null===a.imageBlob){let r=eE({canvas:n,cardPosition:a.detectedCard});x.takePicture({canvas:n,quality:f}).then(async o=>{a.imageBlob=o,a.captureTime=Date.now(),a.hash=r,t&&await eb(a.detectedCard);let n=await eC();e({...a,...n,qrScannedResults:et()})})}else{t&&await eb(a.detectedCard);let r=await eC();e({...a,...r,qrScannedResults:et()})}G(!1)})},n);else{let r=eE({canvas:k.current,cardPosition:_.current,quality:f});x.takePicture({canvas:k.current,quality:f}).then(async o=>{a.imageBlob=o,a.captureTime=Date.now(),a.hash=r,t&&await eb(a.detectedCard),e({...a,qrScannedResults:et()})})}})),[el,n,es,eP,l,eQ,eq,eC,eI,r,o,f,eb,et]),eX=t.useRef(null),eH=t.useRef(null),eK=t.useRef({});t.useEffect(()=>(h&&(eX.current=document.createElement("canva