k-qr-scanner 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/README.md +38 -10
- package/dist/chunks/chunk-PUUIGXID.js +149 -0
- package/dist/chunks/engine-EJ4OC3LZ.js +1 -0
- package/dist/cli.js +22 -9
- package/dist/element.d.ts +11 -1
- package/dist/emv.d.ts +89 -0
- package/dist/engine.d.ts +5 -0
- package/dist/index.cjs +24 -10
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -2
- package/dist/kqrcode.engine.js +1 -1
- package/dist/kqrcode.global.js +24 -10
- package/dist/kqrcode.jsqr.js +0 -1
- package/dist/react-native.d.ts +4 -0
- package/dist/react.cjs +1 -2
- package/dist/react.d.ts +2 -0
- package/dist/react.js +1 -2
- package/dist/rn/index.js +5 -6
- package/dist/rn/runtime.js +1 -1
- package/dist/scan-qr.d.ts +2 -0
- package/dist/sr.cjs +0 -1
- package/dist/sr.js +1 -2
- package/dist/svelte.cjs +1 -2
- package/dist/svelte.d.ts +2 -0
- package/dist/svelte.js +1 -2
- package/dist/vue.cjs +1 -2
- package/dist/vue.d.ts +2 -0
- package/dist/vue.js +1 -2
- package/llms.txt +15 -8
- package/package.json +2 -3
- package/dist/chunks/chunk-E66QYIQI.js +0 -135
- package/dist/chunks/chunk-E66QYIQI.js.map +0 -6
- package/dist/chunks/chunk-HCGRA6GM.js +0 -2
- package/dist/chunks/chunk-HCGRA6GM.js.map +0 -6
- package/dist/chunks/decoder-jsqr-54X2IQSI.js +0 -2
- package/dist/chunks/decoder-jsqr-54X2IQSI.js.map +0 -6
- package/dist/chunks/engine-QWSAAVKN.js +0 -2
- package/dist/chunks/engine-QWSAAVKN.js.map +0 -6
- package/dist/chunks/worker-source.generated-24WX42PC.js +0 -2
- package/dist/chunks/worker-source.generated-24WX42PC.js.map +0 -6
- package/dist/cli.d.ts +0 -17
- package/dist/decoder-jsqr.d.ts +0 -3
- package/dist/decoder-zxing.d.ts +0 -3
- package/dist/engine-host.d.ts +0 -48
- package/dist/engine.cjs +0 -1
- package/dist/index.cjs.map +0 -6
- package/dist/index.js.map +0 -6
- package/dist/jsqr.cjs +0 -2
- package/dist/jsqr.cjs.map +0 -6
- package/dist/kqrcode.global.js.map +0 -6
- package/dist/kqrcode.jsqr.js.map +0 -6
- package/dist/react.cjs.map +0 -6
- package/dist/react.js.map +0 -6
- package/dist/rn/index.js.map +0 -6
- package/dist/rn-bridge.d.ts +0 -103
- package/dist/rn-runtime.generated.d.ts +0 -2
- package/dist/sr-model.generated.d.ts +0 -4
- package/dist/sr.cjs.map +0 -6
- package/dist/sr.js.map +0 -6
- package/dist/svelte.cjs.map +0 -6
- package/dist/svelte.js.map +0 -6
- package/dist/vue.cjs.map +0 -6
- package/dist/vue.js.map +0 -6
- package/dist/worker-source.generated.d.ts +0 -2
- package/dist/worker.d.ts +0 -1
- package/docs/API.md +0 -292
- package/docs/BENCHMARK.md +0 -101
- package/docs/CUSTOMIZE.md +0 -150
- package/docs/FRAMEWORKS.md +0 -241
- package/docs/REACT_NATIVE.md +0 -181
- package/docs/TESTING.md +0 -90
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var xt=Object.create;var $=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Mt=Object.getPrototypeOf,kt=Object.prototype.hasOwnProperty;var zt=(o,e)=>()=>(o&&(e=o(o=0)),e);var et=(o,e)=>{for(var t in e)$(o,t,{get:e[t],enumerable:!0})},nt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wt(e))!kt.call(o,i)&&i!==t&&$(o,i,{get:()=>e[i],enumerable:!(n=yt(e,i))||n.enumerable});return o};var it=(o,e,t)=>(t=o!=null?xt(Mt(o)):{},nt(e||!o||!o.__esModule?$(t,"default",{value:o,enumerable:!0}):t,o)),Rt=o=>nt($({},"__esModule",{value:!0}),o);var mt={};et(mt,{analyze:()=>_t,locate:()=>lt,symbolModules:()=>at,textureCandidates:()=>ct});function at(o,e){let t=e??"";if(o==="micro_qr_code"){let i=parseInt(t.replace(/^M/i,""),10);return i>=1&&i<=4?9+2*i:13}if(o==="rm_qr_code"){let i=/(\d+)\s*x\s*(\d+)/i.exec(t);return i?Math.max(+i[1],+i[2]):43}let n=parseInt(t,10);return n>=1&&n<=40?17+4*n:25}function At(o){let e=o.width*o.height;(!U||U.length!==e)&&(U=new Uint8Array(e));let t=U,n=o.data,i=0;for(let r=0,s=0;r<e;r++,s+=4){let a=n[s]*77+n[s+1]*150+n[s+2]*29>>8;t[r]=a,(r&15)===0&&(i+=a)}return{gray:t,luma:i/Math.ceil(e/16)}}function rt(o,e=!1){let t=o[0]+o[1]+o[2]+o[3]+o[4];if(t<7)return!1;let n=t/7,i=n*(e?.6:.85);return Math.abs(o[0]-n)<i&&Math.abs(o[1]-n)<i&&Math.abs(o[3]-n)<i&&Math.abs(o[4]-n)<i&&Math.abs(o[2]-3*n)<3*i}function Ct(o,e,t,n){let r=Math.ceil(e/16),s=Math.ceil(t/16);(!W||W.length!==r*s)&&(W=new Float32Array(r*s));let a=W;for(let g=0;g<s;g++){let p=g*16,l=Math.min(t,p+16);for(let m=0;m<r;m++){let b=m*16,c=Math.min(e,b+16),u=0,x=0;for(let y=p;y<l;y+=2){let w=y*e;for(let M=b;M<c;M+=2)u+=o[w+M],x++}a[g*r+m]=u/x}}let h=Math.max(2,Math.round(e/16/16)),d=r+1,f=new Float32Array(d*(s+1));for(let g=0;g<s;g++){let p=0;for(let l=0;l<r;l++)p+=a[g*r+l],f[(g+1)*d+l+1]=f[g*d+l+1]+p}(!V||V.length!==r*s)&&(V=new Uint8Array(r*s));let v=V;for(let g=0;g<s;g++){let p=Math.max(0,g-h),l=Math.min(s,g+h+1);for(let m=0;m<r;m++){let b=Math.max(0,m-h),c=Math.min(r,m+h+1),u=f[l*d+c]-f[p*d+c]-f[l*d+b]+f[p*d+b];v[g*r+m]=Math.min(255,u/((c-b)*(l-p))*n)}}return{thr:v,bw:r}}function lt(o,e,t,n=!1){let{thr:i,bw:r}=Ct(o,e,t,n?1.1:.9),s=n?(m,b)=>o[b*e+m]>i[(b>>4)*r+(m>>4)]:(m,b)=>o[b*e+m]<i[(b>>4)*r+(m>>4)],a=(m,b,c,u,x)=>{let y=Math.ceil(x*2),w=(C,I,E)=>{let A=[0,0,0],D=C,B=I,j=0;for(let tt=0;tt<y;tt++){if(D+=c*E,B+=u*E,D<0||B<0||D>=e||B>=t)return null;let K=s(D,B);if(j===0)K?A[0]++:(j=1,A[1]++);else if(j===1)K?(j=2,A[2]++):A[1]++;else if(K)A[2]++;else return A}return null},M=w(m,b,-1),z=w(m,b,1);if(!M||!z||M[2]===0||z[2]===0)return null;let S=M[0]+z[0]+1,T=[M[2],M[1],S,z[1],z[2]];if(!rt(T))return null;let k=T[0]+T[1]+T[2]+T[3]+T[4],R=(z[0]-M[0])/2;return{total:k,ox:c*R,oy:u*R}},h=[],d=(m,b,c)=>{for(let u of h){let x=Math.max(u.m,c)*2.5;if(Math.abs(u.x-m)<x&&Math.abs(u.y-b)<x&&Math.abs(u.m-c)<Math.max(u.m,c)*.5){let y=u.n;u.x=(u.x*y+m)/(y+1),u.y=(u.y*y+b)/(y+1),u.m=(u.m*y+c)/(y+1),u.n++;return}}h.length<200&&h.push({x:m,y:b,m:c,n:1})},f=[0,0,0,0,0],v=2;for(let m=v>>1;m<t;m+=v){let b=0,c=s(0,m),u=0;f[0]=f[1]=f[2]=f[3]=f[4]=0;for(let x=1;x<=e;x++){let y=x<e?s(x,m):!c;if(b++,y!==c||x===e){if(f[0]=f[1],f[1]=f[2],f[2]=f[3],f[3]=f[4],f[4]=b,u++,c&&u>=5&&rt(f)){let w=f[0]+f[1]+f[2]+f[3]+f[4],M=x-f[4]-f[3]-f[2]/2,z=w/7,S=Math.round(M-.5),T=a(S,m,0,1,w);if(T){let k=m+T.oy,R=a(S,Math.round(k),1,0,w);R&&d(S+R.ox,k,(z+T.total/7)/2)}}c=y,b=0}}}let g=h.filter(m=>m.n>=2).sort((m,b)=>b.n-m.n).slice(0,14);if(!g.length)return null;let p=null;for(let m=0;m<g.length;m++)for(let b=m+1;b<g.length;b++)for(let c=b+1;c<g.length;c++){let u=[g[m],g[b],g[c]],x=u.map(E=>E.m);if(Math.max(...x)/Math.min(...x)>1.8)continue;let y=(E,A)=>Math.hypot(E.x-A.x,E.y-A.y),w=[[y(u[0],u[1]),0,1],[y(u[0],u[2]),0,2],[y(u[1],u[2]),1,2]];w.sort((E,A)=>A[0]-E[0]);let M=w[0],z=w[1][0],S=w[2][0],T=Math.abs(z-S)/Math.max(z,S),k=Math.abs(M[0]-Math.SQRT2*((z+S)/2))/M[0];if(T>.4||k>.3)continue;let R=(x[0]+x[1]+x[2])/3,C=(z+S)/2;if(C<R*6)continue;let I=T+k;if(!p||I<p.err){let E=u[M[1]],A=u[M[2]];p={err:I,hint:{cx:(E.x+A.x)/2,cy:(E.y+A.y)/2,size:C+7*R,module:R,full:!0}}}}if(p)return p.hint;let l=g[0];if(g.length>=2){let m=g[1],b=Math.hypot(l.x-m.x,l.y-m.y);return{cx:(l.x+m.x)/2,cy:(l.y+m.y)/2,size:b*1.3+7*l.m,module:(l.m+m.m)/2,full:!1}}return{cx:l.x,cy:l.y,size:l.m*29,module:l.m,full:!1}}function ct(o,e,t,n=3){let r=Math.floor(e/8),s=Math.floor(t/8),a=new Float32Array(r*s);for(let l=0;l<s;l++)for(let m=0;m<r;m++){let b=0,c=m*8,u=l*8;for(let x=u;x<u+8;x+=2){let y=x*e;for(let w=c;w<c+8;w+=2){let M=o[y+w];b+=Math.abs(M-o[y+w+1])+Math.abs(M-o[y+e+w])}}a[l*r+m]=b/16}let h=Float32Array.from(a).sort(),d=h[h.length>>1],f=Math.max(7,d*2.5,h[Math.floor(h.length*.6)]*1.5),v=new Int32Array(r*s).fill(-1),g=[],p=[];for(let l=0;l<r*s;l++){if(v[l]!==-1||a[l]<f)continue;let m=0,b=0,c=r,u=s,x=0,y=0;for(p.push(l),v[l]=l;p.length;){let k=p.pop(),R=k%r,C=k/r|0;m++,b+=a[k],R<c&&(c=R),R>x&&(x=R),C<u&&(u=C),C>y&&(y=C);let I=[R>0?k-1:-1,R<r-1?k+1:-1,C>0?k-r:-1,C<s-1?k+r:-1];for(let E of I)E>=0&&v[E]===-1&&a[E]>=f&&(v[E]=l,p.push(E))}let w=x-c+1,M=y-u+1,z=m/(w*M),S=Math.max(w,M)/Math.min(w,M);if(m<4||Math.max(w,M)*8>Math.min(e,t)*.9||S>2.2||z<.4)continue;let T=Math.max(w,M)*8;g.push({hint:{cx:(c+x+1)*8/2,cy:(u+y+1)*8/2,size:T,module:T/29,full:!1},score:z*(b/m)*Math.min(1,m/9)/S})}return g.sort((l,m)=>m.score-l.score).slice(0,n).map(l=>l.hint)}function Z(o,e,t,n,i,r){let s=Math.round(n*r),a=Math.round(i*r),h=new Uint8ClampedArray(s*a*4),d=o.data,f=o.width;for(let v=0;v<a;v++){let g=t+(v+.5)/r-.5,p=Math.max(0,Math.min(o.height-1,Math.floor(g))),l=Math.min(o.height-1,p+1),m=g-p;for(let b=0;b<s;b++){let c=e+(b+.5)/r-.5,u=Math.max(0,Math.min(f-1,Math.floor(c))),x=Math.min(f-1,u+1),y=c-u,w=(v*s+b)*4,M=(p*f+u)*4,z=(p*f+x)*4,S=(l*f+u)*4,T=(l*f+x)*4;for(let k=0;k<3;k++){let R=d[M+k]+(d[z+k]-d[M+k])*y,C=d[S+k]+(d[T+k]-d[S+k])*y;h[w+k]=R+(C-R)*m}h[w+3]=255}}return{data:h,width:s,height:a}}async function ut(o,e,t,n,i){let r=await n(o),s=Z(r,0,0,r.width,r.height,2),a=s.width/o.width,h=await t.decode(s,e,i);return h?{r:h,k:a}:null}async function st(o,e,t,n,i,r){let s=e.full?.3:.45,a=e.size*(1+s),h=Math.max(0,Math.floor(e.cx-a/2)),d=Math.max(0,Math.floor(e.cy-a/2)),f=Math.min(o.width,Math.ceil(e.cx+a/2)),v=Math.min(o.height,Math.ceil(e.cy+a/2)),g=f-h,p=v-d;if(g<24||p<24)return null;let l=Math.min(4,Math.max(1,4/Math.max(1,e.module)),1600/Math.max(g,p));l=Math.round(l*2)/2;let m=l===1&&g===o.width&&p===o.height?o:Z(o,h,d,g,p,l),b=await n.decode(m,t,r);if(b){let c=u=>({x:h+u.x/l,y:d+u.y/l});return{...J(b),corners:b.corners.map(c),luma:0}}if(i&&e.module<4.5&&Math.max(g,p)<=(i.maxSide??ht)){let c=Z(o,h,d,g,p,1),u=await ut(c,t,n,i,r);if(u){let x=y=>({x:h+y.x/u.k,y:d+y.y/u.k});return{...J(u.r),corners:u.r.corners.map(x),luma:0}}}return null}function G(o,e){let t=o.corners,n=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y);return{...J(o),corners:t,hint:{cx:(t[0].x+t[2].x)/2,cy:(t[0].y+t[2].y)/2,size:n,module:n/at(o.format,o.version),full:!0},luma:e}}async function _t(o,e,t,n){let i=!!e.invert,r=e.sr===!1?null:n??null,{gray:s,luma:a}=At(o);if(e.roiOnly){let v=e.upscale&&e.upscale>1?e.upscale:1,g=v>1?Z(o,0,0,o.width,o.height,v):o,p=await t.decode(g,i,e.formats);if(p)return G({...p,corners:p.corners.map(l=>({x:l.x/v,y:l.y/v}))},a);if(r&&v>1&&Math.max(o.width,o.height)<=(r.maxSide??ht)){let l=await ut(o,i,t,r,e.formats);if(l)return G({...l.r,corners:l.r.corners.map(m=>({x:m.x/l.k,y:m.y/l.k}))},a)}return{luma:a}}if(e.hint){let v=await st(o,e.hint,i,t,r,e.formats);if(v)return{...v,hint:e.hint,luma:a}}if(!t.slow||e.thorough){let v=await t.decode(o,i,e.formats);if(v)return G(v,a)}let h=lt(s,o.width,o.height,i),d=h?[h]:[];for(let v of ct(s,o.width,o.height)){if(d.length>=3)break;d.some(g=>Math.hypot(g.cx-v.cx,g.cy-v.cy)<Math.max(g.size,v.size)*.6)||d.push(v)}let f=r;for(let v of d){let g=await st(o,v,i,t,f,e.formats);if(g)return{...g,hint:v,luma:a};f&&v.module<4.5&&(f=null)}return{hint:h??d[0]??null,luma:a}}var U,V,W,ht,J,dt=zt(()=>{"use strict";U=null;V=null,W=null;ht=160;J=o=>({text:o.text,bytes:o.bytes,format:o.format??"qr_code",version:o.version??"",ecLevel:o.ecLevel??""})});var qt={};et(qt,{AutoZoom:()=>F,KQRScannerElement:()=>q,LABELS:()=>Y,QRScanner:()=>P,QR_FORMATS:()=>N,ScanError:()=>L,TAG_NAME:()=>Q,THEME_VARS:()=>vt,defineScannerElement:()=>O,scanQR:()=>bt});module.exports=Rt(qt);var F=class{constructor(e={}){this.settleUntil=0;this.holdUntil=0;this.lostAt=null;this.resetDone=!1;this.sweepIdx=0;this.sweepDir=1;this.lastSweepAt=0;this.settleMs=e.settleMs??380}hold(e,t=3500){this.holdUntil=e+t}settle(e,t=this.settleMs){this.settleUntil=Math.max(this.settleUntil,e+t)}update(e){return e.max<=e.min*1.05||e.now<this.settleUntil||e.now<this.holdUntil?null:e.hint?(this.lostAt=null,this.resetDone=!1,this.follow(e)):this.search(e)}follow(e){let t=e.hint,n=Math.min(e.videoWidth,e.videoHeight),i=t.size/n,r=1;e.decoded?i<.42*.7&&(r=.42/i):(t.module<4&&(r=6/Math.max(.5,t.module)),t.full||(r=Math.min(r,2))),r=Math.min(r,.7/i);let s=Math.abs(t.cx-e.videoWidth/2)+t.size/2,a=Math.abs(t.cy-e.videoHeight/2)+t.size/2;if(r=Math.min(r,e.videoWidth/2/s*.92,e.videoHeight/2/a*.92),r=Math.max(.8,Math.min(3.5,r)),r>.9&&r<1.18)return null;let h=ot(e.zoom*r,e.min,e.max);if(Math.abs(h-e.zoom)/e.zoom<.08)return null;let d=e.zoom+(h-e.zoom)*.75;return this.settle(e.now),ot(d,e.min,e.max)}search(e){if(this.lostAt===null&&(this.lostAt=e.now),e.now-this.lostAt<700)return null;if(!this.resetDone)return this.resetDone=!0,this.sweepIdx=0,this.sweepDir=1,this.lastSweepAt=e.now,this.settle(e.now,300),e.zoom>e.min*1.05?e.min:null;if(e.now-this.lastSweepAt<700)return null;let t=St(e.min,e.max);if(t.length<2)return null;let n=this.sweepIdx+this.sweepDir;return n>=t.length&&(this.sweepDir=-1,n=t.length-2),n<0&&(this.sweepDir=1,n=1),this.sweepIdx=n,this.lastSweepAt=e.now,this.settle(e.now,300),t[n]}};function St(o,e){let t=[o];for(let n of[2,3.5,5.5,8,12])n>o*1.4&&n<=e&&t.push(n);return t}function ot(o,e,t){return Math.max(e,Math.min(t,o))}var Tt=null,Et=()=>Tt??(Tt=import("./engine.cjs").then(o=>o.default)),X=class{constructor(){this.idleTimeout=3e4;this.srBackend="off";this.unavailable=!1;this.worker=null;this.starting=null;this.ready=null;this.refs=0;this.idleTimer=0;this.pending=new Map;this.nextId=0}warm(){return this.ensure().then(()=>this.ready??void 0).then(()=>this.scheduleIdle())}async acquire(e){this.refs++,this.clearIdle();let t=await this.ensure();return t?(t.postMessage({type:"config",...e}),!0):(this.refs--,!1)}release(){this.refs=Math.max(0,this.refs-1),this.refs===0&&this.scheduleIdle()}analyze(e,t){let n=this.worker;if(!n)return Promise.resolve(null);let i=++this.nextId;return new Promise(r=>{this.pending.set(i,r),"bitmap"in e?n.postMessage({id:i,bitmap:e.bitmap,opts:t},[e.bitmap]):n.postMessage({id:i,pixels:e.pixels,width:e.width,height:e.height,opts:t},[e.pixels])})}get alive(){return!!this.worker}dispose(){this.clearIdle(),this.worker?.terminate(),this.worker=null,this.starting=null,this.ready=null,this.pending.forEach(e=>e(null)),this.pending.clear()}ensure(){return this.worker?Promise.resolve(this.worker):this.unavailable||typeof Worker>"u"?Promise.resolve(null):this.starting??(this.starting=this.spawn())}async spawn(){try{let e=await Et(),t=URL.createObjectURL(new Blob([e],{type:"text/javascript"})),n=new Worker(t);URL.revokeObjectURL(t);let i;return this.ready=new Promise(r=>i=r),n.onmessage=r=>{let s=r.data;if(s.type==="ready"){s.wasm===!1&&this.fail(),i();return}if(s.type==="config-done"){this.srBackend=s.sr??"off";return}if(s.id===void 0)return;let a=this.pending.get(s.id);this.pending.delete(s.id),s.error==="no-wasm"&&this.fail(),a?.(s.result??null)},n.onerror=()=>{this.fail(),i()},this.worker=n,n}catch{return this.unavailable=!0,null}finally{this.starting=null}}fail(){this.unavailable=!0,this.dispose()}scheduleIdle(){this.clearIdle(),!(this.refs>0||!this.worker)&&(this.idleTimer=setTimeout(()=>{this.refs===0&&this.dispose()},this.idleTimeout))}clearIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=0}},_=new X;var L=class extends Error{constructor(t,n){super(n??t);this.code=t;this.name="ScanError"}},Lt=o=>new Promise(e=>{let t=o;if(t.requestVideoFrameCallback){let n=!1,i=()=>{n||(n=!0,e())};t.requestVideoFrameCallback(i),setTimeout(i,100)}else requestAnimationFrame(()=>e())}),pt=o=>"bitmap"in o?{bitmap:o.bitmap}:{pixels:o.pixels,width:o.width,height:o.height},P=class o{constructor(e){this.listeners={};this.stream=null;this.track=null;this.running=!1;this.paused=!1;this.loopToken=0;this.engine=!1;this.useBitmap=typeof OffscreenCanvas<"u";this.grabCanvas=null;this.native=null;this.frame=0;this.lastHint=null;this.zoomCtl=new F;this.zoomRange={min:1,max:1};this.zoomValue=1;this.digital=!1;this.lastText="";this.lastTextAt=0;this.rejected=new Map;this.lumaEma=128;this.darkState=!1;this.onVisibility=()=>{this.paused=document.hidden,!document.hidden&&this.running&&this.track?.readyState==="ended"&&(this.stop(),this.start().catch(()=>{}))};this.video=e.video,this.opts={facingMode:"environment",autoZoom:!0,maxZoom:8,continuous:!1,maxFrameSide:1920,hiRes:!0,superResolution:"js",onnxRuntimeUrl:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.webgpu.min.js",...e},this.opts.deviceId=e.deviceId}on(e,t){var i;let n=(i=this.listeners)[e]??(i[e]=new Set);return n.add(t),()=>n.delete(t)}emit(e,t){this.listeners[e]?.forEach(n=>n(t))}static preload(){return _.warm()}static dispose(){_.dispose()}static get engineIdleTimeout(){return _.idleTimeout}static set engineIdleTimeout(e){_.idleTimeout=e}static isSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia}get zoom(){return this.zoomValue}get zoomMin(){return this.zoomRange.min}get zoomMax(){return this.zoomRange.max}get canZoom(){return this.zoomRange.max>this.zoomRange.min*1.05}get isDigitalZoom(){return this.digital}get superResolutionBackend(){return _.srBackend}get canTorch(){return!!this.track?.getCapabilities?.()?.torch}async start(){if(this.running)return;if(typeof window<"u"&&window.isSecureContext===!1)throw this.fail(new L("insecure-context","Camera needs HTTPS (or localhost)."));if(!o.isSupported())throw this.fail(new L("unsupported","getUserMedia is not available."));try{let n=this.opts.deviceId?{deviceId:{exact:this.opts.deviceId},width:{ideal:1920},height:{ideal:1080}}:{facingMode:{ideal:this.opts.facingMode},width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}};this.stream=await navigator.mediaDevices.getUserMedia({video:n,audio:!1})}catch(n){throw this.fail(Ft(n))}this.track=this.stream.getVideoTracks()[0];let e=this.video;e.muted=!0,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline",""),e.srcObject=this.stream;try{await e.play()}catch{}await Promise.all([this.tune(),this.setupDetectors()]),document.addEventListener("visibilitychange",this.onVisibility),this.running=!0,this.paused=!1;let t=++this.loopToken;this.loop(t)}stop(){this.running=!1,this.loopToken++,document.removeEventListener("visibilitychange",this.onVisibility),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.track=null,this.video.srcObject=null,this.video.style.transform="",this.releaseEngine(),this.lastHint=null,this.zoomValue=1}pause(){this.paused=!0}resume(){this.paused=!1,this.lastText="",this.rejected.clear()}setFormats(e){this.opts.formats=e?.length?[...e]:void 0,this.setupNative()}setAccept(e){this.opts.accept=e,this.rejected.clear()}async switchCamera(){this.opts.facingMode=this.opts.facingMode==="environment"?"user":"environment",this.opts.deviceId=void 0,this.stop(),await this.start()}async setZoom(e,t=!0){if(!this.track||!this.canZoom)return;let n=Math.max(this.zoomRange.min,Math.min(this.zoomRange.max,e)),i=performance.now();if(t&&this.zoomCtl.hold(i),this.zoomCtl.settle(i,this.digital?90:380),this.zoomValue=n,this.lastHint=null,this.emit("zoom",{zoom:n,min:this.zoomRange.min,max:this.zoomRange.max,auto:!t,digital:this.digital}),!this.digital)try{await this.track.applyConstraints({advanced:[{zoom:n}]})}catch{}}async setTorch(e){if(!this.track||!this.canTorch)return!1;try{return await this.track.applyConstraints({advanced:[{torch:e}]}),!0}catch{return!1}}async focusAt(e,t){if(this.track){this.zoomCtl.settle(performance.now(),600);try{await this.track.applyConstraints({advanced:[{focusMode:"single-shot",pointsOfInterest:[{x:e,y:t}]}]}),setTimeout(()=>{this.track?.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},1500)}catch{}}}async scanImage(e){let t=e instanceof Blob?await createImageBitmap(e):e,n=!this.engine;n&&await this.setupDetectors();try{let i=Math.max(t.width,t.height),r=[...new Set([Math.min(i,1600),Math.min(i,1e3),Math.min(i,2600)])];for(let s of r){let a=s/i,h=Math.max(1,Math.round(t.width*a)),d=Math.max(1,Math.round(t.height*a)),f=document.createElement("canvas");f.width=h,f.height=d;let v=f.getContext("2d",{willReadFrequently:!0});v.fillStyle="#fff",v.fillRect(0,0,h,d),v.drawImage(t,0,0,h,d);let g=v.getImageData(0,0,h,d),p=await this.analyzeFrame({pixels:g.data.buffer,width:h,height:d},{invert:!0,thorough:!0,formats:this.opts.formats});if(p&&p.text!==void 0){let l=gt(p,[],1,"image"),m=await this.check(l);return m===!0?l:(this.emit("reject",{result:l,message:m||void 0}),null)}}return null}finally{e instanceof Blob&&t.close(),n&&!this.running&&this.releaseEngine()}}fail(e){return this.emit("error",e),e}async tune(){let e=this.track,t=e.getCapabilities?.()??{};if(t.zoom&&typeof t.zoom.max=="number")this.digital=!1,this.zoomRange={min:t.zoom.min??1,max:Math.min(t.zoom.max,this.opts.maxZoom)},this.zoomValue=e.getSettings().zoom??this.zoomRange.min,this.zoomCtl=new F({settleMs:380});else{if(this.digital=!0,this.opts.hiRes)try{await e.applyConstraints({width:{ideal:3840},height:{ideal:2160}}),await new Promise(r=>setTimeout(r,250))}catch{}let n=this.video.videoWidth||1920,i=Math.min(this.opts.maxZoom,4,Math.max(1.5,n/960));this.zoomRange={min:1,max:i},this.zoomValue=1,this.zoomCtl=new F({settleMs:120})}if(t.focusMode?.includes("continuous"))try{await e.applyConstraints({advanced:[{focusMode:"continuous"}]})}catch{}this.emit("zoom",{zoom:this.zoomValue,min:this.zoomRange.min,max:this.zoomRange.max,auto:!0,digital:this.digital})}async setupDetectors(){if(this.setupNative(),!this.engine){let e=this.opts.superResolution;this.engine=await _.acquire({sr:e===!1?"off":e,ortUrl:this.opts.onnxRuntimeUrl})}}setupNative(){if(this.native=null,this.opts.formats&&!this.opts.formats.includes("qr_code"))return;let e=globalThis.BarcodeDetector;e&&e.getSupportedFormats().then(t=>{t.includes("qr_code")&&(this.native=new e({formats:["qr_code"]}))}).catch(()=>{})}async check(e){let t=this.opts.accept;if(!t)return!0;try{let n=await t(e);return n===void 0||n===!0?!0:typeof n=="string"?n:!1}catch{return!1}}releaseEngine(){this.engine&&(this.engine=!1,_.release())}async loop(e){for(;this.running&&e===this.loopToken&&(await Lt(this.video),!(!this.running||e!==this.loopToken));)if(!this.paused)try{await this.step()}catch(t){this.running&&e===this.loopToken&&this.emit("error",new L("unknown",String(t))),await new Promise(n=>setTimeout(n,300))}}async grab(e,t,n){let i=this.video;if(this.useBitmap&&this.engine&&_.alive){try{let h=await createImageBitmap(i,e.x,e.y,e.w,e.h,{resizeWidth:t,resizeHeight:n,resizeQuality:"low"});if(Math.abs(h.width-t)<=1)return{bitmap:h,src:h};h.close()}catch{}this.useBitmap=!1}let r=this.grabCanvas??(this.grabCanvas=document.createElement("canvas"));(r.width!==t||r.height!==n)&&(r.width=t,r.height=n);let s=r.getContext("2d",{willReadFrequently:!0});s.drawImage(i,e.x,e.y,e.w,e.h,0,0,t,n);let a=s.getImageData(0,0,t,n);return{pixels:a.data.buffer,width:t,height:n,src:a}}async analyzeFrame(e,t){if(this.engine&&_.alive)return _.analyze(e,t);let[{analyze:n},{jsqrDecoder:i}]=await Promise.all([Promise.resolve().then(()=>(dt(),mt)),import("./jsqr.cjs")]),r;if("bitmap"in e){let s=document.createElement("canvas");s.width=e.bitmap.width,s.height=e.bitmap.height;let a=s.getContext("2d",{willReadFrequently:!0});a.drawImage(e.bitmap,0,0),e.bitmap.close(),r=a.getImageData(0,0,s.width,s.height)}else r={data:new Uint8ClampedArray(e.pixels),width:e.width,height:e.height};return n(r,t,i)}async step(){let e=this.video;if(e.readyState<2||!e.videoWidth)return;let t=e.videoWidth,n=e.videoHeight,i=performance.now();this.frame++;let r=this.digital?this.zoomValue:1,s={w:t/r,h:n/r,x:0,y:0};s.x=(t-s.w)/2,s.y=(n-s.h)/2;let a=Math.min(1,this.opts.maxFrameSide/Math.max(s.w,s.h)),h=Math.max(2,Math.round(s.w*a)),d=Math.max(2,Math.round(s.h*a)),f=c=>({x:s.x+c.x/a,y:s.y+c.y/a}),v=c=>({cx:(c.cx-s.x)*a,cy:(c.cy-s.y)*a,size:c.size*a,module:c.module*a,full:c.full}),g=await this.grab(s,h,d),p=null;if(this.native)try{let c=await this.native.detect(g.src);if(c.length&&c[0].rawValue){let u=c[0],x=Math.hypot(u.cornerPoints[0].x-u.cornerPoints[1].x,u.cornerPoints[0].y-u.cornerPoints[1].y);p={text:u.rawValue,bytes:new TextEncoder().encode(u.rawValue),corners:u.cornerPoints,hint:{cx:(u.cornerPoints[0].x+u.cornerPoints[2].x)/2,cy:(u.cornerPoints[0].y+u.cornerPoints[2].y)/2,size:x,module:x/25,full:!0},format:"qr_code",version:"",ecLevel:"",luma:128}}}catch{this.native=null}if(p)"bitmap"in g&&g.bitmap.close();else{let c=this.lastHint&&i-this.lastHint.at<700?v(this.lastHint.hint):null;p=await this.analyzeFrame(pt(g),{hint:c,invert:this.frame%6===5,thorough:this.frame%5===0,formats:this.opts.formats})}if(!this.running)return;let l=p?.hint?{cx:s.x+p.hint.cx/a,cy:s.y+p.hint.cy/a,size:p.hint.size/a,module:p.hint.module/a,full:p.hint.full}:null,m=p?.corners?p.corners.map(f):[];if(p&&p.text===void 0&&l&&a<.95&&l.module<5/a){let c=Math.min(Math.max(160,l.size*1.6),Math.min(t,n),1400),u={w:c,h:c,x:Math.max(0,Math.min(t-c,l.cx-c/2)),y:Math.max(0,Math.min(n-c,l.cy-c/2))},x=await this.grab(u,Math.round(c),Math.round(c)),y=Math.min(3,Math.max(1,4/Math.max(1,l.module))),w=await this.analyzeFrame(pt(x),{roiOnly:!0,upscale:y,invert:this.frame%3===0,formats:this.opts.formats});w&&w.text!==void 0&&w.corners&&(p={...w,hint:p.hint,luma:p.luma},m=w.corners.map(M=>({x:u.x+M.x,y:u.y+M.y})))}if(!this.running)return;if(p&&p.luma){this.lumaEma=this.lumaEma*.85+p.luma*.15;let c=this.darkState?this.lumaEma<70:this.lumaEma<45;c!==this.darkState&&(this.darkState=c,this.emit("dark",c))}l&&(this.lastHint={hint:l,at:i});let b=!!p&&p.text!==void 0;if(this.emit("hint",{hint:l,decoded:b,videoWidth:t,videoHeight:n}),this.opts.autoZoom&&this.canZoom&&!b){let c=this.zoomValue,u=l&&this.digital?{cx:(l.cx-t/2)*c+t/2,cy:(l.cy-n/2)*c+n/2,size:l.size*c,module:l.module*c,full:l.full}:l,x=this.zoomCtl.update({now:i,zoom:c,min:this.zoomRange.min,max:this.zoomRange.max,hint:u,decoded:b,videoWidth:t,videoHeight:n});x!==null&&this.setZoom(x,!1)}if(b&&p){let c=p.text;if(this.opts.continuous&&c===this.lastText&&i-this.lastTextAt<1500){this.lastTextAt=i;return}let u=this.rejected.get(c);if(u!==void 0&&i<u){this.rejected.set(c,i+ft);return}let x=gt(p,m,this.zoomValue,"camera"),y=this.loopToken,w=await this.check(x);if(!this.running||y!==this.loopToken)return;if(w!==!0){let M=performance.now();for(let[z,S]of this.rejected)S<M&&this.rejected.delete(z);this.rejected.set(c,M+ft),this.emit("reject",{result:x,message:w||void 0});return}this.lastText=c,this.lastTextAt=performance.now(),this.opts.continuous||(this.paused=!0),this.emit("result",x)}}},ft=2e3;function gt(o,e,t,n){let i=o.text;return{text:i,bytes:o.bytes??new TextEncoder().encode(i),corners:e,format:o.format??"qr_code",version:o.version??"",ecLevel:o.ecLevel??"",zoom:t,timestamp:Date.now(),source:n}}function Ft(o){let e=o?.name;return e==="NotAllowedError"||e==="SecurityError"?new L("permission-denied","Camera permission denied."):e==="NotFoundError"||e==="OverconstrainedError"?new L("no-camera","No camera found."):e==="NotReadableError"||e==="AbortError"?new L("camera-busy","Camera is in use by another app."):new L("unknown",String(o))}var N=["qr_code","micro_qr_code","rm_qr_code"];var Y={en:{hint:"Scan a QR code anywhere in view",zooming:"Zooming in\u2026",dark:"Too dark \u2013 turn on the light",torchOn:"Tap to turn light on",torchOff:"Tap to turn light off",gallery:"Album",noQrInImage:"No QR code found in the image",close:"Close",permission:"Camera permission denied. Please allow camera access.",noCamera:"No camera found on this device.",busy:"The camera is being used by another app.",insecure:"Camera needs HTTPS.",unsupported:"This browser cannot access the camera."},lo:{hint:"\u0EAA\u0EB0\u0EC1\u0E81\u0E99 QR code \u0E9A\u0EC8\u0EAD\u0E99\u0EC3\u0E94\u0E81\u0ECD\u0EC4\u0E94\u0EC9\u0EC3\u0E99\u0E81\u0EC9\u0EAD\u0E87",zooming:"\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E8A\u0EB9\u0EA1\u0EC0\u0E82\u0EBB\u0EC9\u0EB2\u2026",dark:"\u0EA1\u0EB7\u0E94\u0EC0\u0E81\u0EB5\u0E99\u0EC4\u0E9B \u2013 \u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F\u0EAA\u0EB2\u0E8D",torchOn:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F",torchOff:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0E9B\u0EB4\u0E94\u0EC4\u0E9F",gallery:"\u0EAD\u0EB1\u0E99\u0EA5\u0EB0\u0E9A\u0EB1\u0EC9\u0EA1",noQrInImage:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A QR code \u0EC3\u0E99\u0EAE\u0EB9\u0E9A",close:"\u0E9B\u0EB4\u0E94",permission:"\u0E9A\u0ECD\u0EC8\u0EC4\u0E94\u0EC9\u0EAE\u0EB1\u0E9A\u0EAA\u0EB4\u0E94\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87 \u0E81\u0EB0\u0EA5\u0EB8\u0E99\u0EB2\u0EAD\u0EB0\u0E99\u0EB8\u0E8D\u0EB2\u0E94",noCamera:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A\u0E81\u0EC9\u0EAD\u0E87\u0EC3\u0E99\u0EAD\u0EB8\u0E9B\u0EB0\u0E81\u0EAD\u0E99\u0E99\u0EB5\u0EC9",busy:"\u0E81\u0EC9\u0EAD\u0E87\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E96\u0EB7\u0E81\u0EC3\u0E8A\u0EC9\u0EC2\u0E94\u0E8D\u0EC1\u0EAD\u0EB1\u0E9A\u0EAD\u0EB7\u0EC8\u0E99",insecure:"\u0E81\u0EC9\u0EAD\u0E87\u0E95\u0EC9\u0EAD\u0E87\u0EC3\u0E8A\u0EC9 HTTPS",unsupported:"\u0E9A\u0EA3\u0EB2\u0EA7\u0EC0\u0E8A\u0EB5\u0E99\u0EB5\u0EC9\u0E9A\u0ECD\u0EC8\u0EAE\u0EAD\u0E87\u0EAE\u0EB1\u0E9A\u0E81\u0EB2\u0E99\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87"},zh:{hint:"\u626B\u4E8C\u7EF4\u7801 / \u6761\u7801",zooming:"\u6B63\u5728\u653E\u5927\u2026",dark:"\u5149\u7EBF\u592A\u6697",torchOn:"\u8F7B\u89E6\u7167\u4EAE",torchOff:"\u8F7B\u89E6\u5173\u95ED",gallery:"\u76F8\u518C",noQrInImage:"\u672A\u5728\u56FE\u7247\u4E2D\u53D1\u73B0\u4E8C\u7EF4\u7801",close:"\u5173\u95ED",permission:"\u76F8\u673A\u6743\u9650\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u5141\u8BB8\u8BBF\u95EE\u76F8\u673A",noCamera:"\u672A\u627E\u5230\u76F8\u673A",busy:"\u76F8\u673A\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528",insecure:"\u76F8\u673A\u9700\u8981 HTTPS",unsupported:"\u6B64\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u76F8\u673A"}},vt={"--kqr-accent":"scan line / corner colour (theme default: wechat #07c160, alipay #1677ff, frame/grid #1fd17a)","--kqr-success":'colour of the "found it" dot (default: accent)',"--kqr-mask":"dim colour outside the frame (frame theme), default rgba(0,0,0,.45)","--kqr-frame-size":"frame side, default min(70vmin, 300px)","--kqr-frame-top":"vertical centre of the frame, default 42%","--kqr-frame-radius":"default 14px","--kqr-corner-size":"default 24px","--kqr-corner-width":"default 4px","--kqr-scan-duration":"one sweep, default 2.4s","--kqr-line-width":"scan line thickness, default 3px","--kqr-text":"text colour, default #fff","--kqr-font":"font stack","--kqr-button-bg":"round button background, default rgba(40,40,40,.55)","--kqr-button-size":"default 52px","--kqr-bg":"background behind the video, default #000"},H={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',torch:'<svg viewBox="0 0 24 24"><path d="M8 2h8l-1.5 6h-5L8 2zm1.5 6h5V13l2 3v6h-9v-6l2-3V8z" fill="currentColor"/></svg>',image:'<svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="3" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="9" cy="10" r="1.8" fill="currentColor"/><path d="M4 18l5.5-5.5 4 4 3-3L21 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>'},Pt=`
|
|
1
|
+
"use strict";var Et=Object.create;var U=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var Lt=(r,e)=>()=>(r&&(e=r(r=0)),e);var rt=(r,e)=>{for(var t in e)U(r,t,{get:e[t],enumerable:!0})},ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of St(e))!Ct.call(r,i)&&i!==t&&U(r,i,{get:()=>e[i],enumerable:!(n=At(e,i))||n.enumerable});return r};var st=(r,e,t)=>(t=r!=null?Et(Tt(r)):{},ot(e||!r||!r.__esModule?U(t,"default",{value:r,enumerable:!0}):t,r)),_t=r=>ot(U({},"__esModule",{value:!0}),r);var gt={};rt(gt,{analyze:()=>Qt,locate:()=>ht,moire:()=>mt,symbolModules:()=>ut,textureCandidates:()=>dt});function ut(r,e){let t=e??"";if(r==="micro_qr_code"){let i=parseInt(t.replace(/^M/i,""),10);return i>=1&&i<=4?9+2*i:13}if(r==="rm_qr_code"){let i=/(\d+)\s*x\s*(\d+)/i.exec(t);return i?Math.max(+i[1],+i[2]):43}let n=parseInt(t,10);return n>=1&&n<=40?17+4*n:25}function Ft(r){let e=r.width*r.height;(!$||$.length!==e)&&($=new Uint8Array(e));let t=$,n=r.data,i=0;for(let s=0,o=0;s<e;s++,o+=4){let a=n[o]*77+n[o+1]*150+n[o+2]*29>>8;t[s]=a,(s&15)===0&&(i+=a)}return{gray:t,luma:i/Math.ceil(e/16)}}function ct(r,e=!1){let t=r[0]+r[1]+r[2]+r[3]+r[4];if(t<7)return!1;let n=t/7,i=n*(e?.6:.85);return Math.abs(r[0]-n)<i&&Math.abs(r[1]-n)<i&&Math.abs(r[3]-n)<i&&Math.abs(r[4]-n)<i&&Math.abs(r[2]-3*n)<3*i}function Ot(r,e,t,n){let s=Math.ceil(e/16),o=Math.ceil(t/16);(!N||N.length!==s*o)&&(N=new Float32Array(s*o));let a=N;for(let b=0;b<o;b++){let f=b*16,h=Math.min(t,f+16);for(let d=0;d<s;d++){let v=d*16,l=Math.min(e,v+16),g=0,x=0;for(let w=f;w<h;w+=2){let y=w*e;for(let M=v;M<l;M+=2)g+=r[y+M],x++}a[b*s+d]=g/x}}let c=Math.max(2,Math.round(e/16/16)),u=s+1,m=new Float32Array(u*(o+1));for(let b=0;b<o;b++){let f=0;for(let h=0;h<s;h++)f+=a[b*s+h],m[(b+1)*u+h+1]=m[b*u+h+1]+f}(!j||j.length!==s*o)&&(j=new Uint8Array(s*o));let p=j;for(let b=0;b<o;b++){let f=Math.max(0,b-c),h=Math.min(o,b+c+1);for(let d=0;d<s;d++){let v=Math.max(0,d-c),l=Math.min(s,d+c+1),g=m[h*u+l]-m[f*u+l]-m[h*u+v]+m[f*u+v];p[b*s+d]=Math.min(255,g/((l-v)*(h-f))*n)}}return{thr:p,bw:s}}function ht(r,e,t,n=!1){let{thr:i,bw:s}=Ot(r,e,t,n?1.1:.9),o=n?(d,v)=>r[v*e+d]>i[(v>>4)*s+(d>>4)]:(d,v)=>r[v*e+d]<i[(v>>4)*s+(d>>4)],a=(d,v,l,g,x)=>{let w=Math.ceil(x*2),y=(C,q,S)=>{let T=[0,0,0],V=C,D=q,B=0;for(let it=0;it<w;it++){if(V+=l*S,D+=g*S,V<0||D<0||V>=e||D>=t)return null;let X=o(V,D);if(B===0)X?T[0]++:(B=1,T[1]++);else if(B===1)X?(B=2,T[2]++):T[1]++;else if(X)T[2]++;else return T}return null},M=y(d,v,-1),z=y(d,v,1);if(!M||!z||M[2]===0||z[2]===0)return null;let E=M[0]+z[0]+1,A=[M[2],M[1],E,z[1],z[2]];if(!ct(A))return null;let k=A[0]+A[1]+A[2]+A[3]+A[4],R=(z[0]-M[0])/2;return{total:k,ox:l*R,oy:g*R}},c=[],u=(d,v,l)=>{for(let g of c){let x=Math.max(g.m,l)*2.5;if(Math.abs(g.x-d)<x&&Math.abs(g.y-v)<x&&Math.abs(g.m-l)<Math.max(g.m,l)*.5){let w=g.n;g.x=(g.x*w+d)/(w+1),g.y=(g.y*w+v)/(w+1),g.m=(g.m*w+l)/(w+1),g.n++;return}}c.length<200&&c.push({x:d,y:v,m:l,n:1})},m=[0,0,0,0,0],p=2;for(let d=p>>1;d<t;d+=p){let v=0,l=o(0,d),g=0;m[0]=m[1]=m[2]=m[3]=m[4]=0;for(let x=1;x<=e;x++){let w=x<e?o(x,d):!l;if(v++,w!==l||x===e){if(m[0]=m[1],m[1]=m[2],m[2]=m[3],m[3]=m[4],m[4]=v,g++,l&&g>=5&&ct(m)){let y=m[0]+m[1]+m[2]+m[3]+m[4],M=x-m[4]-m[3]-m[2]/2,z=y/7,E=Math.round(M-.5),A=a(E,d,0,1,y);if(A){let k=d+A.oy,R=a(E,Math.round(k),1,0,y);R&&u(E+R.ox,k,(z+A.total/7)/2)}}l=w,v=0}}}let b=c.filter(d=>d.n>=2).sort((d,v)=>v.n-d.n).slice(0,14);if(!b.length)return null;let f=null;for(let d=0;d<b.length;d++)for(let v=d+1;v<b.length;v++)for(let l=v+1;l<b.length;l++){let g=[b[d],b[v],b[l]],x=g.map(S=>S.m);if(Math.max(...x)/Math.min(...x)>1.8)continue;let w=(S,T)=>Math.hypot(S.x-T.x,S.y-T.y),y=[[w(g[0],g[1]),0,1],[w(g[0],g[2]),0,2],[w(g[1],g[2]),1,2]];y.sort((S,T)=>T[0]-S[0]);let M=y[0],z=y[1][0],E=y[2][0],A=Math.abs(z-E)/Math.max(z,E),k=Math.abs(M[0]-Math.SQRT2*((z+E)/2))/M[0];if(A>.4||k>.3)continue;let R=(x[0]+x[1]+x[2])/3,C=(z+E)/2;if(C<R*6)continue;let q=A+k;if(!f||q<f.err){let S=g[M[1]],T=g[M[2]];f={err:q,hint:{cx:(S.x+T.x)/2,cy:(S.y+T.y)/2,size:C+7*R,module:R,full:!0}}}}if(f)return f.hint;let h=b[0];if(b.length>=2){let d=b[1],v=Math.hypot(h.x-d.x,h.y-d.y);return{cx:(h.x+d.x)/2,cy:(h.y+d.y)/2,size:v*1.3+7*h.m,module:(h.m+d.m)/2,full:!1}}return{cx:h.x,cy:h.y,size:h.m*29,module:h.m,full:!1}}function dt(r,e,t,n=3){let s=Math.floor(e/8),o=Math.floor(t/8),a=new Float32Array(s*o);for(let h=0;h<o;h++)for(let d=0;d<s;d++){let v=0,l=d*8,g=h*8;for(let x=g;x<g+8;x+=2){let w=x*e;for(let y=l;y<l+8;y+=2){let M=r[w+y];v+=Math.abs(M-r[w+y+1])+Math.abs(M-r[w+e+y])}}a[h*s+d]=v/16}let c=Float32Array.from(a).sort(),u=c[c.length>>1],m=Math.max(7,u*2.5,c[Math.floor(c.length*.6)]*1.5),p=new Int32Array(s*o).fill(-1),b=[],f=[];for(let h=0;h<s*o;h++){if(p[h]!==-1||a[h]<m)continue;let d=0,v=0,l=s,g=o,x=0,w=0;for(f.push(h),p[h]=h;f.length;){let k=f.pop(),R=k%s,C=k/s|0;d++,v+=a[k],R<l&&(l=R),R>x&&(x=R),C<g&&(g=C),C>w&&(w=C);let q=[R>0?k-1:-1,R<s-1?k+1:-1,C>0?k-s:-1,C<o-1?k+s:-1];for(let S of q)S>=0&&p[S]===-1&&a[S]>=m&&(p[S]=h,f.push(S))}let y=x-l+1,M=w-g+1,z=d/(y*M),E=Math.max(y,M)/Math.min(y,M);if(d<4||Math.max(y,M)*8>Math.min(e,t)*.9||E>2.2||z<.4)continue;let A=Math.max(y,M)*8;b.push({hint:{cx:(l+x+1)*8/2,cy:(g+w+1)*8/2,size:A,module:A/29,full:!1},score:z*(v/d)*Math.min(1,d/9)/E})}return b.sort((h,d)=>d.score-h.score).slice(0,n).map(h=>h.hint)}function Z(r,e,t,n,i,s){let o=Math.round(n*s),a=Math.round(i*s),c=new Uint8ClampedArray(o*a*4),u=r.data,m=r.width;for(let p=0;p<a;p++){let b=t+(p+.5)/s-.5,f=Math.max(0,Math.min(r.height-1,Math.floor(b))),h=Math.min(r.height-1,f+1),d=b-f;for(let v=0;v<o;v++){let l=e+(v+.5)/s-.5,g=Math.max(0,Math.min(m-1,Math.floor(l))),x=Math.min(m-1,g+1),w=l-g,y=(p*o+v)*4,M=(f*m+g)*4,z=(f*m+x)*4,E=(h*m+g)*4,A=(h*m+x)*4;for(let k=0;k<3;k++){let R=u[M+k]+(u[z+k]-u[M+k])*w,C=u[E+k]+(u[A+k]-u[E+k])*w;c[y+k]=R+(C-R)*d}c[y+3]=255}}return{data:c,width:o,height:a}}function mt(r,e,t){let n=0,i=0;for(let s=4;s<t;s+=8){let o=s*e;for(let a=o+1,c=o+e-1;a<c;a++)n+=Math.abs(2*r[a]-r[a-1]-r[a+1]),i++}return i?n/i:0}function Ht(r){let{width:e,height:t,data:n}=r,i=new Uint8ClampedArray(e*t);for(let o=0,a=0;o<i.length;o++,a+=4)i[o]=n[a]*77+n[a+1]*150+n[a+2]*29>>8;let s=new Uint8ClampedArray(e*t*4);for(let o=0;o<t;o++){let a=o>0?o-1:o,c=o<t-1?o+1:o;for(let u=0;u<e;u++){let m=u>0?u-1:u,p=u<e-1?u+1:u,b=(i[a*e+m]+i[a*e+u]+i[a*e+p]+i[o*e+m]+i[o*e+u]+i[o*e+p]+i[c*e+m]+i[c*e+u]+i[c*e+p])/9,f=(o*e+u)*4;s[f]=s[f+1]=s[f+2]=b,s[f+3]=255}}return{data:s,width:e,height:t}}async function ft(r,e,t,n,i){let s=await n(r),o=Z(s,0,0,s.width,s.height,2),a=o.width/r.width,c=await t.decode(o,e,i);return c?{r:c,k:a}:null}async function lt(r,e,t,n,i,s){let o=e.size*(e.full?1.42:1.6)+8*e.module,a=Math.max(0,Math.floor(e.cx-o/2)),c=Math.max(0,Math.floor(e.cy-o/2)),u=Math.min(r.width,Math.ceil(e.cx+o/2)),m=Math.min(r.height,Math.ceil(e.cy+o/2)),p=u-a,b=m-c;if(p<24||b<24)return null;let f=Math.min(4,Math.max(1,4/Math.max(1,e.module)),1600/Math.max(p,b));f=Math.round(f*2)/2;let h=f===1&&p===r.width&&b===r.height?r:Z(r,a,c,p,b,f),d=await n.decode(h,t,s);if(d){let v=l=>({x:a+l.x/f,y:c+l.y/f});return{...tt(d),corners:d.corners.map(v),luma:0}}if(i&&e.module<4.5&&Math.max(p,b)<=(i.maxSide??pt)){let v=Z(r,a,c,p,b,1),l=await ft(v,t,n,i,s);if(l){let g=x=>({x:a+x.x/l.k,y:c+x.y/l.k});return{...tt(l.r),corners:l.r.corners.map(g),luma:0}}}return null}function W(r,e){let t=r.corners,n=Math.hypot(t[0].x-t[1].x,t[0].y-t[1].y);return{...tt(r),corners:t,hint:{cx:(t[0].x+t[2].x)/2,cy:(t[0].y+t[2].y)/2,size:n,module:n/ut(r.format,r.version),full:!0},luma:e}}async function Qt(r,e,t,n){let i=!!e.invert,s=e.sr===!1?null:n??null,{gray:o,luma:a}=Ft(r);if(e.roiOnly){let p=e.upscale&&e.upscale>1?e.upscale:1,b=p>1?Z(r,0,0,r.width,r.height,p):r,f=await t.decode(b,i,e.formats);if(f)return W({...f,corners:f.corners.map(h=>({x:h.x/p,y:h.y/p}))},a);if(s&&p>1&&Math.max(r.width,r.height)<=(s.maxSide??pt)){let h=await ft(r,i,t,s,e.formats);if(h)return W({...h.r,corners:h.r.corners.map(d=>({x:d.x/h.k,y:d.y/h.k}))},a)}return{luma:a}}if(e.hint){let p=await lt(r,e.hint,i,t,s,e.formats);if(p)return{...p,hint:e.hint,luma:a}}if(!t.slow||e.thorough){let p=await t.decode(r,i,e.formats);if(p)return W(p,a)}let c=ht(o,r.width,r.height,i),u=c?[c]:[];for(let p of dt(o,r.width,r.height)){if(u.length>=3)break;u.some(b=>Math.hypot(b.cx-p.cx,b.cy-p.cy)<Math.max(b.size,p.size)*.6)||u.push(p)}let m=s;for(let p of u){let b=await lt(r,p,i,t,m,e.formats);if(b)return{...b,hint:p,luma:a};m&&p.module<4.5&&(m=null)}if((!t.slow||e.thorough)&&(e.thorough||u.some(p=>p.module>=2.5)||mt(o,r.width,r.height)>18)){let p=await t.decode(Ht(r),i,e.formats);if(p)return W(p,a)}return{hint:c??u[0]??null,luma:a}}var $,j,N,pt,tt,bt=Lt(()=>{"use strict";$=null;j=null,N=null;pt=160;tt=r=>({text:r.text,bytes:r.bytes,format:r.format??"qr_code",version:r.version??"",ecLevel:r.ecLevel??""})});var jt={};rt(jt,{AutoZoom:()=>P,KQRScannerElement:()=>F,LABELS:()=>K,QRScanner:()=>I,QR_FORMATS:()=>Y,ScanError:()=>_,TAG_NAME:()=>Q,THEME_VARS:()=>wt,acceptEMV:()=>Rt,defineScannerElement:()=>O,emvCRC:()=>et,parseEMV:()=>nt,scanQR:()=>Mt});module.exports=_t(jt);var P=class{constructor(e={}){this.settleUntil=0;this.holdUntil=0;this.lostAt=null;this.resetDone=!1;this.sweepIdx=0;this.sweepDir=1;this.lastSweepAt=0;this.settleMs=e.settleMs??380}hold(e,t=3500){this.holdUntil=e+t}settle(e,t=this.settleMs){this.settleUntil=Math.max(this.settleUntil,e+t)}update(e){return e.max<=e.min*1.05||e.now<this.settleUntil||e.now<this.holdUntil?null:e.hint?(this.lostAt=null,this.resetDone=!1,this.follow(e)):this.search(e)}follow(e){let t=e.hint,n=Math.min(e.videoWidth,e.videoHeight),i=t.size/n,s=1;e.decoded?i<.42*.7&&(s=.42/i):(t.module<4&&(s=6/Math.max(.5,t.module)),t.full||(s=Math.min(s,2))),s=Math.min(s,.7/i);let o=Math.abs(t.cx-e.videoWidth/2)+t.size/2,a=Math.abs(t.cy-e.videoHeight/2)+t.size/2;if(s=Math.min(s,e.videoWidth/2/o*.92,e.videoHeight/2/a*.92),s=Math.max(.8,Math.min(3.5,s)),s>.9&&s<1.18)return null;let c=at(e.zoom*s,e.min,e.max);if(Math.abs(c-e.zoom)/e.zoom<.08)return null;let u=e.zoom+(c-e.zoom)*.75;return this.settle(e.now),at(u,e.min,e.max)}search(e){if(this.lostAt===null&&(this.lostAt=e.now),e.now-this.lostAt<700)return null;if(!this.resetDone)return this.resetDone=!0,this.sweepIdx=0,this.sweepDir=1,this.lastSweepAt=e.now,this.settle(e.now,300),e.zoom>e.min*1.05?e.min:null;if(e.now-this.lastSweepAt<700)return null;let t=Pt(e.min,e.max);if(t.length<2)return null;let n=this.sweepIdx+this.sweepDir;return n>=t.length&&(this.sweepDir=-1,n=t.length-2),n<0&&(this.sweepDir=1,n=1),this.sweepIdx=n,this.lastSweepAt=e.now,this.settle(e.now,300),t[n]}};function Pt(r,e){let t=[r];for(let n of[2,3.5,5.5,8,12])n>r*1.4&&n<=e&&t.push(n);return t}function at(r,e,t){return Math.max(e,Math.min(t,r))}var It=null,qt=()=>It??(It=import("./kqrcode.engine.js").then(r=>r.default)),J=class{constructor(){this.idleTimeout=3e4;this.srBackend="off";this.unavailable=!1;this.worker=null;this.starting=null;this.ready=null;this.refs=0;this.idleTimer=0;this.pending=new Map;this.nextId=0}warm(){return this.ensure().then(()=>this.ready??void 0).then(()=>this.scheduleIdle())}async acquire(e){this.refs++,this.clearIdle();let t=await this.ensure();return t?(t.postMessage({type:"config",...e}),!0):(this.refs--,!1)}release(){this.refs=Math.max(0,this.refs-1),this.refs===0&&this.scheduleIdle()}analyze(e,t){let n=this.worker;if(!n)return Promise.resolve(null);let i=++this.nextId;return new Promise(s=>{this.pending.set(i,s),"bitmap"in e?n.postMessage({id:i,bitmap:e.bitmap,opts:t},[e.bitmap]):n.postMessage({id:i,pixels:e.pixels,width:e.width,height:e.height,opts:t},[e.pixels])})}get alive(){return!!this.worker}dispose(){this.clearIdle(),this.worker?.terminate(),this.worker=null,this.starting=null,this.ready=null,this.pending.forEach(e=>e(null)),this.pending.clear()}ensure(){return this.worker?Promise.resolve(this.worker):this.unavailable||typeof Worker>"u"?Promise.resolve(null):this.starting??(this.starting=this.spawn())}async spawn(){try{let e=await qt(),t=URL.createObjectURL(new Blob([e],{type:"text/javascript"})),n=new Worker(t);URL.revokeObjectURL(t);let i;return this.ready=new Promise(s=>i=s),n.onmessage=s=>{let o=s.data;if(o.type==="ready"){o.wasm===!1&&this.fail(),i();return}if(o.type==="config-done"){this.srBackend=o.sr??"off";return}if(o.id===void 0)return;let a=this.pending.get(o.id);this.pending.delete(o.id),o.error==="no-wasm"&&this.fail(),a?.(o.result??null)},n.onerror=()=>{this.fail(),i()},this.worker=n,n}catch{return this.unavailable=!0,null}finally{this.starting=null}}fail(){this.unavailable=!0,this.dispose()}scheduleIdle(){this.clearIdle(),!(this.refs>0||!this.worker)&&(this.idleTimer=setTimeout(()=>{this.refs===0&&this.dispose()},this.idleTimeout))}clearIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=0}},L=new J;var _=class extends Error{constructor(t,n){super(n??t);this.code=t;this.name="ScanError"}},Vt=r=>new Promise(e=>{let t=r;if(t.requestVideoFrameCallback){let n=!1,i=()=>{n||(n=!0,e())};t.requestVideoFrameCallback(i),setTimeout(i,100)}else requestAnimationFrame(()=>e())}),vt=r=>"bitmap"in r?{bitmap:r.bitmap}:{pixels:r.pixels,width:r.width,height:r.height},I=class r{constructor(e){this.listeners={};this.stream=null;this.track=null;this.running=!1;this.paused=!1;this.loopToken=0;this.engine=!1;this.useBitmap=typeof OffscreenCanvas<"u";this.grabCanvas=null;this.native=null;this.frame=0;this.lastHint=null;this.zoomCtl=new P;this.zoomRange={min:1,max:1};this.zoomValue=1;this.digital=!1;this.lastText="";this.lastTextAt=0;this.rejected=new Map;this.lumaEma=128;this.darkState=!1;this.onVisibility=()=>{this.paused=document.hidden,!document.hidden&&this.running&&this.track?.readyState==="ended"&&(this.stop(),this.start().catch(()=>{}))};this.video=e.video,this.opts={facingMode:"environment",autoZoom:!0,maxZoom:8,continuous:!1,maxFrameSide:1920,hiRes:!0,superResolution:"js",onnxRuntimeUrl:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.webgpu.min.js",...e},this.opts.deviceId=e.deviceId}on(e,t){var i;let n=(i=this.listeners)[e]??(i[e]=new Set);return n.add(t),()=>n.delete(t)}emit(e,t){this.listeners[e]?.forEach(n=>n(t))}static preload(){return L.warm()}static dispose(){L.dispose()}static get engineIdleTimeout(){return L.idleTimeout}static set engineIdleTimeout(e){L.idleTimeout=e}static isSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia}get zoom(){return this.zoomValue}get zoomMin(){return this.zoomRange.min}get zoomMax(){return this.zoomRange.max}get canZoom(){return this.zoomRange.max>this.zoomRange.min*1.05}get isDigitalZoom(){return this.digital}get superResolutionBackend(){return L.srBackend}get canTorch(){return!!this.track?.getCapabilities?.()?.torch}async start(){if(this.running)return;if(typeof window<"u"&&window.isSecureContext===!1)throw this.fail(new _("insecure-context","Camera needs HTTPS (or localhost)."));if(!r.isSupported())throw this.fail(new _("unsupported","getUserMedia is not available."));try{let n=this.opts.deviceId?{deviceId:{exact:this.opts.deviceId},width:{ideal:1920},height:{ideal:1080}}:{facingMode:{ideal:this.opts.facingMode},width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}};this.stream=await navigator.mediaDevices.getUserMedia({video:n,audio:!1})}catch(n){throw this.fail(Dt(n))}this.track=this.stream.getVideoTracks()[0];let e=this.video;e.muted=!0,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline",""),e.srcObject=this.stream;try{await e.play()}catch{}await Promise.all([this.tune(),this.setupDetectors()]),document.addEventListener("visibilitychange",this.onVisibility),this.running=!0,this.paused=!1;let t=++this.loopToken;this.loop(t)}stop(){this.running=!1,this.loopToken++,document.removeEventListener("visibilitychange",this.onVisibility),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.track=null,this.video.srcObject=null,this.video.style.transform="",this.releaseEngine(),this.lastHint=null,this.zoomValue=1}pause(){this.paused=!0}resume(){this.paused=!1,this.lastText="",this.rejected.clear()}setFormats(e){this.opts.formats=e?.length?[...e]:void 0,this.setupNative()}setAccept(e){this.opts.accept=e,this.rejected.clear()}async switchCamera(){this.opts.facingMode=this.opts.facingMode==="environment"?"user":"environment",this.opts.deviceId=void 0,this.stop(),await this.start()}async setZoom(e,t=!0){if(!this.track||!this.canZoom)return;let n=Math.max(this.zoomRange.min,Math.min(this.zoomRange.max,e)),i=performance.now();if(t&&this.zoomCtl.hold(i),this.zoomCtl.settle(i,this.digital?90:380),this.zoomValue=n,this.lastHint=null,this.emit("zoom",{zoom:n,min:this.zoomRange.min,max:this.zoomRange.max,auto:!t,digital:this.digital}),!this.digital)try{await this.track.applyConstraints({advanced:[{zoom:n}]})}catch{}}async setTorch(e){if(!this.track||!this.canTorch)return!1;try{return await this.track.applyConstraints({advanced:[{torch:e}]}),!0}catch{return!1}}async focusAt(e,t){if(this.track){this.zoomCtl.settle(performance.now(),600);try{await this.track.applyConstraints({advanced:[{focusMode:"single-shot",pointsOfInterest:[{x:e,y:t}]}]}),setTimeout(()=>{this.track?.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},1500)}catch{}}}async scanImage(e){let t=e instanceof Blob?await createImageBitmap(e):e,n=!this.engine;n&&await this.setupDetectors();try{let i=Math.max(t.width,t.height),s=[...new Set([Math.min(i,1600),Math.min(i,1e3),Math.min(i,2600)])];for(let o of s){let a=o/i,c=Math.max(1,Math.round(t.width*a)),u=Math.max(1,Math.round(t.height*a)),m=document.createElement("canvas");m.width=c,m.height=u;let p=m.getContext("2d",{willReadFrequently:!0});p.fillStyle="#fff",p.fillRect(0,0,c,u),p.drawImage(t,0,0,c,u);let b=p.getImageData(0,0,c,u),f=await this.analyzeFrame({pixels:b.data.buffer,width:c,height:u},{invert:!0,thorough:!0,formats:this.opts.formats});if(f&&f.text!==void 0){let h=yt(f,[],1,"image"),d=await this.check(h);return d===!0?h:(this.emit("reject",{result:h,message:d||void 0}),null)}}return null}finally{e instanceof Blob&&t.close(),n&&!this.running&&this.releaseEngine()}}fail(e){return this.emit("error",e),e}async tune(){let e=this.track,t=e.getCapabilities?.()??{};if(t.zoom&&typeof t.zoom.max=="number")this.digital=!1,this.zoomRange={min:t.zoom.min??1,max:Math.min(t.zoom.max,this.opts.maxZoom)},this.zoomValue=e.getSettings().zoom??this.zoomRange.min,this.zoomCtl=new P({settleMs:380});else{if(this.digital=!0,this.opts.hiRes)try{await e.applyConstraints({width:{ideal:3840},height:{ideal:2160}}),await new Promise(s=>setTimeout(s,250))}catch{}let n=this.video.videoWidth||1920,i=Math.min(this.opts.maxZoom,4,Math.max(1.5,n/960));this.zoomRange={min:1,max:i},this.zoomValue=1,this.zoomCtl=new P({settleMs:120})}if(t.focusMode?.includes("continuous"))try{await e.applyConstraints({advanced:[{focusMode:"continuous"}]})}catch{}this.emit("zoom",{zoom:this.zoomValue,min:this.zoomRange.min,max:this.zoomRange.max,auto:!0,digital:this.digital})}async setupDetectors(){if(this.setupNative(),!this.engine){let e=this.opts.superResolution;this.engine=await L.acquire({sr:e===!1?"off":e,ortUrl:this.opts.onnxRuntimeUrl})}}setupNative(){if(this.native=null,this.opts.formats&&!this.opts.formats.includes("qr_code"))return;let e=globalThis.BarcodeDetector;e&&e.getSupportedFormats().then(t=>{t.includes("qr_code")&&(this.native=new e({formats:["qr_code"]}))}).catch(()=>{})}async check(e){let t=this.opts.accept;if(!t)return!0;try{let n=await t(e);return n===void 0||n===!0?!0:typeof n=="string"?n:!1}catch{return!1}}releaseEngine(){this.engine&&(this.engine=!1,L.release())}async loop(e){for(;this.running&&e===this.loopToken&&(await Vt(this.video),!(!this.running||e!==this.loopToken));)if(!this.paused)try{await this.step()}catch(t){this.running&&e===this.loopToken&&this.emit("error",new _("unknown",String(t))),await new Promise(n=>setTimeout(n,300))}}async grab(e,t,n){let i=this.video;if(this.useBitmap&&this.engine&&L.alive){try{let c=await createImageBitmap(i,e.x,e.y,e.w,e.h,{resizeWidth:t,resizeHeight:n,resizeQuality:"low"});if(Math.abs(c.width-t)<=1)return{bitmap:c,src:c};c.close()}catch{}this.useBitmap=!1}let s=this.grabCanvas??(this.grabCanvas=document.createElement("canvas"));(s.width!==t||s.height!==n)&&(s.width=t,s.height=n);let o=s.getContext("2d",{willReadFrequently:!0});o.drawImage(i,e.x,e.y,e.w,e.h,0,0,t,n);let a=o.getImageData(0,0,t,n);return{pixels:a.data.buffer,width:t,height:n,src:a}}async analyzeFrame(e,t){if(this.engine&&L.alive)return L.analyze(e,t);let[{analyze:n},{jsqrDecoder:i}]=await Promise.all([Promise.resolve().then(()=>(bt(),gt)),import("./kqrcode.jsqr.js")]),s;if("bitmap"in e){let o=document.createElement("canvas");o.width=e.bitmap.width,o.height=e.bitmap.height;let a=o.getContext("2d",{willReadFrequently:!0});a.drawImage(e.bitmap,0,0),e.bitmap.close(),s=a.getImageData(0,0,o.width,o.height)}else s={data:new Uint8ClampedArray(e.pixels),width:e.width,height:e.height};return n(s,t,i)}async step(){let e=this.video;if(e.readyState<2||!e.videoWidth)return;let t=e.videoWidth,n=e.videoHeight,i=performance.now();this.frame++;let s=this.digital?this.zoomValue:1,o={w:t/s,h:n/s,x:0,y:0};o.x=(t-o.w)/2,o.y=(n-o.h)/2;let a=Math.min(1,this.opts.maxFrameSide/Math.max(o.w,o.h)),c=Math.max(2,Math.round(o.w*a)),u=Math.max(2,Math.round(o.h*a)),m=l=>({x:o.x+l.x/a,y:o.y+l.y/a}),p=l=>({cx:(l.cx-o.x)*a,cy:(l.cy-o.y)*a,size:l.size*a,module:l.module*a,full:l.full}),b=await this.grab(o,c,u),f=null;if(this.native)try{let l=await this.native.detect(b.src);if(l.length&&l[0].rawValue){let g=l[0],x=Math.hypot(g.cornerPoints[0].x-g.cornerPoints[1].x,g.cornerPoints[0].y-g.cornerPoints[1].y);f={text:g.rawValue,bytes:new TextEncoder().encode(g.rawValue),corners:g.cornerPoints,hint:{cx:(g.cornerPoints[0].x+g.cornerPoints[2].x)/2,cy:(g.cornerPoints[0].y+g.cornerPoints[2].y)/2,size:x,module:x/25,full:!0},format:"qr_code",version:"",ecLevel:"",luma:128}}}catch{this.native=null}if(f)"bitmap"in b&&b.bitmap.close();else{let l=this.lastHint&&i-this.lastHint.at<700?p(this.lastHint.hint):null;f=await this.analyzeFrame(vt(b),{hint:l,invert:this.frame%6===5,thorough:this.frame%5===0,formats:this.opts.formats})}if(!this.running)return;let h=f?.hint?{cx:o.x+f.hint.cx/a,cy:o.y+f.hint.cy/a,size:f.hint.size/a,module:f.hint.module/a,full:f.hint.full}:null,d=f?.corners?f.corners.map(m):[];if(f&&f.text===void 0&&h&&a<.95&&h.module<5/a){let l=Math.min(Math.max(160,h.size*1.6),Math.min(t,n),1400),g={w:l,h:l,x:Math.max(0,Math.min(t-l,h.cx-l/2)),y:Math.max(0,Math.min(n-l,h.cy-l/2))},x=await this.grab(g,Math.round(l),Math.round(l)),w=Math.min(3,Math.max(1,4/Math.max(1,h.module))),y=await this.analyzeFrame(vt(x),{roiOnly:!0,upscale:w,invert:this.frame%3===0,formats:this.opts.formats});y&&y.text!==void 0&&y.corners&&(f={...y,hint:f.hint,luma:f.luma},d=y.corners.map(M=>({x:g.x+M.x,y:g.y+M.y})))}if(!this.running)return;if(f&&f.luma){this.lumaEma=this.lumaEma*.85+f.luma*.15;let l=this.darkState?this.lumaEma<70:this.lumaEma<45;l!==this.darkState&&(this.darkState=l,this.emit("dark",l))}h&&(this.lastHint={hint:h,at:i});let v=!!f&&f.text!==void 0;if(this.emit("hint",{hint:h,decoded:v,videoWidth:t,videoHeight:n}),this.opts.autoZoom&&this.canZoom&&!v){let l=this.zoomValue,g=h&&this.digital?{cx:(h.cx-t/2)*l+t/2,cy:(h.cy-n/2)*l+n/2,size:h.size*l,module:h.module*l,full:h.full}:h,x=this.zoomCtl.update({now:i,zoom:l,min:this.zoomRange.min,max:this.zoomRange.max,hint:g,decoded:v,videoWidth:t,videoHeight:n});x!==null&&this.setZoom(x,!1)}if(v&&f){let l=f.text;if(this.opts.continuous&&l===this.lastText&&i-this.lastTextAt<1500){this.lastTextAt=i;return}let g=this.rejected.get(l);if(g!==void 0&&i<g){this.rejected.set(l,i+xt);return}let x=yt(f,d,this.zoomValue,"camera"),w=this.loopToken,y=await this.check(x);if(!this.running||w!==this.loopToken)return;if(y!==!0){let M=performance.now();for(let[z,E]of this.rejected)E<M&&this.rejected.delete(z);this.rejected.set(l,M+xt),this.emit("reject",{result:x,message:y||void 0});return}this.lastText=l,this.lastTextAt=performance.now(),this.opts.continuous||(this.paused=!0),this.emit("result",x)}}},xt=2e3;function yt(r,e,t,n){let i=r.text;return{text:i,bytes:r.bytes??new TextEncoder().encode(i),corners:e,format:r.format??"qr_code",version:r.version??"",ecLevel:r.ecLevel??"",zoom:t,timestamp:Date.now(),source:n}}function Dt(r){let e=r?.name;return e==="NotAllowedError"||e==="SecurityError"?new _("permission-denied","Camera permission denied."):e==="NotFoundError"||e==="OverconstrainedError"?new _("no-camera","No camera found."):e==="NotReadableError"||e==="AbortError"?new _("camera-busy","Camera is in use by another app."):new _("unknown",String(r))}var Y=["qr_code","micro_qr_code","rm_qr_code"];var K={en:{hint:"Scan a QR code anywhere in view",zooming:"Zooming in\u2026",dark:"Too dark \u2013 turn on the light",torchOn:"Tap to turn light on",torchOff:"Tap to turn light off",gallery:"Album",noQrInImage:"No QR code found in the image",close:"Close",permission:"Camera permission denied. Please allow camera access.",noCamera:"No camera found on this device.",busy:"The camera is being used by another app.",insecure:"Camera needs HTTPS.",unsupported:"This browser cannot access the camera."},lo:{hint:"\u0EAA\u0EB0\u0EC1\u0E81\u0E99 QR code \u0E9A\u0EC8\u0EAD\u0E99\u0EC3\u0E94\u0E81\u0ECD\u0EC4\u0E94\u0EC9\u0EC3\u0E99\u0E81\u0EC9\u0EAD\u0E87",zooming:"\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E8A\u0EB9\u0EA1\u0EC0\u0E82\u0EBB\u0EC9\u0EB2\u2026",dark:"\u0EA1\u0EB7\u0E94\u0EC0\u0E81\u0EB5\u0E99\u0EC4\u0E9B \u2013 \u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F\u0EAA\u0EB2\u0E8D",torchOn:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F",torchOff:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0E9B\u0EB4\u0E94\u0EC4\u0E9F",gallery:"\u0EAD\u0EB1\u0E99\u0EA5\u0EB0\u0E9A\u0EB1\u0EC9\u0EA1",noQrInImage:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A QR code \u0EC3\u0E99\u0EAE\u0EB9\u0E9A",close:"\u0E9B\u0EB4\u0E94",permission:"\u0E9A\u0ECD\u0EC8\u0EC4\u0E94\u0EC9\u0EAE\u0EB1\u0E9A\u0EAA\u0EB4\u0E94\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87 \u0E81\u0EB0\u0EA5\u0EB8\u0E99\u0EB2\u0EAD\u0EB0\u0E99\u0EB8\u0E8D\u0EB2\u0E94",noCamera:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A\u0E81\u0EC9\u0EAD\u0E87\u0EC3\u0E99\u0EAD\u0EB8\u0E9B\u0EB0\u0E81\u0EAD\u0E99\u0E99\u0EB5\u0EC9",busy:"\u0E81\u0EC9\u0EAD\u0E87\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E96\u0EB7\u0E81\u0EC3\u0E8A\u0EC9\u0EC2\u0E94\u0E8D\u0EC1\u0EAD\u0EB1\u0E9A\u0EAD\u0EB7\u0EC8\u0E99",insecure:"\u0E81\u0EC9\u0EAD\u0E87\u0E95\u0EC9\u0EAD\u0E87\u0EC3\u0E8A\u0EC9 HTTPS",unsupported:"\u0E9A\u0EA3\u0EB2\u0EA7\u0EC0\u0E8A\u0EB5\u0E99\u0EB5\u0EC9\u0E9A\u0ECD\u0EC8\u0EAE\u0EAD\u0E87\u0EAE\u0EB1\u0E9A\u0E81\u0EB2\u0E99\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87"},zh:{hint:"\u626B\u4E8C\u7EF4\u7801 / \u6761\u7801",zooming:"\u6B63\u5728\u653E\u5927\u2026",dark:"\u5149\u7EBF\u592A\u6697",torchOn:"\u8F7B\u89E6\u7167\u4EAE",torchOff:"\u8F7B\u89E6\u5173\u95ED",gallery:"\u76F8\u518C",noQrInImage:"\u672A\u5728\u56FE\u7247\u4E2D\u53D1\u73B0\u4E8C\u7EF4\u7801",close:"\u5173\u95ED",permission:"\u76F8\u673A\u6743\u9650\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u5141\u8BB8\u8BBF\u95EE\u76F8\u673A",noCamera:"\u672A\u627E\u5230\u76F8\u673A",busy:"\u76F8\u673A\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528",insecure:"\u76F8\u673A\u9700\u8981 HTTPS",unsupported:"\u6B64\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u76F8\u673A"}},wt={"--kqr-accent":"scan line / corner colour (theme default: wechat #07c160, alipay #1677ff, frame/grid #1fd17a)","--kqr-success":'colour of the "found it" dot (default: accent)',"--kqr-mask":"dim colour outside the frame (frame theme), default rgba(0,0,0,.45)","--kqr-frame-size":"frame side, default min(70vmin, 300px)","--kqr-frame-top":"vertical centre of the frame, default 42%","--kqr-frame-radius":"default 14px","--kqr-frame-border":"border around the frame, e.g. 1px solid #fff9; default none","--kqr-corner-size":"default 24px","--kqr-corner-width":"default 4px (0 hides the corners)","--kqr-scan-duration":"one sweep, default 2.4s","--kqr-line-width":"scan line thickness, default 3px","--kqr-text":"text colour, default #fff","--kqr-font":"font stack","--kqr-button-bg":"round button background, default rgba(40,40,40,.55)","--kqr-button-size":"default 52px","--kqr-bg":"background behind the video, default #000","--kqr-gallery-bg":'album button background in layout="bar", default: accent',"--kqr-gallery-size":'album button size in layout="bar", default 68px',"--kqr-gallery-radius":'album button corner radius in layout="bar", default 22px'},H={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',torch:'<svg viewBox="0 0 24 24"><path d="M8 2h8l-1.5 6h-5L8 2zm1.5 6h5V13l2 3v6h-9v-6l2-3V8z" fill="currentColor"/></svg>',image:'<svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="3" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="9" cy="10" r="1.8" fill="currentColor"/><path d="M4 18l5.5-5.5 4 4 3-3L21 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>'},Bt=`
|
|
2
2
|
:host{--_accent:var(--kqr-accent,#07c160);--_ok:var(--kqr-success,var(--_accent));--_dur:var(--kqr-scan-duration,2.4s);
|
|
3
3
|
--_fs:var(--kqr-frame-size,min(70vmin,300px));--_ft:var(--kqr-frame-top,42%);--_fr:var(--kqr-frame-radius,14px);
|
|
4
4
|
--_cs:var(--kqr-corner-size,24px);--_cw:var(--kqr-corner-width,4px);--_lw:var(--kqr-line-width,3px);
|
|
@@ -32,7 +32,7 @@ canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
|
|
|
32
32
|
|
|
33
33
|
/* ---------- frame (frame / grid) ---------- */
|
|
34
34
|
.frame{position:absolute;left:50%;top:var(--_ft);width:var(--_fs);aspect-ratio:1;transform:translate(-50%,-50%);
|
|
35
|
-
border-radius:var(--_fr);display:none;overflow:hidden}
|
|
35
|
+
border-radius:var(--_fr);display:none;overflow:hidden;border:var(--kqr-frame-border,none)}
|
|
36
36
|
:host([theme=frame]) .frame,:host([theme=grid]) .frame{display:block}
|
|
37
37
|
:host([theme=frame]) .frame{box-shadow:0 0 0 100vmax var(--kqr-mask,rgba(0,0,0,.45));overflow:visible}
|
|
38
38
|
.frame i{position:absolute;width:var(--_cs);height:var(--_cs);border:0 solid var(--_accent);z-index:1}
|
|
@@ -86,8 +86,21 @@ button:focus-visible{outline:2px solid currentColor;outline-offset:3px;border-ra
|
|
|
86
86
|
.torch{flex-direction:column;gap:4px;font-size:12px;padding:6px 10px}
|
|
87
87
|
.torch .ic{width:44px;height:44px;background:transparent;-webkit-backdrop-filter:none;backdrop-filter:none}
|
|
88
88
|
.torch.on{color:var(--_accent)}
|
|
89
|
-
.actions{display:
|
|
90
|
-
.
|
|
89
|
+
.actions{display:grid;grid-template-columns:1fr auto 1fr;align-items:end;width:100%}
|
|
90
|
+
.cl{justify-self:start;display:flex;gap:12px}.cc{justify-self:center;display:flex;gap:12px}.cr{justify-self:end;display:flex;gap:12px}
|
|
91
|
+
.banner{position:absolute;left:0;right:0;top:calc(max(12px,env(safe-area-inset-top)) + 50px);display:flex;flex-direction:column;
|
|
92
|
+
align-items:center;gap:8px;padding:0 16px;text-align:center;pointer-events:none}
|
|
93
|
+
.banner>*{pointer-events:auto}
|
|
94
|
+
/* layout="bar": one row \u2013 flashlight \xB7 big album button \xB7 your button */
|
|
95
|
+
:host([layout=bar]) .actions{align-items:center}
|
|
96
|
+
:host([layout=bar]) .torch,:host([layout=bar]) .gallery{padding:0}
|
|
97
|
+
:host([layout=bar]) .torch .t,:host([layout=bar]) .gallery .t{display:none}
|
|
98
|
+
:host([layout=bar]) .torch .ic{width:var(--_bs);height:var(--_bs)}
|
|
99
|
+
:host([layout=bar]) .torch .ic svg{width:30px;height:30px}
|
|
100
|
+
:host([layout=bar]) .gallery .ic{width:var(--kqr-gallery-size,68px);height:var(--kqr-gallery-size,68px);
|
|
101
|
+
border-radius:var(--kqr-gallery-radius,22px);background:var(--kqr-gallery-bg,var(--_accent));
|
|
102
|
+
-webkit-backdrop-filter:none;backdrop-filter:none;box-shadow:0 4px 14px rgba(0,0,0,.25)}
|
|
103
|
+
:host([layout=bar]) .gallery .ic svg{width:32px;height:32px}
|
|
91
104
|
.zoom{display:flex;align-items:center;gap:10px;width:min(86vw,340px)}
|
|
92
105
|
.zoom button .ic{width:30px;height:30px}.zoom button .ic svg{width:16px;height:16px}
|
|
93
106
|
.zoom input{flex:1;accent-color:var(--_accent);height:28px;margin:0}
|
|
@@ -101,8 +114,8 @@ button:focus-visible{outline:2px solid currentColor;outline-offset:3px;border-ra
|
|
|
101
114
|
:host([error]) .err{display:grid}
|
|
102
115
|
input[type=file]{display:none}
|
|
103
116
|
@media (prefers-reduced-motion:reduce){.sweep,.scan{animation-duration:6s!important}}
|
|
104
|
-
`,
|
|
105
|
-
<style>${
|
|
117
|
+
`,Ut=typeof HTMLElement>"u"?class{}:HTMLElement,F=class extends Ut{constructor(){super(...arguments);this.labels={};this.scanner=null;this.$={};this.audio=null;this.pointers=new Map;this.pinch=null;this.tapStart=null;this.lastTap=0;this.lastDraw=null;this.torchOn=!1;this.dark=!1;this.dz=1;this.prevOverflow="";this.msgTimer=0;this.stopTimer=0;this.started=!1;this.rejectedAt=-1;this.onResize=()=>this.redraw()}get accept(){return this._accept}set accept(t){this._accept=t,this.scanner?.setAccept(t)}flag(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}attr(t,n){return this.getAttribute(t)??n}get L(){let t=typeof navigator<"u"?navigator.language:"en";return{...K[(this.getAttribute("locale")||t||"en").slice(0,2).toLowerCase()]??K.en,...this.labels}}connectedCallback(){if(window.addEventListener("resize",this.onResize),this.root){this.flag("manual")||this.start();return}this.hasAttribute("theme")||this.setAttribute("theme","wechat"),this.root=this.attachShadow({mode:"open"}),this.root.innerHTML=`
|
|
118
|
+
<style>${Bt}</style>
|
|
106
119
|
<div class="stage" part="stage"><video part="video" muted playsinline></video><canvas part="candidates"></canvas></div>
|
|
107
120
|
<div class="fx" part="effect">
|
|
108
121
|
<div class="sweep" part="scanline"></div>
|
|
@@ -115,6 +128,7 @@ input[type=file]{display:none}
|
|
|
115
128
|
<slot name="top-center"><div class="title" part="title"></div></slot>
|
|
116
129
|
<div class="r"><slot name="top-right"></slot></div>
|
|
117
130
|
</div>
|
|
131
|
+
<div class="banner" part="banner"><slot name="banner"></slot></div>
|
|
118
132
|
<div class="bottom" part="bottom">
|
|
119
133
|
<slot name="hint"><div class="msg" part="hint" role="status" aria-live="polite"></div></slot>
|
|
120
134
|
<button class="torch" part="torch" hidden><span class="ic">${H.torch}</span><span class="t"></span></button>
|
|
@@ -125,11 +139,11 @@ input[type=file]{display:none}
|
|
|
125
139
|
<span class="zl">1.0\xD7</span>
|
|
126
140
|
</div>
|
|
127
141
|
<div class="actions" part="actions">
|
|
128
|
-
<slot name="actions-left"></slot>
|
|
129
|
-
<
|
|
142
|
+
<div class="cell cl"><slot name="actions-left"></slot></div>
|
|
143
|
+
<div class="cell cc"><slot name="actions-center"></slot></div>
|
|
144
|
+
<div class="cell cr"><slot name="actions-right"><button class="gallery" part="gallery"><span class="ic">${H.image}</span><span class="t"></span></button></slot></div>
|
|
130
145
|
</div>
|
|
131
146
|
<slot name="footer"></slot>
|
|
132
147
|
</div>
|
|
133
148
|
<div class="err" part="error" role="alert"><slot name="error"><div class="et"></div></slot></div>
|
|
134
|
-
<input type="file" accept="image/*">`;let t=i=>this.root.querySelector(i);this.$={stage:t(".stage"),ring:t(".ring"),dot:t(".dot"),msg:t(".msg"),title:t(".title"),zoom:t(".zoom"),range:t(".zoom input"),zl:t(".zl"),torch:t(".torch"),gallery:t(".gallery"),file:t("input[type=file]"),err:t(".et"),close:t(".close"),zm:t(".zm"),zp:t(".zp")},this.video=t("video"),this.canvas=t("canvas"),this.applyLabels(),this.$.gallery.hidden=this.flag("no-gallery"),this.$.close.hidden=this.flag("no-close");let n=(i,r,s)=>i.addEventListener(r,s);n(this.$.close,"click",()=>this.close()),n(this.$.gallery,"click",()=>this.pickImage()),n(this.$.file,"change",()=>this.onFile()),n(this.$.torch,"click",()=>this.toggleTorch()),n(this.$.range,"input",()=>this.scanner?.setZoom(parseFloat(this.$.range.value),!0)),n(this.$.zm,"click",()=>this.zoomStep(-1)),n(this.$.zp,"click",()=>this.zoomStep(1)),n(this.$.stage,"pointerdown",i=>this.pdown(i)),n(this.$.stage,"pointermove",i=>this.pmove(i)),n(this.$.stage,"pointerup",i=>this.pup(i)),n(this.$.stage,"pointercancel",i=>{this.pointers.delete(i.pointerId),this.pinch=null}),this.flag("manual")||this.start()}disconnectedCallback(){window.removeEventListener("resize",this.onResize),this.stop()}attributeChangedCallback(t){this.root&&((t==="locale"||t==="heading")&&this.applyLabels(),t==="torch"&&this.updateTorchButton(),t==="formats"&&this.scanner?.setFormats(this.formats),t==="zoom-control"&&this.scanner&&this.onZoom({zoom:this.scanner.zoom,min:this.scanner.zoomMin,max:this.scanner.zoomMax,auto:!1,digital:this.scanner.isDigitalZoom}))}async start(){if(!this.video||this.started)return;this.started=!0,this.hidden=!1,this.removeAttribute("error"),this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.flag("inline")||(this.prevOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",this.flag("request-fullscreen")&&this.requestFullscreen?.().catch(()=>{}));let t=this.getAttribute("super-resolution"),n=this.scanner=new P({video:this.video,facingMode:this.getAttribute("facing")||"environment",autoZoom:!this.flag("no-auto-zoom"),maxZoom:parseFloat(this.getAttribute("max-zoom")||"")||8,continuous:this.flag("continuous"),superResolution:t==="off"||t==="false"?!1:t==="webgpu"?"webgpu":"js",...this.getAttribute("onnx-runtime-url")?{onnxRuntimeUrl:this.getAttribute("onnx-runtime-url")}:{},formats:this.formats,accept:this._accept});n.on("result",i=>this.onResult(i)),n.on("reject",i=>this.onReject(i)),n.on("error",i=>this.onError(i)),n.on("zoom",i=>this.onZoom(i)),n.on("hint",i=>{this.lastDraw={hint:i.hint,decoded:i.decoded,vw:i.videoWidth,vh:i.videoHeight},this.redraw()}),n.on("dark",i=>{this.dark=i,this.updateTorchButton(),i&&!this.torchOn?this.say(this.L.dark,0,!0):this.say(this.L.hint)});try{await n.start(),this.updateTorchButton(),this.say(this.L.hint),this.dispatchEvent(new CustomEvent("ready"))}catch{}}stop(){clearTimeout(this.stopTimer),this.scanner?.stop(),this.scanner=null,this.started&&!this.flag("inline")&&(document.documentElement.style.overflow=this.prevOverflow),this.started=!1,this.torchOn=!1,this.audio&&(this.audio.close().catch(()=>{}),this.audio=null)}close(){this.stop(),this.hidden=!0,this.dispatchEvent(new CustomEvent("close"))}get active(){return this.started}resume(){if(!this.started){this.start();return}this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.video.play().catch(()=>{}),this.scanner?.resume(),this.say(this.L.hint)}pickImage(){this.$.file.click()}async toggleTorch(t=!this.torchOn){return this.scanner&&await this.scanner.setTorch(t)?(this.torchOn=t,this.updateTorchButton(),t&&this.say(this.L.hint),!0):!1}get formats(){let t=this.getAttribute("formats");if(!t)return;let n=t.split(/[\s,]+/).filter(i=>N.includes(i));return n.length?n:void 0}onReject(t){this.rejectedAt=performance.now(),t.message&&this.say(t.message,2500,!0),this.dispatchEvent(new CustomEvent("reject",{detail:t,bubbles:!0,composed:!0}))}onResult(t){this.setAttribute("found","");let n=this.flag("continuous");if(!n&&t.source==="camera"&&this.video.pause(),this.showSuccess(t),!this.flag("no-vibrate"))try{navigator.vibrate?.(40)}catch{}this.flag("no-beep")||this.beep();let i=t.source==="camera"&&this.attr("success","dot")!=="none"?380:0;window.setTimeout(()=>this.dispatchEvent(new CustomEvent("scan",{detail:t,bubbles:!0,composed:!0})),i),!n&&!this.flag("keep-camera")?this.stopTimer=window.setTimeout(()=>this.stop(),i+120):n&&setTimeout(()=>{this.removeAttribute("found"),this.$.dot.classList.remove("go")},900)}showSuccess(t){if(this.attr("success","dot")!=="dot"||!t.corners.length)return;let i=this.mapper();if(!i)return;let r=(t.corners[0].x+t.corners[2].x)/2,s=(t.corners[0].y+t.corners[2].y)/2,a=this.$.dot;a.style.left=i.x(r)+"px",a.style.top=i.y(s)+"px",a.classList.remove("go"),a.offsetWidth,a.classList.add("go")}onError(t){let n=this.L,i={"permission-denied":n.permission,"no-camera":n.noCamera,"camera-busy":n.busy,"insecure-context":n.insecure,unsupported:n.unsupported,unknown:t.message}[t.code];this.$.err.textContent=i,this.setAttribute("error",t.code),this.started=!1,this.dispatchEvent(new CustomEvent("error",{detail:t}))}onZoom(t){this.dz=t.digital?t.zoom:1,this.video.style.transition="transform .14s ease-out",this.video.style.transform=t.digital?`scale(${t.zoom})`:"";let n=this.$.range;n.min=String(t.min),n.max=String(t.max),n.value=String(t.zoom),this.$.zoom.hidden=this.attr("zoom-control","none")!=="slider"||t.max<=t.min*1.05,this.$.zl.textContent=t.zoom.toFixed(1)+"\xD7",t.auto&&t.zoom>t.min*1.05&&this.say(this.L.zooming,1200),this.redraw(),this.dispatchEvent(new CustomEvent("zoom",{detail:t}))}zoomStep(t){let n=this.scanner;n&&n.setZoom(n.zoom+t*Math.max(.5,n.zoomMax/8),!0)}updateTorchButton(){let t=this.flag("no-torch")?"never":this.attr("torch","auto"),i=!!this.scanner?.canTorch&&(t==="always"||t==="auto"&&(this.dark||this.torchOn));this.$.torch.hidden=!i,this.$.torch.classList.toggle("on",this.torchOn),this.$.torch.querySelector(".t").textContent=this.torchOn?this.L.torchOff:this.L.torchOn}async onFile(){let t=this.$.file,n=t.files?.[0];if(t.value="",!n)return;let i=this.scanner?null:new P({video:this.video,formats:this.formats,accept:this._accept});i?.on("reject",a=>this.onReject(a));let r=this.scanner??i,s=performance.now();try{let a=await r.scanImage(n);a?this.onResult(a):this.rejectedAt<s&&this.say(this.L.noQrInImage,2500,!0)}catch{this.say(this.L.noQrInImage,2500,!0)}finally{i?.stop()}}pdown(t){this.$.stage.setPointerCapture?.(t.pointerId),this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pointers.size===1?this.tapStart={x:t.clientX,y:t.clientY,t:performance.now()}:(this.tapStart=null,this.pinch={dist:this.pdist(),zoom:this.scanner?.zoom??1})}pmove(t){this.pointers.has(t.pointerId)&&(this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pinch&&this.pointers.size>=2&&this.scanner&&this.scanner.setZoom(this.pinch.zoom*(this.pdist()/this.pinch.dist),!0))}pup(t){this.pointers.delete(t.pointerId),this.pointers.size<2&&(this.pinch=null);let n=this.tapStart;this.tapStart=null;let i=this.scanner;if(!n||!i||Math.hypot(t.clientX-n.x,t.clientY-n.y)>10||performance.now()-n.t>400)return;let r=performance.now();if(r-this.lastTap<300&&i.canZoom){this.lastTap=0;let d=i.zoom>i.zoomMin*1.3?i.zoomMin:Math.min(i.zoomMax,i.zoomMin*2.5);i.setZoom(d,!0);return}this.lastTap=r;let s=this.getBoundingClientRect(),a=this.$.ring;a.style.left=t.clientX-s.left+"px",a.style.top=t.clientY-s.top+"px",a.classList.remove("go"),a.offsetWidth,a.classList.add("go");let h=this.mapper();h&&i.focusAt(Math.min(1,Math.max(0,h.invX(t.clientX-s.left))),Math.min(1,Math.max(0,h.invY(t.clientY-s.top))))}pdist(){let[t,n]=[...this.pointers.values()];return Math.hypot(t.x-n.x,t.y-n.y)||1}mapper(){let t=this.video;if(!t?.videoWidth)return null;let n=this.clientWidth,i=this.clientHeight,r=Math.max(n/t.videoWidth,i/t.videoHeight),s=(n-t.videoWidth*r)/2,a=(i-t.videoHeight*r)/2,h=this.dz;return{x:d=>(d*r+s-n/2)*h+n/2,y:d=>(d*r+a-i/2)*h+i/2,s:r*h,invX:d=>((d-n/2)/h+n/2-s)/r/t.videoWidth,invY:d=>((d-i/2)/h+i/2-a)/r/t.videoHeight}}redraw(){let t=this.canvas;if(!t)return;let n=window.devicePixelRatio||1,i=this.clientWidth,r=this.clientHeight;(t.width!==Math.round(i*n)||t.height!==Math.round(r*n))&&(t.width=Math.round(i*n),t.height=Math.round(r*n));let s=t.getContext("2d");s.setTransform(n,0,0,n,0,0),s.clearRect(0,0,i,r);let a=this.lastDraw,h=this.mapper();if(!a||!a.hint||!h||this.flag("no-candidates")||a.decoded&&this.attr("success","dot")!=="box")return;let d=h.x(a.hint.cx),f=h.y(a.hint.cy),v=Math.max(18,a.hint.size*h.s/2),g=Math.min(16,v*.5),p=getComputedStyle(this).getPropertyValue("--kqr-accent").trim()||"#fff";s.strokeStyle=a.decoded?p:"rgba(255,255,255,.9)",s.lineWidth=a.decoded?3.5:2.5,s.lineCap="round";for(let[l,m]of[[-1,-1],[1,-1],[1,1],[-1,1]]){let b=d+l*v,c=f+m*v;s.beginPath(),s.moveTo(b-l*g,c),s.lineTo(b,c),s.lineTo(b,c-m*g),s.stroke()}}applyLabels(){let t=this.L,n=this.$.gallery.querySelector(".t");n.textContent=t.gallery,this.$.close.setAttribute("aria-label",t.close),this.$.title.textContent=this.getAttribute("heading")??"",this.updateTorchButton(),this.say(t.hint)}say(t,n=0,i=!1){clearTimeout(this.msgTimer);let r=this.$.msg;r&&(r.textContent=t,r.classList.toggle("warn",i),n&&(this.msgTimer=window.setTimeout(()=>{r.textContent=this.L.hint,r.classList.remove("warn")},n)))}beep(){try{let t=window.AudioContext||window.webkitAudioContext,n=this.audio??(this.audio=new t),i=n.createOscillator(),r=n.createGain();i.type="sine",i.frequency.value=1800,r.gain.setValueAtTime(1e-4,n.currentTime),r.gain.exponentialRampToValueAtTime(.25,n.currentTime+.01),r.gain.exponentialRampToValueAtTime(1e-4,n.currentTime+.12),i.connect(r).connect(n.destination),i.start(),i.stop(n.currentTime+.13)}catch{}}};q.observedAttributes=["locale","heading","torch","zoom-control","formats"];var Q="kqr-scanner";function O(o=Q){typeof customElements<"u"&&!customElements.get(o)&&customElements.define(o,q)}function bt(o={}){return O(),new Promise((e,t)=>{let n=document.createElement(Q),i=(h,d)=>{d===void 0||d===!1||n.setAttribute(h,d===!0?"":String(d))};i("theme",o.theme),i("locale",o.locale),i("heading",o.heading),i("facing",o.facing),i("super-resolution",o.superResolution),i("onnx-runtime-url",o.onnxRuntimeUrl),i("success",o.success),i("torch",o.torch),i("zoom-control",o.zoomControl),i("max-zoom",o.maxZoom),i("inline",o.inline),i("no-gallery",o.gallery===!1),i("no-beep",o.beep===!1),i("no-vibrate",o.vibrate===!1),i("no-auto-zoom",o.autoZoom===!1),i("formats",o.formats?.join(" ")),o.accept&&(n.accept=o.accept),o.labels&&(n.labels=o.labels);for(let[h,d]of Object.entries(o.style??{}))n.style.setProperty(h,d);for(let[h,d]of Object.entries(o.slots??{})){let f;if(typeof d=="string"){let v=document.createElement("div");v.innerHTML=d,f=v}else f=d;if(f instanceof Element)f.setAttribute("slot",h);else{let v=document.createElement("div");v.setAttribute("slot",h),v.appendChild(f),f=v}n.appendChild(f)}let r=!1,s=h=>{r||(r=!0,o.signal?.removeEventListener("abort",a),n.remove(),h())},a=()=>s(()=>t(new DOMException("Scan aborted","AbortError")));if(o.signal?.aborted)return a();o.signal?.addEventListener("abort",a),n.addEventListener("reject",h=>{let d=h.detail;o.onReject?.(d.result,d.message)}),n.addEventListener("scan",h=>s(()=>e(h.detail))),n.addEventListener("close",()=>{r?n.remove():s(()=>t(new DOMException("Scanner closed","AbortError")))}),n.addEventListener("error",h=>{let d=h.detail;r||(r=!0,o.signal?.removeEventListener("abort",a),t(d))}),(o.container??document.body).appendChild(n)})}O();
|
|
135
|
-
//# sourceMappingURL=index.cjs.map
|
|
149
|
+
<input type="file" accept="image/*">`;let t=i=>this.root.querySelector(i);this.$={stage:t(".stage"),ring:t(".ring"),dot:t(".dot"),msg:t(".msg"),title:t(".title"),zoom:t(".zoom"),range:t(".zoom input"),zl:t(".zl"),torch:t(".torch"),gallery:t(".gallery"),file:t("input[type=file]"),err:t(".et"),close:t(".close"),zm:t(".zm"),zp:t(".zp")},this.video=t("video"),this.canvas=t("canvas"),this.applyLabels(),this.placeButtons(),this.$.gallery.hidden=this.flag("no-gallery"),this.$.close.hidden=this.flag("no-close");let n=(i,s,o)=>i.addEventListener(s,o);n(this.$.close,"click",()=>this.close()),n(this.$.gallery,"click",()=>this.pickImage()),n(this.$.file,"change",()=>this.onFile()),n(this.$.torch,"click",()=>this.toggleTorch()),n(this.$.range,"input",()=>this.scanner?.setZoom(parseFloat(this.$.range.value),!0)),n(this.$.zm,"click",()=>this.zoomStep(-1)),n(this.$.zp,"click",()=>this.zoomStep(1)),n(this.$.stage,"pointerdown",i=>this.pdown(i)),n(this.$.stage,"pointermove",i=>this.pmove(i)),n(this.$.stage,"pointerup",i=>this.pup(i)),n(this.$.stage,"pointercancel",i=>{this.pointers.delete(i.pointerId),this.pinch=null}),this.flag("manual")||this.start()}disconnectedCallback(){window.removeEventListener("resize",this.onResize),this.stop()}attributeChangedCallback(t){this.root&&((t==="locale"||t==="heading")&&this.applyLabels(),t==="torch"&&this.updateTorchButton(),t==="layout"&&(this.placeButtons(),this.updateTorchButton()),t==="formats"&&this.scanner?.setFormats(this.formats),t==="zoom-control"&&this.scanner&&this.onZoom({zoom:this.scanner.zoom,min:this.scanner.zoomMin,max:this.scanner.zoomMax,auto:!1,digital:this.scanner.isDigitalZoom}))}async start(){if(!this.video||this.started)return;this.started=!0,this.hidden=!1,this.removeAttribute("error"),this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.flag("inline")||(this.prevOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",this.flag("request-fullscreen")&&this.requestFullscreen?.().catch(()=>{}));let t=this.getAttribute("super-resolution"),n=this.scanner=new I({video:this.video,facingMode:this.getAttribute("facing")||"environment",autoZoom:!this.flag("no-auto-zoom"),maxZoom:parseFloat(this.getAttribute("max-zoom")||"")||8,continuous:this.flag("continuous"),superResolution:t==="off"||t==="false"?!1:t==="webgpu"?"webgpu":"js",...this.getAttribute("onnx-runtime-url")?{onnxRuntimeUrl:this.getAttribute("onnx-runtime-url")}:{},formats:this.formats,accept:this._accept});n.on("result",i=>this.onResult(i)),n.on("reject",i=>this.onReject(i)),n.on("error",i=>this.onError(i)),n.on("zoom",i=>this.onZoom(i)),n.on("hint",i=>{this.lastDraw={hint:i.hint,decoded:i.decoded,vw:i.videoWidth,vh:i.videoHeight},this.redraw()}),n.on("dark",i=>{this.dark=i,this.updateTorchButton(),i&&!this.torchOn?this.say(this.L.dark,0,!0):this.say(this.L.hint)});try{await n.start(),this.updateTorchButton(),this.say(this.L.hint),this.dispatchEvent(new CustomEvent("ready"))}catch{}}stop(){clearTimeout(this.stopTimer),this.scanner?.stop(),this.scanner=null,this.started&&!this.flag("inline")&&(document.documentElement.style.overflow=this.prevOverflow),this.started=!1,this.torchOn=!1,this.audio&&(this.audio.close().catch(()=>{}),this.audio=null)}close(){this.stop(),this.hidden=!0,this.dispatchEvent(new CustomEvent("close"))}get active(){return this.started}resume(){if(!this.started){this.start();return}this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.video.play().catch(()=>{}),this.scanner?.resume(),this.say(this.L.hint)}pickImage(){this.$.file.click()}async toggleTorch(t=!this.torchOn){return this.scanner&&await this.scanner.setTorch(t)?(this.torchOn=t,this.updateTorchButton(),t&&this.say(this.L.hint),!0):!1}get formats(){let t=this.getAttribute("formats");if(!t)return;let n=t.split(/[\s,]+/).filter(i=>Y.includes(i));return n.length?n:void 0}onReject(t){this.rejectedAt=performance.now(),t.message&&this.say(t.message,2500,!0),this.dispatchEvent(new CustomEvent("reject",{detail:t,bubbles:!0,composed:!0}))}onResult(t){this.setAttribute("found","");let n=this.flag("continuous");if(!n&&t.source==="camera"&&this.video.pause(),this.showSuccess(t),!this.flag("no-vibrate"))try{navigator.vibrate?.(40)}catch{}this.flag("no-beep")||this.beep();let i=t.source==="camera"&&this.attr("success","dot")!=="none"?380:0;window.setTimeout(()=>this.dispatchEvent(new CustomEvent("scan",{detail:t,bubbles:!0,composed:!0})),i),!n&&!this.flag("keep-camera")?this.stopTimer=window.setTimeout(()=>this.stop(),i+120):n&&setTimeout(()=>{this.removeAttribute("found"),this.$.dot.classList.remove("go")},900)}showSuccess(t){if(this.attr("success","dot")!=="dot"||!t.corners.length)return;let i=this.mapper();if(!i)return;let s=(t.corners[0].x+t.corners[2].x)/2,o=(t.corners[0].y+t.corners[2].y)/2,a=this.$.dot;a.style.left=i.x(s)+"px",a.style.top=i.y(o)+"px",a.classList.remove("go"),a.offsetWidth,a.classList.add("go")}onError(t){let n=this.L,i={"permission-denied":n.permission,"no-camera":n.noCamera,"camera-busy":n.busy,"insecure-context":n.insecure,unsupported:n.unsupported,unknown:t.message}[t.code];this.$.err.textContent=i,this.setAttribute("error",t.code),this.started=!1,this.dispatchEvent(new CustomEvent("error",{detail:t}))}onZoom(t){this.dz=t.digital?t.zoom:1,this.video.style.transition="transform .14s ease-out",this.video.style.transform=t.digital?`scale(${t.zoom})`:"";let n=this.$.range;n.min=String(t.min),n.max=String(t.max),n.value=String(t.zoom),this.$.zoom.hidden=this.attr("zoom-control","none")!=="slider"||t.max<=t.min*1.05,this.$.zl.textContent=t.zoom.toFixed(1)+"\xD7",t.auto&&t.zoom>t.min*1.05&&this.say(this.L.zooming,1200),this.redraw(),this.dispatchEvent(new CustomEvent("zoom",{detail:t}))}zoomStep(t){let n=this.scanner;n&&n.setZoom(n.zoom+t*Math.max(.5,n.zoomMax/8),!0)}placeButtons(){let t=n=>this.root.querySelector(`slot[name=${n}]`);this.getAttribute("layout")==="bar"?(t("actions-left").append(this.$.torch),t("actions-center").append(this.$.gallery)):(this.$.zoom.before(this.$.torch),t("actions-right").append(this.$.gallery))}updateTorchButton(){let t=this.flag("no-torch")?"never":this.attr("torch","auto"),n=!!this.scanner?.canTorch,i=this.getAttribute("layout")==="bar",s=n&&(t==="always"||t==="auto"&&(i||this.dark||this.torchOn));this.$.torch.hidden=!s,this.$.torch.classList.toggle("on",this.torchOn),this.$.torch.querySelector(".t").textContent=this.torchOn?this.L.torchOff:this.L.torchOn}async onFile(){let t=this.$.file,n=t.files?.[0];if(t.value="",!n)return;let i=this.scanner?null:new I({video:this.video,formats:this.formats,accept:this._accept});i?.on("reject",a=>this.onReject(a));let s=this.scanner??i,o=performance.now();try{let a=await s.scanImage(n);a?this.onResult(a):this.rejectedAt<o&&this.say(this.L.noQrInImage,2500,!0)}catch{this.say(this.L.noQrInImage,2500,!0)}finally{i?.stop()}}pdown(t){this.$.stage.setPointerCapture?.(t.pointerId),this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pointers.size===1?this.tapStart={x:t.clientX,y:t.clientY,t:performance.now()}:(this.tapStart=null,this.pinch={dist:this.pdist(),zoom:this.scanner?.zoom??1})}pmove(t){this.pointers.has(t.pointerId)&&(this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pinch&&this.pointers.size>=2&&this.scanner&&this.scanner.setZoom(this.pinch.zoom*(this.pdist()/this.pinch.dist),!0))}pup(t){this.pointers.delete(t.pointerId),this.pointers.size<2&&(this.pinch=null);let n=this.tapStart;this.tapStart=null;let i=this.scanner;if(!n||!i||Math.hypot(t.clientX-n.x,t.clientY-n.y)>10||performance.now()-n.t>400)return;let s=performance.now();if(s-this.lastTap<300&&i.canZoom){this.lastTap=0;let u=i.zoom>i.zoomMin*1.3?i.zoomMin:Math.min(i.zoomMax,i.zoomMin*2.5);i.setZoom(u,!0);return}this.lastTap=s;let o=this.getBoundingClientRect(),a=this.$.ring;a.style.left=t.clientX-o.left+"px",a.style.top=t.clientY-o.top+"px",a.classList.remove("go"),a.offsetWidth,a.classList.add("go");let c=this.mapper();c&&i.focusAt(Math.min(1,Math.max(0,c.invX(t.clientX-o.left))),Math.min(1,Math.max(0,c.invY(t.clientY-o.top))))}pdist(){let[t,n]=[...this.pointers.values()];return Math.hypot(t.x-n.x,t.y-n.y)||1}mapper(){let t=this.video;if(!t?.videoWidth)return null;let n=this.clientWidth,i=this.clientHeight,s=Math.max(n/t.videoWidth,i/t.videoHeight),o=(n-t.videoWidth*s)/2,a=(i-t.videoHeight*s)/2,c=this.dz;return{x:u=>(u*s+o-n/2)*c+n/2,y:u=>(u*s+a-i/2)*c+i/2,s:s*c,invX:u=>((u-n/2)/c+n/2-o)/s/t.videoWidth,invY:u=>((u-i/2)/c+i/2-a)/s/t.videoHeight}}redraw(){let t=this.canvas;if(!t)return;let n=window.devicePixelRatio||1,i=this.clientWidth,s=this.clientHeight;(t.width!==Math.round(i*n)||t.height!==Math.round(s*n))&&(t.width=Math.round(i*n),t.height=Math.round(s*n));let o=t.getContext("2d");o.setTransform(n,0,0,n,0,0),o.clearRect(0,0,i,s);let a=this.lastDraw,c=this.mapper();if(!a||!a.hint||!c||this.flag("no-candidates")||a.decoded&&this.attr("success","dot")!=="box")return;let u=c.x(a.hint.cx),m=c.y(a.hint.cy),p=Math.max(18,a.hint.size*c.s/2),b=Math.min(16,p*.5),f=getComputedStyle(this).getPropertyValue("--kqr-accent").trim()||"#fff";o.strokeStyle=a.decoded?f:"rgba(255,255,255,.9)",o.lineWidth=a.decoded?3.5:2.5,o.lineCap="round";for(let[h,d]of[[-1,-1],[1,-1],[1,1],[-1,1]]){let v=u+h*p,l=m+d*p;o.beginPath(),o.moveTo(v-h*b,l),o.lineTo(v,l),o.lineTo(v,l-d*b),o.stroke()}}applyLabels(){let t=this.L,n=this.$.gallery.querySelector(".t");n.textContent=t.gallery,this.$.close.setAttribute("aria-label",t.close),this.$.title.textContent=this.getAttribute("heading")??"",this.updateTorchButton(),this.say(t.hint)}say(t,n=0,i=!1){clearTimeout(this.msgTimer);let s=this.$.msg;s&&(s.textContent=t,s.classList.toggle("warn",i),n&&(this.msgTimer=window.setTimeout(()=>{s.textContent=this.L.hint,s.classList.remove("warn")},n)))}beep(){try{let t=window.AudioContext||window.webkitAudioContext,n=this.audio??(this.audio=new t),i=n.createOscillator(),s=n.createGain();i.type="sine",i.frequency.value=1800,s.gain.setValueAtTime(1e-4,n.currentTime),s.gain.exponentialRampToValueAtTime(.25,n.currentTime+.01),s.gain.exponentialRampToValueAtTime(1e-4,n.currentTime+.12),i.connect(s).connect(n.destination),i.start(),i.stop(n.currentTime+.13)}catch{}}};F.observedAttributes=["locale","heading","torch","zoom-control","formats","layout"];var Q="kqr-scanner";function O(r=Q){typeof customElements<"u"&&!customElements.get(r)&&customElements.define(r,F)}function Mt(r={}){return O(),new Promise((e,t)=>{let n=document.createElement(Q),i=(c,u)=>{u===void 0||u===!1||n.setAttribute(c,u===!0?"":String(u))};i("theme",r.theme),i("locale",r.locale),i("heading",r.heading),i("facing",r.facing),i("super-resolution",r.superResolution),i("onnx-runtime-url",r.onnxRuntimeUrl),i("success",r.success),i("torch",r.torch),i("zoom-control",r.zoomControl),i("layout",r.layout),i("max-zoom",r.maxZoom),i("inline",r.inline),i("no-gallery",r.gallery===!1),i("no-beep",r.beep===!1),i("no-vibrate",r.vibrate===!1),i("no-auto-zoom",r.autoZoom===!1),i("formats",r.formats?.join(" ")),r.accept&&(n.accept=r.accept),r.labels&&(n.labels=r.labels);for(let[c,u]of Object.entries(r.style??{}))n.style.setProperty(c,u);for(let[c,u]of Object.entries(r.slots??{})){let m;if(typeof u=="string"){let p=document.createElement("div");p.innerHTML=u,m=p}else m=u;if(m instanceof Element)m.setAttribute("slot",c);else{let p=document.createElement("div");p.setAttribute("slot",c),p.appendChild(m),m=p}n.appendChild(m)}let s=!1,o=c=>{s||(s=!0,r.signal?.removeEventListener("abort",a),n.remove(),c())},a=()=>o(()=>t(new DOMException("Scan aborted","AbortError")));if(r.signal?.aborted)return a();r.signal?.addEventListener("abort",a),n.addEventListener("reject",c=>{let u=c.detail;r.onReject?.(u.result,u.message)}),n.addEventListener("scan",c=>o(()=>e(c.detail))),n.addEventListener("close",()=>{s?n.remove():o(()=>t(new DOMException("Scanner closed","AbortError")))}),n.addEventListener("error",c=>{let u=c.detail;s||(s=!0,r.signal?.removeEventListener("abort",a),t(u))}),(r.container??document.body).appendChild(n)})}var kt={418:"LAK",764:"THB",156:"CNY",840:"USD",704:"VND",116:"KHR",104:"MMK",458:"MYR",702:"SGD",360:"IDR",608:"PHP",356:"INR",344:"HKD",446:"MOP",901:"TWD",392:"JPY",410:"KRW",978:"EUR",826:"GBP","036":"AUD","096":"BND",524:"NPR","050":"BDT",144:"LKR"};function G(r){let e={},t=0;for(;t<r.length;){if(t+4>r.length)return null;let n=r.slice(t,t+2),i=Number(r.slice(t+2,t+4));if(!/^\d\d$/.test(n)||!/^\d\d$/.test(r.slice(t+2,t+4))||t+4+i>r.length)return null;e[n]=r.slice(t+4,t+4+i),t+=4+i}return e}function $t(r){let e=[];for(let t of r){let n=t.codePointAt(0);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):n<65536?e.push(224|n>>12,128|n>>6&63,128|n&63):e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return e}function et(r){let e=65535;for(let t of $t(r)){e^=t<<8;for(let n=0;n<8;n++)e=e&32768?(e<<1^4129)&65535:e<<1&65535}return e.toString(16).toUpperCase().padStart(4,"0")}function nt(r){let e=r.trim();if(!e.startsWith("000201"))return null;let t=G(e);if(!t||t["00"]!=="01")return null;let n=e.lastIndexOf("6304"),i=!!t[63]&&n===e.length-8&&et(e.slice(0,n+4))===t[63].toUpperCase(),s=[];for(let[a,c]of Object.entries(t)){let u=Number(a);if(u>=2&&u<=25)s.push({tag:a,id:c,fields:{}});else if(u>=26&&u<=51){let m=G(c)??{};s.push({tag:a,id:m["00"]??"",fields:m})}}s.sort((a,c)=>Number(a.tag)-Number(c.tag));let o={valid:i,accounts:s,tags:t};if(t["01"]==="11"?o.initiation="static":t["01"]==="12"&&(o.initiation="dynamic"),t[52]&&(o.mcc=t[52]),t[53]&&(o.currency=t[53],kt[t[53]]&&(o.currencyCode=kt[t[53]])),t[54]&&(o.amount=t[54]),t[55]&&(o.tip={indicator:t[55],...t[56]&&{fixed:t[56]},...t[57]&&{percent:t[57]}}),t[58]&&(o.country=t[58]),t[59]&&(o.merchantName=t[59]),t[60]&&(o.merchantCity=t[60]),t[61]&&(o.postalCode=t[61]),t[62]){let a=G(t[62])??{},c=["","billNumber","mobileNumber","storeLabel","loyaltyNumber","referenceLabel","customerLabel","terminalLabel","purpose"],u={fields:a};c.forEach((m,p)=>{let b=a["0"+p];m&&b&&(u[m]=b)}),o.additional=u}if(t[64]){let a=G(t[64])??{};o.language={preference:a["00"],merchantName:a["01"],merchantCity:a["02"]}}return o}var zt=r=>r===void 0?void 0:(Array.isArray(r)?r:[r]).map(e=>e.toUpperCase());function Rt(r={}){let e=r.message??"Not a payment QR code",t=zt(r.currency),n=zt(r.country),i=r.accounts?.map(s=>s.toUpperCase());return s=>{let o=nt(s.text);return!o||!o.valid||t&&!t.includes(o.currency??"")&&!t.includes(o.currencyCode??"")||n&&!n.includes((o.country??"").toUpperCase())||i&&!o.accounts.some(a=>i.includes(a.id.toUpperCase()))||r.dynamicOnly&&o.initiation!=="dynamic"?e:r.check?r.check(o,s):!0}}O();
|
package/dist/index.d.ts
CHANGED
|
@@ -6,5 +6,7 @@ export { scanQR } from './scan-qr';
|
|
|
6
6
|
export type { ScanQROptions } from './scan-qr';
|
|
7
7
|
export type { QRHint, Point } from './engine';
|
|
8
8
|
export { QR_FORMATS, type QRFormat } from './formats';
|
|
9
|
+
export { parseEMV, acceptEMV, emvCRC } from './emv';
|
|
10
|
+
export type { EMVQR, EMVAccount, EMVAdditionalData, AcceptEMVOptions } from './emv';
|
|
9
11
|
export { AutoZoom } from './autozoom';
|
|
10
12
|
export type { SuperRes } from './engine';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
import{a as x,b as S,c as h,d as A,e as M,f as C,g as v,h as p,i as f}from"./chunks/chunk-PUUIGXID.js";function V(t={}){return f(),new Promise((r,e)=>{let n=document.createElement(p),s=(c,o)=>{o===void 0||o===!1||n.setAttribute(c,o===!0?"":String(o))};s("theme",t.theme),s("locale",t.locale),s("heading",t.heading),s("facing",t.facing),s("super-resolution",t.superResolution),s("onnx-runtime-url",t.onnxRuntimeUrl),s("success",t.success),s("torch",t.torch),s("zoom-control",t.zoomControl),s("layout",t.layout),s("max-zoom",t.maxZoom),s("inline",t.inline),s("no-gallery",t.gallery===!1),s("no-beep",t.beep===!1),s("no-vibrate",t.vibrate===!1),s("no-auto-zoom",t.autoZoom===!1),s("formats",t.formats?.join(" ")),t.accept&&(n.accept=t.accept),t.labels&&(n.labels=t.labels);for(let[c,o]of Object.entries(t.style??{}))n.style.setProperty(c,o);for(let[c,o]of Object.entries(t.slots??{})){let u;if(typeof o=="string"){let m=document.createElement("div");m.innerHTML=o,u=m}else u=o;if(u instanceof Element)u.setAttribute("slot",c);else{let m=document.createElement("div");m.setAttribute("slot",c),m.appendChild(u),u=m}n.appendChild(u)}let l=!1,i=c=>{l||(l=!0,t.signal?.removeEventListener("abort",a),n.remove(),c())},a=()=>i(()=>e(new DOMException("Scan aborted","AbortError")));if(t.signal?.aborted)return a();t.signal?.addEventListener("abort",a),n.addEventListener("reject",c=>{let o=c.detail;t.onReject?.(o.result,o.message)}),n.addEventListener("scan",c=>i(()=>r(c.detail))),n.addEventListener("close",()=>{l?n.remove():i(()=>e(new DOMException("Scanner closed","AbortError")))}),n.addEventListener("error",c=>{let o=c.detail;l||(l=!0,t.signal?.removeEventListener("abort",a),e(o))}),(t.container??document.body).appendChild(n)})}var b={418:"LAK",764:"THB",156:"CNY",840:"USD",704:"VND",116:"KHR",104:"MMK",458:"MYR",702:"SGD",360:"IDR",608:"PHP",356:"INR",344:"HKD",446:"MOP",901:"TWD",392:"JPY",410:"KRW",978:"EUR",826:"GBP","036":"AUD","096":"BND",524:"NPR","050":"BDT",144:"LKR"};function d(t){let r={},e=0;for(;e<t.length;){if(e+4>t.length)return null;let n=t.slice(e,e+2),s=Number(t.slice(e+2,e+4));if(!/^\d\d$/.test(n)||!/^\d\d$/.test(t.slice(e+2,e+4))||e+4+s>t.length)return null;r[n]=t.slice(e+4,e+4+s),e+=4+s}return r}function N(t){let r=[];for(let e of t){let n=e.codePointAt(0);n<128?r.push(n):n<2048?r.push(192|n>>6,128|n&63):n<65536?r.push(224|n>>12,128|n>>6&63,128|n&63):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return r}function y(t){let r=65535;for(let e of N(t)){r^=e<<8;for(let n=0;n<8;n++)r=r&32768?(r<<1^4129)&65535:r<<1&65535}return r.toString(16).toUpperCase().padStart(4,"0")}function E(t){let r=t.trim();if(!r.startsWith("000201"))return null;let e=d(r);if(!e||e["00"]!=="01")return null;let n=r.lastIndexOf("6304"),s=!!e[63]&&n===r.length-8&&y(r.slice(0,n+4))===e[63].toUpperCase(),l=[];for(let[a,c]of Object.entries(e)){let o=Number(a);if(o>=2&&o<=25)l.push({tag:a,id:c,fields:{}});else if(o>=26&&o<=51){let u=d(c)??{};l.push({tag:a,id:u["00"]??"",fields:u})}}l.sort((a,c)=>Number(a.tag)-Number(c.tag));let i={valid:s,accounts:l,tags:e};if(e["01"]==="11"?i.initiation="static":e["01"]==="12"&&(i.initiation="dynamic"),e[52]&&(i.mcc=e[52]),e[53]&&(i.currency=e[53],b[e[53]]&&(i.currencyCode=b[e[53]])),e[54]&&(i.amount=e[54]),e[55]&&(i.tip={indicator:e[55],...e[56]&&{fixed:e[56]},...e[57]&&{percent:e[57]}}),e[58]&&(i.country=e[58]),e[59]&&(i.merchantName=e[59]),e[60]&&(i.merchantCity=e[60]),e[61]&&(i.postalCode=e[61]),e[62]){let a=d(e[62])??{},c=["","billNumber","mobileNumber","storeLabel","loyaltyNumber","referenceLabel","customerLabel","terminalLabel","purpose"],o={fields:a};c.forEach((u,m)=>{let g=a["0"+m];u&&g&&(o[u]=g)}),i.additional=o}if(e[64]){let a=d(e[64])??{};i.language={preference:a["00"],merchantName:a["01"],merchantCity:a["02"]}}return i}var R=t=>t===void 0?void 0:(Array.isArray(t)?t:[t]).map(r=>r.toUpperCase());function L(t={}){let r=t.message??"Not a payment QR code",e=R(t.currency),n=R(t.country),s=t.accounts?.map(l=>l.toUpperCase());return l=>{let i=E(l.text);return!i||!i.valid||e&&!e.includes(i.currency??"")&&!e.includes(i.currencyCode??"")||n&&!n.includes((i.country??"").toUpperCase())||s&&!i.accounts.some(a=>s.includes(a.id.toUpperCase()))||t.dynamicOnly&&i.initiation!=="dynamic"?r:t.check?t.check(i,l):!0}}f();export{x as AutoZoom,v as KQRScannerElement,M as LABELS,h as QRScanner,A as QR_FORMATS,S as ScanError,p as TAG_NAME,C as THEME_VARS,L as acceptEMV,f as defineScannerElement,y as emvCRC,E as parseEMV,V as scanQR};
|