mirror of
https://github.com/nimiq/qr-scanner.git
synced 2026-09-22 18:23:54 +00:00
Always create new worker instead of reusing a singleton worker
Create a new worker instance on each call to createQrEngine instead of using a singleton worker instance. Sharing a singleton instance resulted in problems when destroying the worker, for example in a call to QrScanner.scanImage, while it was still needed in a scanner instance or further calls to scanImage.
This commit is contained in:
8 files changed
+63
-62
No files matched your search
Vendored
+2
-2
@@ -1,4 +1,4 @@
|
||||
export default new Worker(URL.createObjectURL(new Blob([`class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;f<b+d;f++)for(let g=a;g<a+c;g++)this.set(g,f,!!e)}}
|
||||
export const createWorker=()=>new Worker(URL.createObjectURL(new Blob([`class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;f<b+d;f++)for(let g=a;g<a+c;g++)this.set(g,f,!!e)}}
|
||||
class A{constructor(a,b,c){this.width=a;a*=b;if(c&&c.length!==a)throw Error("Wrong buffer size");this.data=c||new Uint8ClampedArray(a)}get(a,b){return this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c}}
|
||||
class ba{constructor(a){this.bitOffset=this.byteOffset=0;this.bytes=a}readBits(a){if(1>a||32<a||a>this.available())throw Error("Cannot read "+a.toString()+" bits");var b=0;if(0<this.bitOffset){b=8-this.bitOffset;var c=a<b?a:b;b-=c;b=(this.bytes[this.byteOffset]&255>>8-c<<b)>>b;a-=c;this.bitOffset+=c;8===this.bitOffset&&(this.bitOffset=0,this.byteOffset++)}if(0<a){for(;8<=a;)b=b<<8|this.bytes[this.byteOffset]&255,this.byteOffset++,a-=8;0<a&&(c=8-a,b=b<<a|(this.bytes[this.byteOffset]&255>>c<<c)>>c,
|
||||
this.bitOffset+=a)}return b}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var B,C=B||(B={});C.Numeric="numeric";C.Alphanumeric="alphanumeric";C.Byte="byte";C.Kanji="kanji";C.ECI="eci";C.StructuredAppend="structuredappend";var D,E=D||(D={});E[E.Terminator=0]="Terminator";E[E.Numeric=1]="Numeric";E[E.Alphanumeric=2]="Alphanumeric";E[E.Byte=4]="Byte";E[E.Kanji=8]="Kanji";E[E.ECI=7]="ECI";E[E.StructuredAppend=3]="StructuredAppend";let F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split("");
|
||||
@@ -95,4 +95,4 @@ u.set(r,q,v)}h?(q=new Uint8ClampedArray(a.buffer,m,k),m+=k,q=new x(q,b)):q=x.cre
|
||||
y:z))||"attemptBoth"!==e.inversionAttempts&&"invertFirst"!==e.inversionAttempts||(f=V(d?z:y));return f}X.default=X;let Y="dontInvert",Z={red:77,green:150,blue:29,useIntegerApproximation:!0};
|
||||
self.onmessage=a=>{let b=a.data.data;switch(a.data.type){case "decode":(a=X(b.data,b.width,b.height,{inversionAttempts:Y,greyScaleWeights:Z}))?self.postMessage({type:"qrResult",data:a.data,cornerPoints:[a.location.topLeftCorner,a.location.topRightCorner,a.location.bottomRightCorner,a.location.bottomLeftCorner]}):self.postMessage({type:"qrResult",data:null});break;case "grayscaleWeights":Z.red=b.red;Z.green=b.green;Z.blue=b.blue;Z.useIntegerApproximation=b.useIntegerApproximation;break;case "inversionMode":switch(b){case "original":Y=
|
||||
"dontInvert";break;case "invert":Y="onlyInvert";break;case "both":Y="attemptBoth";break;default:throw Error("Invalid inversion mode");}break;case "close":self.close()}}
|
||||
`]),{type: "application/javascript"}))//# sourceMappingURL=qr-scanner-worker.min.js.map
|
||||
`]),{type:"application/javascript"}))//# sourceMappingURL=qr-scanner-worker.min.js.map
|
||||
Vendored
+53
-53
@@ -1,55 +1,55 @@
|
||||
'use strict';var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(b,d,g){if(b==Array.prototype||b==Object.prototype)return b;b[d]=g.value;return b};
|
||||
$jscomp.getGlobal=function(b){b=["object"==typeof globalThis&&globalThis,b,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var d=0;d<b.length;++d){var g=b[d];if(g&&g.Math==Math)return g}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};
|
||||
$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(b,d){var g=$jscomp.propertyToPolyfillSymbol[d];if(null==g)return b[d];g=b[g];return void 0!==g?g:b[d]};$jscomp.polyfill=function(b,d,g,a){d&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(b,d,g,a):$jscomp.polyfillUnisolated(b,d,g,a))};
|
||||
$jscomp.polyfillUnisolated=function(b,d,g,a){g=$jscomp.global;b=b.split(".");for(a=0;a<b.length-1;a++){var c=b[a];if(!(c in g))return;g=g[c]}b=b[b.length-1];a=g[b];d=d(a);d!=a&&null!=d&&$jscomp.defineProperty(g,b,{configurable:!0,writable:!0,value:d})};
|
||||
$jscomp.polyfillIsolated=function(b,d,g,a){var c=b.split(".");b=1===c.length;a=c[0];a=!b&&a in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var e=0;e<c.length-1;e++){var f=c[e];if(!(f in a))return;a=a[f]}c=c[c.length-1];g=$jscomp.IS_SYMBOL_NATIVE&&"es6"===g?a[c]:null;d=d(g);null!=d&&(b?$jscomp.defineProperty($jscomp.polyfills,c,{configurable:!0,writable:!0,value:d}):d!==g&&(void 0===$jscomp.propertyToPolyfillSymbol[c]&&(g=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[c]=$jscomp.IS_SYMBOL_NATIVE?
|
||||
$jscomp.global.Symbol(c):$jscomp.POLYFILL_PREFIX+g+"$"+c),$jscomp.defineProperty(a,$jscomp.propertyToPolyfillSymbol[c],{configurable:!0,writable:!0,value:d})))};$jscomp.underscoreProtoCanBeSet=function(){var b={a:!0},d={};try{return d.__proto__=b,d.a}catch(g){}return!1};
|
||||
$jscomp.setPrototypeOf=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:$jscomp.underscoreProtoCanBeSet()?function(b,d){b.__proto__=d;if(b.__proto__!==d)throw new TypeError(b+" is not extensible");return b}:null;$jscomp.arrayIteratorImpl=function(b){var d=0;return function(){return d<b.length?{done:!1,value:b[d++]}:{done:!0}}};$jscomp.arrayIterator=function(b){return{next:$jscomp.arrayIteratorImpl(b)}};
|
||||
$jscomp.makeIterator=function(b){var d="undefined"!=typeof Symbol&&Symbol.iterator&&b[Symbol.iterator];return d?d.call(b):$jscomp.arrayIterator(b)};$jscomp.generator={};$jscomp.generator.ensureIteratorResultIsObject_=function(b){if(!(b instanceof Object))throw new TypeError("Iterator result "+b+" is not an object");};
|
||||
'use strict';var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(c,e,a){if(c==Array.prototype||c==Object.prototype)return c;c[e]=a.value;return c};
|
||||
$jscomp.getGlobal=function(c){c=["object"==typeof globalThis&&globalThis,c,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var e=0;e<c.length;++e){var a=c[e];if(a&&a.Math==Math)return a}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};
|
||||
$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(c,e){var a=$jscomp.propertyToPolyfillSymbol[e];if(null==a)return c[e];a=c[a];return void 0!==a?a:c[e]};$jscomp.polyfill=function(c,e,a,b){e&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(c,e,a,b):$jscomp.polyfillUnisolated(c,e,a,b))};
|
||||
$jscomp.polyfillUnisolated=function(c,e,a,b){a=$jscomp.global;c=c.split(".");for(b=0;b<c.length-1;b++){var d=c[b];if(!(d in a))return;a=a[d]}c=c[c.length-1];b=a[c];e=e(b);e!=b&&null!=e&&$jscomp.defineProperty(a,c,{configurable:!0,writable:!0,value:e})};
|
||||
$jscomp.polyfillIsolated=function(c,e,a,b){var d=c.split(".");c=1===d.length;b=d[0];b=!c&&b in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var f=0;f<d.length-1;f++){var g=d[f];if(!(g in b))return;b=b[g]}d=d[d.length-1];a=$jscomp.IS_SYMBOL_NATIVE&&"es6"===a?b[d]:null;e=e(a);null!=e&&(c?$jscomp.defineProperty($jscomp.polyfills,d,{configurable:!0,writable:!0,value:e}):e!==a&&(void 0===$jscomp.propertyToPolyfillSymbol[d]&&(a=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[d]=$jscomp.IS_SYMBOL_NATIVE?
|
||||
$jscomp.global.Symbol(d):$jscomp.POLYFILL_PREFIX+a+"$"+d),$jscomp.defineProperty(b,$jscomp.propertyToPolyfillSymbol[d],{configurable:!0,writable:!0,value:e})))};$jscomp.underscoreProtoCanBeSet=function(){var c={a:!0},e={};try{return e.__proto__=c,e.a}catch(a){}return!1};
|
||||
$jscomp.setPrototypeOf=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:$jscomp.underscoreProtoCanBeSet()?function(c,e){c.__proto__=e;if(c.__proto__!==e)throw new TypeError(c+" is not extensible");return c}:null;$jscomp.arrayIteratorImpl=function(c){var e=0;return function(){return e<c.length?{done:!1,value:c[e++]}:{done:!0}}};$jscomp.arrayIterator=function(c){return{next:$jscomp.arrayIteratorImpl(c)}};
|
||||
$jscomp.makeIterator=function(c){var e="undefined"!=typeof Symbol&&Symbol.iterator&&c[Symbol.iterator];return e?e.call(c):$jscomp.arrayIterator(c)};$jscomp.generator={};$jscomp.generator.ensureIteratorResultIsObject_=function(c){if(!(c instanceof Object))throw new TypeError("Iterator result "+c+" is not an object");};
|
||||
$jscomp.generator.Context=function(){this.isRunning_=!1;this.yieldAllIterator_=null;this.yieldResult=void 0;this.nextAddress=1;this.finallyAddress_=this.catchAddress_=0;this.finallyContexts_=this.abruptCompletion_=null};$jscomp.generator.Context.prototype.start_=function(){if(this.isRunning_)throw new TypeError("Generator is already running");this.isRunning_=!0};$jscomp.generator.Context.prototype.stop_=function(){this.isRunning_=!1};
|
||||
$jscomp.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_};$jscomp.generator.Context.prototype.next_=function(b){this.yieldResult=b};$jscomp.generator.Context.prototype.throw_=function(b){this.abruptCompletion_={exception:b,isException:!0};this.jumpToErrorHandler_()};$jscomp.generator.Context.prototype.return=function(b){this.abruptCompletion_={return:b};this.nextAddress=this.finallyAddress_};
|
||||
$jscomp.generator.Context.prototype.jumpThroughFinallyBlocks=function(b){this.abruptCompletion_={jumpTo:b};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.yield=function(b,d){this.nextAddress=d;return{value:b}};$jscomp.generator.Context.prototype.yieldAll=function(b,d){b=$jscomp.makeIterator(b);var g=b.next();$jscomp.generator.ensureIteratorResultIsObject_(g);if(g.done)this.yieldResult=g.value,this.nextAddress=d;else return this.yieldAllIterator_=b,this.yield(g.value,d)};
|
||||
$jscomp.generator.Context.prototype.jumpTo=function(b){this.nextAddress=b};$jscomp.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0};$jscomp.generator.Context.prototype.setCatchFinallyBlocks=function(b,d){this.catchAddress_=b;void 0!=d&&(this.finallyAddress_=d)};$jscomp.generator.Context.prototype.setFinallyBlock=function(b){this.catchAddress_=0;this.finallyAddress_=b||0};$jscomp.generator.Context.prototype.leaveTryBlock=function(b,d){this.nextAddress=b;this.catchAddress_=d||0};
|
||||
$jscomp.generator.Context.prototype.enterCatchBlock=function(b){this.catchAddress_=b||0;b=this.abruptCompletion_.exception;this.abruptCompletion_=null;return b};$jscomp.generator.Context.prototype.enterFinallyBlock=function(b,d,g){g?this.finallyContexts_[g]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_];this.catchAddress_=b||0;this.finallyAddress_=d||0};
|
||||
$jscomp.generator.Context.prototype.leaveFinallyBlock=function(b,d){d=this.finallyContexts_.splice(d||0)[0];if(d=this.abruptCompletion_=this.abruptCompletion_||d){if(d.isException)return this.jumpToErrorHandler_();void 0!=d.jumpTo&&this.finallyAddress_<d.jumpTo?(this.nextAddress=d.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=b};$jscomp.generator.Context.prototype.forIn=function(b){return new $jscomp.generator.Context.PropertyIterator(b)};
|
||||
$jscomp.generator.Context.PropertyIterator=function(b){this.object_=b;this.properties_=[];for(var d in b)this.properties_.push(d);this.properties_.reverse()};$jscomp.generator.Context.PropertyIterator.prototype.getNext=function(){for(;0<this.properties_.length;){var b=this.properties_.pop();if(b in this.object_)return b}return null};$jscomp.generator.Engine_=function(b){this.context_=new $jscomp.generator.Context;this.program_=b};
|
||||
$jscomp.generator.Engine_.prototype.next_=function(b){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_.next,b,this.context_.next_);this.context_.next_(b);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.return_=function(b){this.context_.start_();var d=this.context_.yieldAllIterator_;if(d)return this.yieldAllStep_("return"in d?d["return"]:function(g){return{value:g,done:!0}},b,this.context_.return);this.context_.return(b);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.throw_=function(b){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_["throw"],b,this.context_.next_);this.context_.throw_(b);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.yieldAllStep_=function(b,d,g){try{var a=b.call(this.context_.yieldAllIterator_,d);$jscomp.generator.ensureIteratorResultIsObject_(a);if(!a.done)return this.context_.stop_(),a;var c=a.value}catch(e){return this.context_.yieldAllIterator_=null,this.context_.throw_(e),this.nextStep_()}this.context_.yieldAllIterator_=null;g.call(this.context_,c);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var b=this.program_(this.context_);if(b)return this.context_.stop_(),{value:b.value,done:!1}}catch(d){this.context_.yieldResult=void 0,this.context_.throw_(d)}this.context_.stop_();if(this.context_.abruptCompletion_){b=this.context_.abruptCompletion_;this.context_.abruptCompletion_=null;if(b.isException)throw b.exception;return{value:b.return,done:!0}}return{value:void 0,done:!0}};
|
||||
$jscomp.generator.Generator_=function(b){this.next=function(d){return b.next_(d)};this.throw=function(d){return b.throw_(d)};this.return=function(d){return b.return_(d)};this[Symbol.iterator]=function(){return this}};$jscomp.generator.createGenerator=function(b,d){d=new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(d));$jscomp.setPrototypeOf&&b.prototype&&$jscomp.setPrototypeOf(d,b.prototype);return d};
|
||||
$jscomp.asyncExecutePromiseGenerator=function(b){function d(a){return b.next(a)}function g(a){return b.throw(a)}return new Promise(function(a,c){function e(f){f.done?a(f.value):Promise.resolve(f.value).then(d,g).then(e,c)}e(b.next())})};$jscomp.asyncExecutePromiseGeneratorFunction=function(b){return $jscomp.asyncExecutePromiseGenerator(b())};$jscomp.asyncExecutePromiseGeneratorProgram=function(b){return $jscomp.asyncExecutePromiseGenerator(new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(b)))};
|
||||
(function(b,d){"object"===typeof exports&&"undefined"!==typeof module?module.exports=d():"function"===typeof define&&define.amd?define(d):(b="undefined"!==typeof globalThis?globalThis:b||self,b.QrScanner=d())})(this,function(){class b{constructor(a,c,e,f,h){this._legacyCanvasSize=b.DEFAULT_CANVAS_SIZE;this._preferredCamera="environment";this._maxScansPerSecond=25;this._lastScanTimestamp=-1;this._destroyed=this._flashOn=this._paused=this._active=!1;this.$video=a;this.$canvas=document.createElement("canvas");
|
||||
e&&"object"===typeof e?this._onDecode=c:(e||f||h?console.warn("You're using a deprecated version of the QrScanner constructor which will be removed in the future"):console.warn("Note that the type of the scan result passed to onDecode will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),this._legacyOnDecode=c);c="object"===typeof e?e:{};this._onDecodeError=c.onDecodeError||("function"===typeof e?e:this._onDecodeError);this._calculateScanRegion=
|
||||
c.calculateScanRegion||("function"===typeof f?f:this._calculateScanRegion);this._preferredCamera=c.preferredCamera||h||this._preferredCamera;this._legacyCanvasSize="number"===typeof e?e:"number"===typeof f?f:this._legacyCanvasSize;this._maxScansPerSecond=c.maxScansPerSecond||this._maxScansPerSecond;this._onPlay=this._onPlay.bind(this);this._onLoadedMetaData=this._onLoadedMetaData.bind(this);this._onVisibilityChange=this._onVisibilityChange.bind(this);this._updateOverlay=this._updateOverlay.bind(this);
|
||||
a.disablePictureInPicture=!0;a.playsInline=!0;a.muted=!0;let l=!1;a.hidden&&(a.hidden=!1,l=!0);document.body.contains(a)||(document.body.appendChild(a),l=!0);e=a.parentElement;if(c.highlightScanRegion||c.highlightCodeOutline){f=!!c.overlay;this.$overlay=c.overlay||document.createElement("div");h=this.$overlay.style;h.position="absolute";h.display="none";h.pointerEvents="none";this.$overlay.classList.add("scan-region-highlight");if(!f&&c.highlightScanRegion){this.$overlay.innerHTML='<svg class="scan-region-highlight-svg" viewBox="0 0 238 238" preserveAspectRatio="none" style="position:absolute;width:100%;height:100%;left:0;top:0;fill:none;stroke:#e9b213;stroke-width:4;stroke-linecap:round;stroke-linejoin:round"><path d="M31 2H10a8 8 0 0 0-8 8v21M207 2h21a8 8 0 0 1 8 8v21m0 176v21a8 8 0 0 1-8 8h-21m-176 0H10a8 8 0 0 1-8-8v-21"/></svg>';
|
||||
try{this.$overlay.firstElementChild.animate({transform:["scale(.98)","scale(1.01)"]},{duration:400,iterations:Infinity,direction:"alternate",easing:"ease-in-out"})}catch(m){}e.insertBefore(this.$overlay,this.$video.nextSibling)}c.highlightCodeOutline&&(this.$overlay.insertAdjacentHTML("beforeend",'<svg class="code-outline-highlight" preserveAspectRatio="none" style="display:none;width:100%;height:100%;fill:none;stroke:#e9b213;stroke-width:5;stroke-dasharray:25;stroke-linecap:round;stroke-linejoin:round"><polygon/></svg>'),
|
||||
this.$codeOutlineHighlight=this.$overlay.lastElementChild)}this._scanRegion=this._calculateScanRegion(a);requestAnimationFrame(()=>{let m=window.getComputedStyle(a);"none"===m.display&&(a.style.setProperty("display","block","important"),l=!0);"visible"!==m.visibility&&(a.style.setProperty("visibility","visible","important"),l=!0);l&&(console.warn("QrScanner has overwritten the video hiding style to avoid Safari stopping the playback."),a.style.opacity="0",a.style.width="0",a.style.height="0",this.$overlay&&
|
||||
this.$overlay.parentElement&&this.$overlay.parentElement.removeChild(this.$overlay),delete this.$overlay,delete this.$codeOutlineHighlight);this.$overlay&&this._updateOverlay()});a.addEventListener("play",this._onPlay);a.addEventListener("loadedmetadata",this._onLoadedMetaData);document.addEventListener("visibilitychange",this._onVisibilityChange);window.addEventListener("resize",this._updateOverlay);this._qrEnginePromise=b.createQrEngine()}static set WORKER_PATH(a){console.warn("Setting QrScanner.WORKER_PATH is not required and not supported anymore. Have a look at the README for new setup instructions.")}static hasCamera(){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){try{return!!(yield b.listCameras(!1)).length}catch(a){return!1}})}static listCameras(a=
|
||||
!1){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!navigator.mediaDevices)return[];let c=()=>$jscomp.asyncExecutePromiseGeneratorFunction(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(f=>"videoinput"===f.kind)}),e;try{a&&(yield c()).every(f=>!f.label)&&(e=yield navigator.mediaDevices.getUserMedia({audio:!1,video:!0}))}catch(f){}try{return(yield c()).map((f,h)=>({id:f.deviceId,label:f.label||(0===h?"Default Camera":`Camera ${h+1}`)}))}finally{e&&(console.warn("Call listCameras after successfully starting a QR scanner to avoid creating a temporary video stream"),
|
||||
b._stopVideoStream(e))}})}hasFlash(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let c;try{if(a.$video.srcObject){if(!(a.$video.srcObject instanceof MediaStream))return!1;c=a.$video.srcObject}else c=(yield a._getCameraStream()).stream;return"torch"in c.getVideoTracks()[0].getSettings()}catch(e){return!1}finally{c&&c!==a.$video.srcObject&&(console.warn("Call hasFlash after successfully starting the scanner to avoid creating a temporary video stream"),b._stopVideoStream(c))}})}isFlashOn(){return this._flashOn}toggleFlash(){const a=
|
||||
this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a._flashOn?yield a.turnFlashOff():yield a.turnFlashOn()})}turnFlashOn(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!a._flashOn&&!a._destroyed&&(a._flashOn=!0,a._active&&!a._paused))try{if(!(yield a.hasFlash()))throw"No flash available";yield a.$video.srcObject.getVideoTracks()[0].applyConstraints({advanced:[{torch:!0}]})}catch(c){throw a._flashOn=!1,c;}})}turnFlashOff(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a._flashOn&&
|
||||
(a._flashOn=!1,yield a._restartVideoStream())})}destroy(){this.$video.removeEventListener("loadedmetadata",this._onLoadedMetaData);this.$video.removeEventListener("play",this._onPlay);document.removeEventListener("visibilitychange",this._onVisibilityChange);window.removeEventListener("resize",this._updateOverlay);this._destroyed=!0;this._flashOn=!1;this.stop();b._postWorkerMessage(this._qrEnginePromise,"close")}start(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(a._destroyed)throw Error("The QR scanner can not be started as it had been destroyed.");
|
||||
if(!a._active||a._paused)if("https:"!==window.location.protocol&&console.warn("The camera stream is only accessible if the page is transferred via https."),a._active=!0,!document.hidden)if(a._paused=!1,a.$video.srcObject)yield a.$video.play();else try{let {stream:c,facingMode:e}=yield a._getCameraStream();!a._active||a._paused?b._stopVideoStream(c):(a._setVideoMirror(e),a.$video.srcObject=c,yield a.$video.play(),a._flashOn&&(a._flashOn=!1,a.turnFlashOn().catch(()=>{})))}catch(c){if(!a._paused)throw a._active=
|
||||
!1,c;}})}stop(){this.pause();this._active=!1}pause(a=!1){const c=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){c._paused=!0;if(!c._active)return!0;c.$video.pause();c.$overlay&&(c.$overlay.style.display="none");let e=()=>{c.$video.srcObject instanceof MediaStream&&(b._stopVideoStream(c.$video.srcObject),c.$video.srcObject=null)};if(a)return e(),!0;yield new Promise(f=>setTimeout(f,300));if(!c._paused)return!1;e();return!0})}setCamera(a){const c=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a!==
|
||||
c._preferredCamera&&(c._preferredCamera=a,yield c._restartVideoStream())})}static scanImage(a,c,e,f,h=!1,l=!1){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let m,q=!1;c&&("scanRegion"in c||"qrEngine"in c||"canvas"in c||"disallowCanvasResizing"in c||"alsoTryWithoutScanRegion"in c||"returnDetailedScanResult"in c)?(m=c.scanRegion,e=c.qrEngine,f=c.canvas,h=c.disallowCanvasResizing||!1,l=c.alsoTryWithoutScanRegion||!1,q=!0):c||e||f||h||l?console.warn("You're using a deprecated api for scanImage which will be removed in the future."):
|
||||
console.warn("Note that the return type of scanImage will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true.");let t=!!e;try{let n,r;[e,n]=yield Promise.all([e||b.createQrEngine(),b._loadImage(a)]);[f,r]=b._drawToCanvas(n,m,f,h);let p;if(e instanceof Worker){let k=e;t||k.postMessage({type:"inversionMode",data:"both"});p=yield new Promise((u,A)=>{let y,w,x;w=v=>{"qrResult"===v.data.type&&(k.removeEventListener("message",w),k.removeEventListener("error",
|
||||
x),clearTimeout(y),null!==v.data.data?u({data:v.data.data,cornerPoints:b._convertPoints(v.data.cornerPoints,m)}):A(b.NO_QR_CODE_FOUND))};x=v=>{k.removeEventListener("message",w);k.removeEventListener("error",x);clearTimeout(y);A("Scanner error: "+(v?v.message||v:"Unknown Error"))};k.addEventListener("message",w);k.addEventListener("error",x);y=setTimeout(()=>x("timeout"),1E4);let z=r.getImageData(0,0,f.width,f.height);k.postMessage({type:"decode",data:z},[z.data.buffer])})}else p=yield Promise.race([new Promise((k,
|
||||
u)=>window.setTimeout(()=>u("Scanner error: timeout"),1E4)),(()=>$jscomp.asyncExecutePromiseGeneratorFunction(function*(){try{var [k]=yield e.detect(f);if(!k)throw b.NO_QR_CODE_FOUND;return{data:k.rawValue,cornerPoints:b._convertPoints(k.cornerPoints,m)}}catch(u){k=u.message||u;if(/not implemented|service unavailable/.test(k))return b._disableBarcodeDetector=!0,b.scanImage(a,{scanRegion:m,canvas:f,disallowCanvasResizing:h,alsoTryWithoutScanRegion:l});throw`Scanner error: ${k}`;}}))()]);return q?p:
|
||||
p.data}catch(n){if(!m||!l)throw n;let r=yield b.scanImage(a,{qrEngine:e,canvas:f,disallowCanvasResizing:h});return q?r:r.data}finally{t||b._postWorkerMessage(e,"close")}})}setGrayscaleWeights(a,c,e,f=!0){b._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:a,green:c,blue:e,useIntegerApproximation:f})}setInversionMode(a){b._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static createQrEngine(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a&&console.warn("Specifying a worker path is not required and not supported anymore.");
|
||||
return!b._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(yield BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):Promise.resolve().then(function(){return g}).then(c=>c.default)})}_onPlay(){this._scanRegion=this._calculateScanRegion(this.$video);this._updateOverlay();this.$overlay&&(this.$overlay.style.display="");this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video);
|
||||
this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(a){let c=Math.round(2/3*Math.min(a.videoWidth,a.videoHeight));return{x:Math.round((a.videoWidth-c)/2),y:Math.round((a.videoHeight-c)/2),width:c,height:c,downScaledWidth:this._legacyCanvasSize,downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var a=this.$video,c=a.videoWidth,e=a.videoHeight,f=a.offsetWidth,h=a.offsetHeight,l=a.offsetLeft,
|
||||
m=a.offsetTop,q=window.getComputedStyle(a),t=q.objectFit,n=c/e,r=f/h;switch(t){case "none":var p=c;var k=e;break;case "fill":p=f;k=h;break;default:("cover"===t?n>r:n<r)?(k=h,p=k*n):(p=f,k=p/n),"scale-down"===t&&(p=Math.min(p,c),k=Math.min(k,e))}var [u,A]=q.objectPosition.split(" ").map((w,x)=>{const z=parseFloat(w);return w.endsWith("%")?(x?h-k:f-p)*z/100:z});q=this._scanRegion.width||c;r=this._scanRegion.height||e;t=this._scanRegion.x||0;var y=this._scanRegion.y||0;n=this.$overlay.style;n.width=
|
||||
`${q/c*p}px`;n.height=`${r/e*k}px`;n.top=`${m+A+y/e*k}px`;e=/scaleX\(-1\)/.test(a.style.transform);n.left=`${l+(e?f-u-p:u)+(e?c-t-q:t)/c*p}px`;n.transform=a.style.transform}})}static _convertPoints(a,c){if(!c)return a;let e=c.x||0,f=c.y||0,h=c.width&&c.downScaledWidth?c.width/c.downScaledWidth:1;c=c.height&&c.downScaledHeight?c.height/c.downScaledHeight:1;for(let l of a)l.x=l.x*h+e,l.y=l.y*c+f;return a}_scanFrame(){!this._active||this.$video.paused||this.$video.ended||("requestVideoFrameCallback"in
|
||||
this.$video?this.$video.requestVideoFrameCallback.bind(this.$video):requestAnimationFrame)(()=>{const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!(1>=a.$video.readyState)){var c=Date.now()-a._lastScanTimestamp,e=1E3/a._maxScansPerSecond;c<e&&(yield new Promise(h=>setTimeout(h,e-c)));a._lastScanTimestamp=Date.now();try{var f=yield b.scanImage(a.$video,{scanRegion:a._scanRegion,qrEngine:a._qrEnginePromise,canvas:a.$canvas})}catch(h){if(!a._active)return;a._onDecodeError(h)}!b._disableBarcodeDetector||
|
||||
(yield a._qrEnginePromise)instanceof Worker||(a._qrEnginePromise=b.createQrEngine());f?(a._onDecode?a._onDecode(f):a._legacyOnDecode&&a._legacyOnDecode(f.data),a.$codeOutlineHighlight&&(clearTimeout(a._codeOutlineHighlightRemovalTimeout),a._codeOutlineHighlightRemovalTimeout=void 0,a.$codeOutlineHighlight.setAttribute("viewBox",`${a._scanRegion.x||0} `+`${a._scanRegion.y||0} `+`${a._scanRegion.width||a.$video.videoWidth} `+`${a._scanRegion.height||a.$video.videoHeight}`),a.$codeOutlineHighlight.firstElementChild.setAttribute("points",
|
||||
f.cornerPoints.map(({x:h,y:l})=>`${h},${l}`).join(" ")),a.$codeOutlineHighlight.style.display="")):a.$codeOutlineHighlight&&!a._codeOutlineHighlightRemovalTimeout&&(a._codeOutlineHighlightRemovalTimeout=setTimeout(()=>a.$codeOutlineHighlight.style.display="none",100))}a._scanFrame()})})}_onDecodeError(a){a!==b.NO_QR_CODE_FOUND&&console.log(a)}_getCameraStream(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!navigator.mediaDevices)throw"Camera not found.";let c=/^(environment|user)$/.test(a._preferredCamera)?
|
||||
"facingMode":"deviceId",e=[{width:{min:1024}},{width:{min:768}},{}],f=e.map(h=>Object.assign({},h,{[c]:{exact:a._preferredCamera}}));for(let h of[...f,...e])try{let l=yield navigator.mediaDevices.getUserMedia({video:h,audio:!1}),m=a._getFacingMode(l)||(h.facingMode?a._preferredCamera:"environment"===a._preferredCamera?"user":"environment");return{stream:l,facingMode:m}}catch(l){}throw"Camera not found.";})}_restartVideoStream(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let c=
|
||||
a._paused;(yield a.pause(!0))&&!c&&a._active&&(yield a.start())})}static _stopVideoStream(a){for(let c of a.getTracks())c.stop(),a.removeTrack(c)}_setVideoMirror(a){this.$video.style.transform="scaleX("+("user"===a?-1:1)+")"}_getFacingMode(a){return(a=a.getVideoTracks()[0])?/rear|back|environment/i.test(a.label)?"environment":/front|user|face/i.test(a.label)?"user":null:null}static _drawToCanvas(a,c,e,f=!1){e=e||document.createElement("canvas");let h=c&&c.x?c.x:0,l=c&&c.y?c.y:0,m=c&&c.width?c.width:
|
||||
a.videoWidth||a.width,q=c&&c.height?c.height:a.videoHeight||a.height;f||(f=c&&c.downScaledWidth?c.downScaledWidth:m,c=c&&c.downScaledHeight?c.downScaledHeight:q,e.width!==f&&(e.width=f),e.height!==c&&(e.height=c));c=e.getContext("2d",{alpha:!1});c.imageSmoothingEnabled=!1;c.drawImage(a,h,l,m,q,0,0,e.width,e.height);return[e,c]}static _loadImage(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(a instanceof Image)return yield b._awaitImageLoad(a),a;if(a instanceof HTMLVideoElement||
|
||||
a instanceof HTMLCanvasElement||a instanceof SVGImageElement||"OffscreenCanvas"in window&&a instanceof OffscreenCanvas||"ImageBitmap"in window&&a instanceof ImageBitmap)return a;if(a instanceof File||a instanceof Blob||a instanceof URL||"string"===typeof a){let c=new Image;c.src=a instanceof File||a instanceof Blob?URL.createObjectURL(a):a.toString();try{return yield b._awaitImageLoad(c),c}finally{(a instanceof File||a instanceof Blob)&&URL.revokeObjectURL(c.src)}}else throw"Unsupported image type.";
|
||||
})}static _awaitImageLoad(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a.complete&&0!==a.naturalWidth||(yield new Promise((c,e)=>{let f=h=>{a.removeEventListener("load",f);a.removeEventListener("error",f);h instanceof ErrorEvent?e("Image load error"):c()};a.addEventListener("load",f);a.addEventListener("error",f)}))})}static _postWorkerMessage(a,c,e){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let f=yield a;f instanceof Worker&&f.postMessage({type:c,data:e})})}}
|
||||
b.DEFAULT_CANVAS_SIZE=400;b.NO_QR_CODE_FOUND="No QR code found";b._disableBarcodeDetector=!1;var d=new Worker(URL.createObjectURL(new Blob(['class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;f<b+d;f++)for(let g=a;g<a+c;g++)this.set(g,f,!!e)}}\nclass A{constructor(a,b,c){this.width=a;a*=b;if(c&&c.length!==a)throw Error("Wrong buffer size");this.data=c||new Uint8ClampedArray(a)}get(a,b){return this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c}}\nclass ba{constructor(a){this.bitOffset=this.byteOffset=0;this.bytes=a}readBits(a){if(1>a||32<a||a>this.available())throw Error("Cannot read "+a.toString()+" bits");var b=0;if(0<this.bitOffset){b=8-this.bitOffset;var c=a<b?a:b;b-=c;b=(this.bytes[this.byteOffset]&255>>8-c<<b)>>b;a-=c;this.bitOffset+=c;8===this.bitOffset&&(this.bitOffset=0,this.byteOffset++)}if(0<a){for(;8<=a;)b=b<<8|this.bytes[this.byteOffset]&255,this.byteOffset++,a-=8;0<a&&(c=8-a,b=b<<a|(this.bytes[this.byteOffset]&255>>c<<c)>>c,\nthis.bitOffset+=a)}return b}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var B,C=B||(B={});C.Numeric="numeric";C.Alphanumeric="alphanumeric";C.Byte="byte";C.Kanji="kanji";C.ECI="eci";C.StructuredAppend="structuredappend";var D,E=D||(D={});E[E.Terminator=0]="Terminator";E[E.Numeric=1]="Numeric";E[E.Alphanumeric=2]="Alphanumeric";E[E.Byte=4]="Byte";E[E.Kanji=8]="Kanji";E[E.ECI=7]="ECI";E[E.StructuredAppend=3]="StructuredAppend";let F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split("");\nfunction ca(a,b){let c=[],d="";b=a.readBits([8,16,16][b]);for(let e=0;e<b;e++){let f=a.readBits(8);c.push(f)}try{d+=decodeURIComponent(c.map(e=>`%${("0"+e.toString(16)).substr(-2)}`).join(""))}catch(e){}return{bytes:c,text:d}}\nfunction da(a,b){a=new ba(a);let c=9>=b?0:26>=b?1:2;for(b={text:"",bytes:[],chunks:[],version:b};4<=a.available();){var d=a.readBits(4);if(d===D.Terminator)return b;if(d===D.ECI)0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(7)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(14)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(21)}):b.chunks.push({type:B.ECI,assignmentNumber:-1});else if(d===D.Numeric){var e=a,f=[];d="";for(var g=\ne.readBits([10,12,14][c]);3<=g;){var h=e.readBits(10);if(1E3<=h)throw Error("Invalid numeric value above 999");var k=Math.floor(h/100),m=Math.floor(h/10)%10;h%=10;f.push(48+k,48+m,48+h);d+=k.toString()+m.toString()+h.toString();g-=3}if(2===g){g=e.readBits(7);if(100<=g)throw Error("Invalid numeric value above 99");e=Math.floor(g/10);g%=10;f.push(48+e,48+g);d+=e.toString()+g.toString()}else if(1===g){e=e.readBits(4);if(10<=e)throw Error("Invalid numeric value above 9");f.push(48+e);d+=e.toString()}b.text+=\nd;b.bytes.push(...f);b.chunks.push({type:B.Numeric,text:d})}else if(d===D.Alphanumeric){e=a;f=[];d="";for(g=e.readBits([9,11,13][c]);2<=g;)m=e.readBits(11),k=Math.floor(m/45),m%=45,f.push(F[k].charCodeAt(0),F[m].charCodeAt(0)),d+=F[k]+F[m],g-=2;1===g&&(e=e.readBits(6),f.push(F[e].charCodeAt(0)),d+=F[e]);b.text+=d;b.bytes.push(...f);b.chunks.push({type:B.Alphanumeric,text:d})}else if(d===D.Byte)d=ca(a,c),b.text+=d.text,b.bytes.push(...d.bytes),b.chunks.push({type:B.Byte,bytes:d.bytes,text:d.text});\nelse if(d===D.Kanji){f=a;d=[];e=f.readBits([8,10,12][c]);for(g=0;g<e;g++)k=f.readBits(13),k=Math.floor(k/192)<<8|k%192,k=7936>k?k+33088:k+49472,d.push(k>>8,k&255);f=(new TextDecoder("shift-jis")).decode(Uint8Array.from(d));b.text+=f;b.bytes.push(...d);b.chunks.push({type:B.Kanji,bytes:d,text:f})}else d===D.StructuredAppend&&b.chunks.push({type:B.StructuredAppend,currentSequence:a.readBits(4),totalSequence:a.readBits(4),parity:a.readBits(8)})}if(0===a.available()||0===a.readBits(a.available()))return b}\nclass G{constructor(a,b){if(0===b.length)throw Error("No coefficients.");this.field=a;let c=b.length;if(1<c&&0===b[0]){let d=1;for(;d<c&&0===b[d];)d++;if(d===c)this.coefficients=a.zero.coefficients;else for(this.coefficients=new Uint8ClampedArray(c-d),a=0;a<this.coefficients.length;a++)this.coefficients[a]=b[d+a]}else this.coefficients=b}degree(){return this.coefficients.length-1}isZero(){return 0===this.coefficients[0]}getCoefficient(a){return this.coefficients[this.coefficients.length-1-a]}addOrSubtract(a){if(this.isZero())return a;\nif(a.isZero())return this;let b=this.coefficients;a=a.coefficients;b.length>a.length&&([b,a]=[a,b]);let c=new Uint8ClampedArray(a.length),d=a.length-b.length;for(var e=0;e<d;e++)c[e]=a[e];for(e=d;e<a.length;e++)c[e]=b[e-d]^a[e];return new G(this.field,c)}multiply(a){if(0===a)return this.field.zero;if(1===a)return this;let b=this.coefficients.length,c=new Uint8ClampedArray(b);for(let d=0;d<b;d++)c[d]=this.field.multiply(this.coefficients[d],a);retLine truncated
|
||||
{type:"application/javascript"})),g=Object.freeze({__proto__:null,"default":d});return b})
|
||||
$jscomp.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_};$jscomp.generator.Context.prototype.next_=function(c){this.yieldResult=c};$jscomp.generator.Context.prototype.throw_=function(c){this.abruptCompletion_={exception:c,isException:!0};this.jumpToErrorHandler_()};$jscomp.generator.Context.prototype.return=function(c){this.abruptCompletion_={return:c};this.nextAddress=this.finallyAddress_};
|
||||
$jscomp.generator.Context.prototype.jumpThroughFinallyBlocks=function(c){this.abruptCompletion_={jumpTo:c};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.yield=function(c,e){this.nextAddress=e;return{value:c}};$jscomp.generator.Context.prototype.yieldAll=function(c,e){c=$jscomp.makeIterator(c);var a=c.next();$jscomp.generator.ensureIteratorResultIsObject_(a);if(a.done)this.yieldResult=a.value,this.nextAddress=e;else return this.yieldAllIterator_=c,this.yield(a.value,e)};
|
||||
$jscomp.generator.Context.prototype.jumpTo=function(c){this.nextAddress=c};$jscomp.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0};$jscomp.generator.Context.prototype.setCatchFinallyBlocks=function(c,e){this.catchAddress_=c;void 0!=e&&(this.finallyAddress_=e)};$jscomp.generator.Context.prototype.setFinallyBlock=function(c){this.catchAddress_=0;this.finallyAddress_=c||0};$jscomp.generator.Context.prototype.leaveTryBlock=function(c,e){this.nextAddress=c;this.catchAddress_=e||0};
|
||||
$jscomp.generator.Context.prototype.enterCatchBlock=function(c){this.catchAddress_=c||0;c=this.abruptCompletion_.exception;this.abruptCompletion_=null;return c};$jscomp.generator.Context.prototype.enterFinallyBlock=function(c,e,a){a?this.finallyContexts_[a]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_];this.catchAddress_=c||0;this.finallyAddress_=e||0};
|
||||
$jscomp.generator.Context.prototype.leaveFinallyBlock=function(c,e){e=this.finallyContexts_.splice(e||0)[0];if(e=this.abruptCompletion_=this.abruptCompletion_||e){if(e.isException)return this.jumpToErrorHandler_();void 0!=e.jumpTo&&this.finallyAddress_<e.jumpTo?(this.nextAddress=e.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=c};$jscomp.generator.Context.prototype.forIn=function(c){return new $jscomp.generator.Context.PropertyIterator(c)};
|
||||
$jscomp.generator.Context.PropertyIterator=function(c){this.object_=c;this.properties_=[];for(var e in c)this.properties_.push(e);this.properties_.reverse()};$jscomp.generator.Context.PropertyIterator.prototype.getNext=function(){for(;0<this.properties_.length;){var c=this.properties_.pop();if(c in this.object_)return c}return null};$jscomp.generator.Engine_=function(c){this.context_=new $jscomp.generator.Context;this.program_=c};
|
||||
$jscomp.generator.Engine_.prototype.next_=function(c){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_.next,c,this.context_.next_);this.context_.next_(c);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.return_=function(c){this.context_.start_();var e=this.context_.yieldAllIterator_;if(e)return this.yieldAllStep_("return"in e?e["return"]:function(a){return{value:a,done:!0}},c,this.context_.return);this.context_.return(c);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.throw_=function(c){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_["throw"],c,this.context_.next_);this.context_.throw_(c);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.yieldAllStep_=function(c,e,a){try{var b=c.call(this.context_.yieldAllIterator_,e);$jscomp.generator.ensureIteratorResultIsObject_(b);if(!b.done)return this.context_.stop_(),b;var d=b.value}catch(f){return this.context_.yieldAllIterator_=null,this.context_.throw_(f),this.nextStep_()}this.context_.yieldAllIterator_=null;a.call(this.context_,d);return this.nextStep_()};
|
||||
$jscomp.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var c=this.program_(this.context_);if(c)return this.context_.stop_(),{value:c.value,done:!1}}catch(e){this.context_.yieldResult=void 0,this.context_.throw_(e)}this.context_.stop_();if(this.context_.abruptCompletion_){c=this.context_.abruptCompletion_;this.context_.abruptCompletion_=null;if(c.isException)throw c.exception;return{value:c.return,done:!0}}return{value:void 0,done:!0}};
|
||||
$jscomp.generator.Generator_=function(c){this.next=function(e){return c.next_(e)};this.throw=function(e){return c.throw_(e)};this.return=function(e){return c.return_(e)};this[Symbol.iterator]=function(){return this}};$jscomp.generator.createGenerator=function(c,e){e=new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(e));$jscomp.setPrototypeOf&&c.prototype&&$jscomp.setPrototypeOf(e,c.prototype);return e};
|
||||
$jscomp.asyncExecutePromiseGenerator=function(c){function e(b){return c.next(b)}function a(b){return c.throw(b)}return new Promise(function(b,d){function f(g){g.done?b(g.value):Promise.resolve(g.value).then(e,a).then(f,d)}f(c.next())})};$jscomp.asyncExecutePromiseGeneratorFunction=function(c){return $jscomp.asyncExecutePromiseGenerator(c())};$jscomp.asyncExecutePromiseGeneratorProgram=function(c){return $jscomp.asyncExecutePromiseGenerator(new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(c)))};
|
||||
(function(c,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"===typeof define&&define.amd?define(e):(c="undefined"!==typeof globalThis?globalThis:c||self,c.QrScanner=e())})(this,function(){class c{constructor(a,b,d,f,g){this._legacyCanvasSize=c.DEFAULT_CANVAS_SIZE;this._preferredCamera="environment";this._maxScansPerSecond=25;this._lastScanTimestamp=-1;this._destroyed=this._flashOn=this._paused=this._active=!1;this.$video=a;this.$canvas=document.createElement("canvas");
|
||||
d&&"object"===typeof d?this._onDecode=b:(d||f||g?console.warn("You're using a deprecated version of the QrScanner constructor which will be removed in the future"):console.warn("Note that the type of the scan result passed to onDecode will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),this._legacyOnDecode=b);b="object"===typeof d?d:{};this._onDecodeError=b.onDecodeError||("function"===typeof d?d:this._onDecodeError);this._calculateScanRegion=
|
||||
b.calculateScanRegion||("function"===typeof f?f:this._calculateScanRegion);this._preferredCamera=b.preferredCamera||g||this._preferredCamera;this._legacyCanvasSize="number"===typeof d?d:"number"===typeof f?f:this._legacyCanvasSize;this._maxScansPerSecond=b.maxScansPerSecond||this._maxScansPerSecond;this._onPlay=this._onPlay.bind(this);this._onLoadedMetaData=this._onLoadedMetaData.bind(this);this._onVisibilityChange=this._onVisibilityChange.bind(this);this._updateOverlay=this._updateOverlay.bind(this);
|
||||
a.disablePictureInPicture=!0;a.playsInline=!0;a.muted=!0;let k=!1;a.hidden&&(a.hidden=!1,k=!0);document.body.contains(a)||(document.body.appendChild(a),k=!0);d=a.parentElement;if(b.highlightScanRegion||b.highlightCodeOutline){f=!!b.overlay;this.$overlay=b.overlay||document.createElement("div");g=this.$overlay.style;g.position="absolute";g.display="none";g.pointerEvents="none";this.$overlay.classList.add("scan-region-highlight");if(!f&&b.highlightScanRegion){this.$overlay.innerHTML='<svg class="scan-region-highlight-svg" viewBox="0 0 238 238" preserveAspectRatio="none" style="position:absolute;width:100%;height:100%;left:0;top:0;fill:none;stroke:#e9b213;stroke-width:4;stroke-linecap:round;stroke-linejoin:round"><path d="M31 2H10a8 8 0 0 0-8 8v21M207 2h21a8 8 0 0 1 8 8v21m0 176v21a8 8 0 0 1-8 8h-21m-176 0H10a8 8 0 0 1-8-8v-21"/></svg>';
|
||||
try{this.$overlay.firstElementChild.animate({transform:["scale(.98)","scale(1.01)"]},{duration:400,iterations:Infinity,direction:"alternate",easing:"ease-in-out"})}catch(l){}d.insertBefore(this.$overlay,this.$video.nextSibling)}b.highlightCodeOutline&&(this.$overlay.insertAdjacentHTML("beforeend",'<svg class="code-outline-highlight" preserveAspectRatio="none" style="display:none;width:100%;height:100%;fill:none;stroke:#e9b213;stroke-width:5;stroke-dasharray:25;stroke-linecap:round;stroke-linejoin:round"><polygon/></svg>'),
|
||||
this.$codeOutlineHighlight=this.$overlay.lastElementChild)}this._scanRegion=this._calculateScanRegion(a);requestAnimationFrame(()=>{let l=window.getComputedStyle(a);"none"===l.display&&(a.style.setProperty("display","block","important"),k=!0);"visible"!==l.visibility&&(a.style.setProperty("visibility","visible","important"),k=!0);k&&(console.warn("QrScanner has overwritten the video hiding style to avoid Safari stopping the playback."),a.style.opacity="0",a.style.width="0",a.style.height="0",this.$overlay&&
|
||||
this.$overlay.parentElement&&this.$overlay.parentElement.removeChild(this.$overlay),delete this.$overlay,delete this.$codeOutlineHighlight);this.$overlay&&this._updateOverlay()});a.addEventListener("play",this._onPlay);a.addEventListener("loadedmetadata",this._onLoadedMetaData);document.addEventListener("visibilitychange",this._onVisibilityChange);window.addEventListener("resize",this._updateOverlay);this._qrEnginePromise=c.createQrEngine()}static set WORKER_PATH(a){console.warn("Setting QrScanner.WORKER_PATH is not required and not supported anymore. Have a look at the README for new setup instructions.")}static hasCamera(){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){try{return!!(yield c.listCameras(!1)).length}catch(a){return!1}})}static listCameras(a=
|
||||
!1){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!navigator.mediaDevices)return[];let b=()=>$jscomp.asyncExecutePromiseGeneratorFunction(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(f=>"videoinput"===f.kind)}),d;try{a&&(yield b()).every(f=>!f.label)&&(d=yield navigator.mediaDevices.getUserMedia({audio:!1,video:!0}))}catch(f){}try{return(yield b()).map((f,g)=>({id:f.deviceId,label:f.label||(0===g?"Default Camera":`Camera ${g+1}`)}))}finally{d&&(console.warn("Call listCameras after successfully starting a QR scanner to avoid creating a temporary video stream"),
|
||||
c._stopVideoStream(d))}})}hasFlash(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let b;try{if(a.$video.srcObject){if(!(a.$video.srcObject instanceof MediaStream))return!1;b=a.$video.srcObject}else b=(yield a._getCameraStream()).stream;return"torch"in b.getVideoTracks()[0].getSettings()}catch(d){return!1}finally{b&&b!==a.$video.srcObject&&(console.warn("Call hasFlash after successfully starting the scanner to avoid creating a temporary video stream"),c._stopVideoStream(b))}})}isFlashOn(){return this._flashOn}toggleFlash(){const a=
|
||||
this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a._flashOn?yield a.turnFlashOff():yield a.turnFlashOn()})}turnFlashOn(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!a._flashOn&&!a._destroyed&&(a._flashOn=!0,a._active&&!a._paused))try{if(!(yield a.hasFlash()))throw"No flash available";yield a.$video.srcObject.getVideoTracks()[0].applyConstraints({advanced:[{torch:!0}]})}catch(b){throw a._flashOn=!1,b;}})}turnFlashOff(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a._flashOn&&
|
||||
(a._flashOn=!1,yield a._restartVideoStream())})}destroy(){this.$video.removeEventListener("loadedmetadata",this._onLoadedMetaData);this.$video.removeEventListener("play",this._onPlay);document.removeEventListener("visibilitychange",this._onVisibilityChange);window.removeEventListener("resize",this._updateOverlay);this._destroyed=!0;this._flashOn=!1;this.stop();c._postWorkerMessage(this._qrEnginePromise,"close")}start(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(a._destroyed)throw Error("The QR scanner can not be started as it had been destroyed.");
|
||||
if(!a._active||a._paused)if("https:"!==window.location.protocol&&console.warn("The camera stream is only accessible if the page is transferred via https."),a._active=!0,!document.hidden)if(a._paused=!1,a.$video.srcObject)yield a.$video.play();else try{let {stream:b,facingMode:d}=yield a._getCameraStream();!a._active||a._paused?c._stopVideoStream(b):(a._setVideoMirror(d),a.$video.srcObject=b,yield a.$video.play(),a._flashOn&&(a._flashOn=!1,a.turnFlashOn().catch(()=>{})))}catch(b){if(!a._paused)throw a._active=
|
||||
!1,b;}})}stop(){this.pause();this._active=!1}pause(a=!1){const b=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){b._paused=!0;if(!b._active)return!0;b.$video.pause();b.$overlay&&(b.$overlay.style.display="none");let d=()=>{b.$video.srcObject instanceof MediaStream&&(c._stopVideoStream(b.$video.srcObject),b.$video.srcObject=null)};if(a)return d(),!0;yield new Promise(f=>setTimeout(f,300));if(!b._paused)return!1;d();return!0})}setCamera(a){const b=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a!==
|
||||
b._preferredCamera&&(b._preferredCamera=a,yield b._restartVideoStream())})}static scanImage(a,b,d,f,g=!1,k=!1){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let l,p=!1;b&&("scanRegion"in b||"qrEngine"in b||"canvas"in b||"disallowCanvasResizing"in b||"alsoTryWithoutScanRegion"in b||"returnDetailedScanResult"in b)?(l=b.scanRegion,d=b.qrEngine,f=b.canvas,g=b.disallowCanvasResizing||!1,k=b.alsoTryWithoutScanRegion||!1,p=!0):b||d||f||g||k?console.warn("You're using a deprecated api for scanImage which will be removed in the future."):
|
||||
console.warn("Note that the return type of scanImage will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true.");let r=!!d;try{let m,q;[d,m]=yield Promise.all([d||c.createQrEngine(),c._loadImage(a)]);[f,q]=c._drawToCanvas(m,l,f,g);let n;if(d instanceof Worker){let h=d;r||h.postMessage({type:"inversionMode",data:"both"});n=yield new Promise((t,z)=>{let x,v,w;v=u=>{"qrResult"===u.data.type&&(h.removeEventListener("message",v),h.removeEventListener("error",
|
||||
w),clearTimeout(x),null!==u.data.data?t({data:u.data.data,cornerPoints:c._convertPoints(u.data.cornerPoints,l)}):z(c.NO_QR_CODE_FOUND))};w=u=>{h.removeEventListener("message",v);h.removeEventListener("error",w);clearTimeout(x);z("Scanner error: "+(u?u.message||u:"Unknown Error"))};h.addEventListener("message",v);h.addEventListener("error",w);x=setTimeout(()=>w("timeout"),1E4);let y=q.getImageData(0,0,f.width,f.height);h.postMessage({type:"decode",data:y},[y.data.buffer])})}else n=yield Promise.race([new Promise((h,
|
||||
t)=>window.setTimeout(()=>t("Scanner error: timeout"),1E4)),(()=>$jscomp.asyncExecutePromiseGeneratorFunction(function*(){try{var [h]=yield d.detect(f);if(!h)throw c.NO_QR_CODE_FOUND;return{data:h.rawValue,cornerPoints:c._convertPoints(h.cornerPoints,l)}}catch(t){h=t.message||t;if(/not implemented|service unavailable/.test(h))return c._disableBarcodeDetector=!0,c.scanImage(a,{scanRegion:l,canvas:f,disallowCanvasResizing:g,alsoTryWithoutScanRegion:k});throw`Scanner error: ${h}`;}}))()]);return p?n:
|
||||
n.data}catch(m){if(!l||!k)throw m;let q=yield c.scanImage(a,{qrEngine:d,canvas:f,disallowCanvasResizing:g});return p?q:q.data}finally{r||c._postWorkerMessage(d,"close")}})}setGrayscaleWeights(a,b,d,f=!0){c._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:a,green:b,blue:d,useIntegerApproximation:f})}setInversionMode(a){c._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static createQrEngine(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a&&console.warn("Specifying a worker path is not required and not supported anymore.");
|
||||
return!c._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(yield BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):Promise.resolve().then(function(){return e}).then(b=>b.createWorker())})}_onPlay(){this._scanRegion=this._calculateScanRegion(this.$video);this._updateOverlay();this.$overlay&&(this.$overlay.style.display="");this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video);
|
||||
this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(a){let b=Math.round(2/3*Math.min(a.videoWidth,a.videoHeight));return{x:Math.round((a.videoWidth-b)/2),y:Math.round((a.videoHeight-b)/2),width:b,height:b,downScaledWidth:this._legacyCanvasSize,downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var a=this.$video,b=a.videoWidth,d=a.videoHeight,f=a.offsetWidth,g=a.offsetHeight,k=a.offsetLeft,
|
||||
l=a.offsetTop,p=window.getComputedStyle(a),r=p.objectFit,m=b/d,q=f/g;switch(r){case "none":var n=b;var h=d;break;case "fill":n=f;h=g;break;default:("cover"===r?m>q:m<q)?(h=g,n=h*m):(n=f,h=n/m),"scale-down"===r&&(n=Math.min(n,b),h=Math.min(h,d))}var [t,z]=p.objectPosition.split(" ").map((v,w)=>{const y=parseFloat(v);return v.endsWith("%")?(w?g-h:f-n)*y/100:y});p=this._scanRegion.width||b;q=this._scanRegion.height||d;r=this._scanRegion.x||0;var x=this._scanRegion.y||0;m=this.$overlay.style;m.width=
|
||||
`${p/b*n}px`;m.height=`${q/d*h}px`;m.top=`${l+z+x/d*h}px`;d=/scaleX\(-1\)/.test(a.style.transform);m.left=`${k+(d?f-t-n:t)+(d?b-r-p:r)/b*n}px`;m.transform=a.style.transform}})}static _convertPoints(a,b){if(!b)return a;let d=b.x||0,f=b.y||0,g=b.width&&b.downScaledWidth?b.width/b.downScaledWidth:1;b=b.height&&b.downScaledHeight?b.height/b.downScaledHeight:1;for(let k of a)k.x=k.x*g+d,k.y=k.y*b+f;return a}_scanFrame(){!this._active||this.$video.paused||this.$video.ended||("requestVideoFrameCallback"in
|
||||
this.$video?this.$video.requestVideoFrameCallback.bind(this.$video):requestAnimationFrame)(()=>{const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!(1>=a.$video.readyState)){var b=Date.now()-a._lastScanTimestamp,d=1E3/a._maxScansPerSecond;b<d&&(yield new Promise(g=>setTimeout(g,d-b)));a._lastScanTimestamp=Date.now();try{var f=yield c.scanImage(a.$video,{scanRegion:a._scanRegion,qrEngine:a._qrEnginePromise,canvas:a.$canvas})}catch(g){if(!a._active)return;a._onDecodeError(g)}!c._disableBarcodeDetector||
|
||||
(yield a._qrEnginePromise)instanceof Worker||(a._qrEnginePromise=c.createQrEngine());f?(a._onDecode?a._onDecode(f):a._legacyOnDecode&&a._legacyOnDecode(f.data),a.$codeOutlineHighlight&&(clearTimeout(a._codeOutlineHighlightRemovalTimeout),a._codeOutlineHighlightRemovalTimeout=void 0,a.$codeOutlineHighlight.setAttribute("viewBox",`${a._scanRegion.x||0} `+`${a._scanRegion.y||0} `+`${a._scanRegion.width||a.$video.videoWidth} `+`${a._scanRegion.height||a.$video.videoHeight}`),a.$codeOutlineHighlight.firstElementChild.setAttribute("points",
|
||||
f.cornerPoints.map(({x:g,y:k})=>`${g},${k}`).join(" ")),a.$codeOutlineHighlight.style.display="")):a.$codeOutlineHighlight&&!a._codeOutlineHighlightRemovalTimeout&&(a._codeOutlineHighlightRemovalTimeout=setTimeout(()=>a.$codeOutlineHighlight.style.display="none",100))}a._scanFrame()})})}_onDecodeError(a){a!==c.NO_QR_CODE_FOUND&&console.log(a)}_getCameraStream(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(!navigator.mediaDevices)throw"Camera not found.";let b=/^(environment|user)$/.test(a._preferredCamera)?
|
||||
"facingMode":"deviceId",d=[{width:{min:1024}},{width:{min:768}},{}],f=d.map(g=>Object.assign({},g,{[b]:{exact:a._preferredCamera}}));for(let g of[...f,...d])try{let k=yield navigator.mediaDevices.getUserMedia({video:g,audio:!1}),l=a._getFacingMode(k)||(g.facingMode?a._preferredCamera:"environment"===a._preferredCamera?"user":"environment");return{stream:k,facingMode:l}}catch(k){}throw"Camera not found.";})}_restartVideoStream(){const a=this;return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let b=
|
||||
a._paused;(yield a.pause(!0))&&!b&&a._active&&(yield a.start())})}static _stopVideoStream(a){for(let b of a.getTracks())b.stop(),a.removeTrack(b)}_setVideoMirror(a){this.$video.style.transform="scaleX("+("user"===a?-1:1)+")"}_getFacingMode(a){return(a=a.getVideoTracks()[0])?/rear|back|environment/i.test(a.label)?"environment":/front|user|face/i.test(a.label)?"user":null:null}static _drawToCanvas(a,b,d,f=!1){d=d||document.createElement("canvas");let g=b&&b.x?b.x:0,k=b&&b.y?b.y:0,l=b&&b.width?b.width:
|
||||
a.videoWidth||a.width,p=b&&b.height?b.height:a.videoHeight||a.height;f||(f=b&&b.downScaledWidth?b.downScaledWidth:l,b=b&&b.downScaledHeight?b.downScaledHeight:p,d.width!==f&&(d.width=f),d.height!==b&&(d.height=b));b=d.getContext("2d",{alpha:!1});b.imageSmoothingEnabled=!1;b.drawImage(a,g,k,l,p,0,0,d.width,d.height);return[d,b]}static _loadImage(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){if(a instanceof Image)return yield c._awaitImageLoad(a),a;if(a instanceof HTMLVideoElement||
|
||||
a instanceof HTMLCanvasElement||a instanceof SVGImageElement||"OffscreenCanvas"in window&&a instanceof OffscreenCanvas||"ImageBitmap"in window&&a instanceof ImageBitmap)return a;if(a instanceof File||a instanceof Blob||a instanceof URL||"string"===typeof a){let b=new Image;b.src=a instanceof File||a instanceof Blob?URL.createObjectURL(a):a.toString();try{return yield c._awaitImageLoad(b),b}finally{(a instanceof File||a instanceof Blob)&&URL.revokeObjectURL(b.src)}}else throw"Unsupported image type.";
|
||||
})}static _awaitImageLoad(a){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){a.complete&&0!==a.naturalWidth||(yield new Promise((b,d)=>{let f=g=>{a.removeEventListener("load",f);a.removeEventListener("error",f);g instanceof ErrorEvent?d("Image load error"):b()};a.addEventListener("load",f);a.addEventListener("error",f)}))})}static _postWorkerMessage(a,b,d){return $jscomp.asyncExecutePromiseGeneratorFunction(function*(){let f=yield a;f instanceof Worker&&f.postMessage({type:b,data:d})})}}
|
||||
c.DEFAULT_CANVAS_SIZE=400;c.NO_QR_CODE_FOUND="No QR code found";c._disableBarcodeDetector=!1;var e=Object.freeze({__proto__:null,createWorker:()=>new Worker(URL.createObjectURL(new Blob(['class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;f<b+d;f++)for(let g=a;g<a+c;g++)this.set(g,f,!!e)}}\nclass A{constructor(a,b,c){this.width=a;a*=b;if(c&&c.length!==a)throw Error("Wrong buffer size");this.data=c||new Uint8ClampedArray(a)}get(a,b){return this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c}}\nclass ba{constructor(a){this.bitOffset=this.byteOffset=0;this.bytes=a}readBits(a){if(1>a||32<a||a>this.available())throw Error("Cannot read "+a.toString()+" bits");var b=0;if(0<this.bitOffset){b=8-this.bitOffset;var c=a<b?a:b;b-=c;b=(this.bytes[this.byteOffset]&255>>8-c<<b)>>b;a-=c;this.bitOffset+=c;8===this.bitOffset&&(this.bitOffset=0,this.byteOffset++)}if(0<a){for(;8<=a;)b=b<<8|this.bytes[this.byteOffset]&255,this.byteOffset++,a-=8;0<a&&(c=8-a,b=b<<a|(this.bytes[this.byteOffset]&255>>c<<c)>>c,\nthis.bitOffset+=a)}return b}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var B,C=B||(B={});C.Numeric="numeric";C.Alphanumeric="alphanumeric";C.Byte="byte";C.Kanji="kanji";C.ECI="eci";C.StructuredAppend="structuredappend";var D,E=D||(D={});E[E.Terminator=0]="Terminator";E[E.Numeric=1]="Numeric";E[E.Alphanumeric=2]="Alphanumeric";E[E.Byte=4]="Byte";E[E.Kanji=8]="Kanji";E[E.ECI=7]="ECI";E[E.StructuredAppend=3]="StructuredAppend";let F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split("");\nfunction ca(a,b){let c=[],d="";b=a.readBits([8,16,16][b]);for(let e=0;e<b;e++){let f=a.readBits(8);c.push(f)}try{d+=decodeURIComponent(c.map(e=>`%${("0"+e.toString(16)).substr(-2)}`).join(""))}catch(e){}return{bytes:c,text:d}}\nfunction da(a,b){a=new ba(a);let c=9>=b?0:26>=b?1:2;for(b={text:"",bytes:[],chunks:[],version:b};4<=a.available();){var d=a.readBits(4);if(d===D.Terminator)return b;if(d===D.ECI)0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(7)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(14)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(21)}):b.chunks.push({type:B.ECI,assignmentNumber:-1});else if(d===D.Numeric){var e=a,f=[];d="";for(var g=\ne.readBits([10,12,14][c]);3<=g;){var h=e.readBits(10);if(1E3<=h)throw Error("Invalid numeric value above 999");var k=Math.floor(h/100),m=Math.floor(h/10)%10;h%=10;f.push(48+k,48+m,48+h);d+=k.toString()+m.toString()+h.toString();g-=3}if(2===g){g=e.readBits(7);if(100<=g)throw Error("Invalid numeric value above 99");e=Math.floor(g/10);g%=10;f.push(48+e,48+g);d+=e.toString()+g.toString()}else if(1===g){e=e.readBits(4);if(10<=e)throw Error("Invalid numeric value above 9");f.push(48+e);d+=e.toString()}b.text+=\nd;b.bytes.push(...f);b.chunks.push({type:B.Numeric,text:d})}else if(d===D.Alphanumeric){e=a;f=[];d="";for(g=e.readBits([9,11,13][c]);2<=g;)m=e.readBits(11),k=Math.floor(m/45),m%=45,f.push(F[k].charCodeAt(0),F[m].charCodeAt(0)),d+=F[k]+F[m],g-=2;1===g&&(e=e.readBits(6),f.push(F[e].charCodeAt(0)),d+=F[e]);b.text+=d;b.bytes.push(...f);b.chunks.push({type:B.Alphanumeric,text:d})}else if(d===D.Byte)d=ca(a,c),b.text+=d.text,b.bytes.push(...d.bytes),b.chunks.push({type:B.Byte,bytes:d.bytes,text:d.text});\nelse if(d===D.Kanji){f=a;d=[];e=f.readBits([8,10,12][c]);for(g=0;g<e;g++)k=f.readBits(13),k=Math.floor(k/192)<<8|k%192,k=7936>k?k+33088:k+49472,d.push(k>>8,k&255);f=(new TextDecoder("shift-jis")).decode(Uint8Array.from(d));b.text+=f;b.bytes.push(...d);b.chunks.push({type:B.Kanji,bytes:d,text:f})}else d===D.StructuredAppend&&b.chunks.push({type:B.StructuredAppend,currentSequence:a.readBits(4),totalSequence:a.readBits(4),parity:a.readBits(8)})}if(0===a.available()||0===a.readBits(a.available()))return b}\nclass G{constructor(a,b){if(0===b.length)throw Error("No coefficients.");this.field=a;let c=b.length;if(1<c&&0===b[0]){let d=1;for(;d<c&&0===b[d];)d++;if(d===c)this.coefficients=a.zero.coefficients;else for(this.coefficients=new Uint8ClampedArray(c-d),a=0;a<this.coefficients.length;a++)this.coefficients[a]=b[d+a]}else this.coefficients=b}degree(){return this.coefficients.length-1}isZero(){return 0===this.coefficients[0]}getCoefficient(a){return this.coefficients[this.coefficients.length-1-a]}addOrSubtract(a){if(this.isZero())return a;\nif(a.isZero())return this;let b=this.coefficients;a=a.coefficients;b.length>a.length&&([b,a]=[a,b]);let c=new Uint8ClampedArray(a.length),d=a.length-b.length;for(var e=0;e<d;e++)c[e]=a[e];for(e=d;e<a.length;e++)c[e]=b[e-d]^a[e];return new G(this.field,c)}multiply(a){if(0===a)return this.field.zero;if(1===a)return this;let b=this.coefficients.length,c=new Uint8ClampedArray(b);for(let d=0;d<b;d++)c[d]=Line truncated
|
||||
{type:"application/javascript"}))});return c})
|
||||
//# sourceMappingURL=qr-scanner.legacy.min.js.map
|
||||
Vendored
+1
-1
@@ -15,7 +15,7 @@ b||"returnDetailedScanResult"in b)?(m=b.scanRegion,c=b.qrEngine,d=b.canvas,f=b.d
|
||||
[d,k]=e._drawToCanvas(p,m,d,f);let r;if(c instanceof Worker){let g=c;b||g.postMessage({type:"inversionMode",data:"both"});r=await new Promise((l,v)=>{let w,u,t;u=q=>{"qrResult"===q.data.type&&(g.removeEventListener("message",u),g.removeEventListener("error",t),clearTimeout(w),null!==q.data.data?l({data:q.data.data,cornerPoints:e._convertPoints(q.data.cornerPoints,m)}):v(e.NO_QR_CODE_FOUND))};t=q=>{g.removeEventListener("message",u);g.removeEventListener("error",t);clearTimeout(w);v("Scanner error: "+
|
||||
(q?q.message||q:"Unknown Error"))};g.addEventListener("message",u);g.addEventListener("error",t);w=setTimeout(()=>t("timeout"),1E4);let x=k.getImageData(0,0,d.width,d.height);g.postMessage({type:"decode",data:x},[x.data.buffer])})}else r=await Promise.race([new Promise((g,l)=>window.setTimeout(()=>l("Scanner error: timeout"),1E4)),(async()=>{try{var [g]=await c.detect(d);if(!g)throw e.NO_QR_CODE_FOUND;return{data:g.rawValue,cornerPoints:e._convertPoints(g.cornerPoints,m)}}catch(l){g=l.message||l;
|
||||
if(/not implemented|service unavailable/.test(g))return e._disableBarcodeDetector=!0,e.scanImage(a,{scanRegion:m,canvas:d,disallowCanvasResizing:f,alsoTryWithoutScanRegion:h});throw`Scanner error: ${g}`;}})()]);return n?r:r.data}catch(p){if(!m||!h)throw p;let k=await e.scanImage(a,{qrEngine:c,canvas:d,disallowCanvasResizing:f});return n?k:k.data}finally{b||e._postWorkerMessage(c,"close")}}setGrayscaleWeights(a,b,c,d=!0){e._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:a,green:b,
|
||||
blue:c,useIntegerApproximation:d})}setInversionMode(a){e._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static async createQrEngine(a){a&&console.warn("Specifying a worker path is not required and not supported anymore.");return!e._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):import("./qr-scanner-worker.min.js").then(b=>b.default)}_onPlay(){this._scanRegion=
|
||||
blue:c,useIntegerApproximation:d})}setInversionMode(a){e._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static async createQrEngine(a){a&&console.warn("Specifying a worker path is not required and not supported anymore.");return!e._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):import("./qr-scanner-worker.min.js").then(b=>b.createWorker())}_onPlay(){this._scanRegion=
|
||||
this._calculateScanRegion(this.$video);this._updateOverlay();this.$overlay&&(this.$overlay.style.display="");this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video);this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(a){let b=Math.round(2/3*Math.min(a.videoWidth,a.videoHeight));return{x:Math.round((a.videoWidth-b)/2),y:Math.round((a.videoHeight-b)/2),width:b,height:b,downScaledWidth:this._legacyCanvasSize,
|
||||
downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var a=this.$video,b=a.videoWidth,c=a.videoHeight,d=a.offsetWidth,f=a.offsetHeight,h=a.offsetLeft,m=a.offsetTop,n=window.getComputedStyle(a),p=n.objectFit,k=b/c,r=d/f;switch(p){case "none":var g=b;var l=c;break;case "fill":g=d;l=f;break;default:("cover"===p?k>r:k<r)?(l=f,g=l*k):(g=d,l=g/k),"scale-down"===p&&(g=Math.min(g,b),l=Math.min(l,c))}var [v,w]=n.objectPosition.split(" ").map((t,x)=>{const q=
|
||||
parseFloat(t);return t.endsWith("%")?(x?f-l:d-g)*q/100:q});n=this._scanRegion.width||b;r=this._scanRegion.height||c;p=this._scanRegion.x||0;var u=this._scanRegion.y||0;k=this.$overlay.style;k.width=`${n/b*g}px`;k.height=`${r/c*l}px`;k.top=`${m+w+u/c*l}px`;c=/scaleX\(-1\)/.test(a.style.transform);k.left=`${h+(c?d-v-g:v)+(c?b-p-n:p)/b*g}px`;k.transform=a.style.transform}})}static _convertPoints(a,b){if(!b)return a;let c=b.x||0,d=b.y||0,f=b.width&&b.downScaledWidth?b.width/b.downScaledWidth:1;b=b.height&&
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"file":"qr-scanner.min.js","sources":["src/qr-scanner.ts"],"sourcesContent":["class QrScanner {\n static readonly DEFAULT_CANVAS_SIZE = 400;\n static readonly NO_QR_CODE_FOUND = 'No QR code found';\n private static _disableBarcodeDetector = false;\n\n /** @deprecated */\n static set WORKER_PATH(workerPath: string) {\n console.warn('Setting QrScanner.WORKER_PATH is not required and not supported anymore. '\n + 'Have a look at the README for new setup instructions.');\n }\n\n static async hasCamera(): Promise<boolean> {\n try {\n return !!(await QrScanner.listCameras(false)).length;\n } catch (e) {\n return false;\n }\n }\n\n static async listCameras(requestLabels = false): Promise<Array<QrScanner.Camera>> {\n if (!navigator.mediaDevices) return [];\n\n const enumerateCameras = async (): Promise<Array<MediaDeviceInfo>> =>\n (await navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === 'videoinput');\n\n // Note that enumerateDevices can always be called and does not prompt the user for permission.\n // However, enumerateDevices only includes device labels if served via https and an active media stream exists\n // or permission to access the camera was given. Therefore, if we're not getting labels but labels are requested\n // ask for camera permission by opening a stream.\n let openedStream: MediaStream | undefined;\n try {\n if (requestLabels && (await enumerateCameras()).every((camera) => !camera.label)) {\n openedStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });\n }\n } catch (e) {\n // Fail gracefully, especially if the device has no camera or on mobile when the camera is already in use\n // and some browsers disallow a second stream.\n }\n\n try {\n return (await enumerateCameras()).map((camera, i) => ({\n id: camera.deviceId,\n label: camera.label || (i === 0 ? 'Default Camera' : `Camera ${i + 1}`),\n }));\n } finally {\n // close the stream we just opened for getting camera access for listing the device labels\n if (openedStream) {\n console.warn('Call listCameras after successfully starting a QR scanner to avoid creating '\n + 'a temporary video stream');\n QrScanner._stopVideoStream(openedStream);\n }\n }\n }\n\n readonly $video: HTMLVideoElement;\n readonly $canvas: HTMLCanvasElement;\n readonly $overlay?: HTMLDivElement;\n private readonly $codeOutlineHighlight?: SVGSVGElement;\n private readonly _onDecode?: (result: QrScanner.ScanResult) => void;\n private readonly _legacyOnDecode?: (result: string) => void;\n private readonly _legacyCanvasSize: number = QrScanner.DEFAULT_CANVAS_SIZE;\n private _preferredCamera: QrScanner.FacingMode | QrScanner.DeviceId = 'environment';\n private readonly _maxScansPerSecond: number = 25;\n private _lastScanTimestamp: number = -1;\n private _scanRegion: QrScanner.ScanRegion;\n private _codeOutlineHighlightRemovalTimeout?: number;\n private _qrEnginePromise: Promise<Worker | BarcodeDetector>\n private _active: boolean = false;\n private _paused: boolean = false;\n private _flashOn: boolean = false;\n private _destroyed: boolean = false;\n\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: QrScanner.ScanResult) => void,\n options: {\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n maxScansPerSecond?: number;\n highlightScanRegion?: boolean,\n highlightCodeOutline?: boolean,\n overlay?: HTMLDivElement,\n /** just a temporary flag until we switch entirely to the new api */\n returnDetailedScanResult?: true,\n },\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n canvasSize?: number,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(video: HTMLVideoElement, onDecode: (result: string) => void, canvasSize?: number);\n constructor(\n video: HTMLLine truncated
|
||||
{"version":3,"file":"qr-scanner.min.js","sources":["src/qr-scanner.ts"],"sourcesContent":["class QrScanner {\n static readonly DEFAULT_CANVAS_SIZE = 400;\n static readonly NO_QR_CODE_FOUND = 'No QR code found';\n private static _disableBarcodeDetector = false;\n\n /** @deprecated */\n static set WORKER_PATH(workerPath: string) {\n console.warn('Setting QrScanner.WORKER_PATH is not required and not supported anymore. '\n + 'Have a look at the README for new setup instructions.');\n }\n\n static async hasCamera(): Promise<boolean> {\n try {\n return !!(await QrScanner.listCameras(false)).length;\n } catch (e) {\n return false;\n }\n }\n\n static async listCameras(requestLabels = false): Promise<Array<QrScanner.Camera>> {\n if (!navigator.mediaDevices) return [];\n\n const enumerateCameras = async (): Promise<Array<MediaDeviceInfo>> =>\n (await navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === 'videoinput');\n\n // Note that enumerateDevices can always be called and does not prompt the user for permission.\n // However, enumerateDevices only includes device labels if served via https and an active media stream exists\n // or permission to access the camera was given. Therefore, if we're not getting labels but labels are requested\n // ask for camera permission by opening a stream.\n let openedStream: MediaStream | undefined;\n try {\n if (requestLabels && (await enumerateCameras()).every((camera) => !camera.label)) {\n openedStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });\n }\n } catch (e) {\n // Fail gracefully, especially if the device has no camera or on mobile when the camera is already in use\n // and some browsers disallow a second stream.\n }\n\n try {\n return (await enumerateCameras()).map((camera, i) => ({\n id: camera.deviceId,\n label: camera.label || (i === 0 ? 'Default Camera' : `Camera ${i + 1}`),\n }));\n } finally {\n // close the stream we just opened for getting camera access for listing the device labels\n if (openedStream) {\n console.warn('Call listCameras after successfully starting a QR scanner to avoid creating '\n + 'a temporary video stream');\n QrScanner._stopVideoStream(openedStream);\n }\n }\n }\n\n readonly $video: HTMLVideoElement;\n readonly $canvas: HTMLCanvasElement;\n readonly $overlay?: HTMLDivElement;\n private readonly $codeOutlineHighlight?: SVGSVGElement;\n private readonly _onDecode?: (result: QrScanner.ScanResult) => void;\n private readonly _legacyOnDecode?: (result: string) => void;\n private readonly _legacyCanvasSize: number = QrScanner.DEFAULT_CANVAS_SIZE;\n private _preferredCamera: QrScanner.FacingMode | QrScanner.DeviceId = 'environment';\n private readonly _maxScansPerSecond: number = 25;\n private _lastScanTimestamp: number = -1;\n private _scanRegion: QrScanner.ScanRegion;\n private _codeOutlineHighlightRemovalTimeout?: number;\n private _qrEnginePromise: Promise<Worker | BarcodeDetector>\n private _active: boolean = false;\n private _paused: boolean = false;\n private _flashOn: boolean = false;\n private _destroyed: boolean = false;\n\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: QrScanner.ScanResult) => void,\n options: {\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n maxScansPerSecond?: number;\n highlightScanRegion?: boolean,\n highlightCodeOutline?: boolean,\n overlay?: HTMLDivElement,\n /** just a temporary flag until we switch entirely to the new api */\n returnDetailedScanResult?: true,\n },\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n canvasSize?: number,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(video: HTMLVideoElement, onDecode: (result: string) => void, canvasSize?: number);\n constructor(\n video: HTMLLine truncated
|
||||
Vendored
+1
-1
@@ -15,7 +15,7 @@ b||"returnDetailedScanResult"in b)?(m=b.scanRegion,c=b.qrEngine,d=b.canvas,f=b.d
|
||||
[d,k]=e._drawToCanvas(p,m,d,f);let r;if(c instanceof Worker){let g=c;b||g.postMessage({type:"inversionMode",data:"both"});r=await new Promise((l,v)=>{let w,u,t;u=q=>{"qrResult"===q.data.type&&(g.removeEventListener("message",u),g.removeEventListener("error",t),clearTimeout(w),null!==q.data.data?l({data:q.data.data,cornerPoints:e._convertPoints(q.data.cornerPoints,m)}):v(e.NO_QR_CODE_FOUND))};t=q=>{g.removeEventListener("message",u);g.removeEventListener("error",t);clearTimeout(w);v("Scanner error: "+
|
||||
(q?q.message||q:"Unknown Error"))};g.addEventListener("message",u);g.addEventListener("error",t);w=setTimeout(()=>t("timeout"),1E4);let x=k.getImageData(0,0,d.width,d.height);g.postMessage({type:"decode",data:x},[x.data.buffer])})}else r=await Promise.race([new Promise((g,l)=>window.setTimeout(()=>l("Scanner error: timeout"),1E4)),(async()=>{try{var [g]=await c.detect(d);if(!g)throw e.NO_QR_CODE_FOUND;return{data:g.rawValue,cornerPoints:e._convertPoints(g.cornerPoints,m)}}catch(l){g=l.message||l;
|
||||
if(/not implemented|service unavailable/.test(g))return e._disableBarcodeDetector=!0,e.scanImage(a,{scanRegion:m,canvas:d,disallowCanvasResizing:f,alsoTryWithoutScanRegion:h});throw`Scanner error: ${g}`;}})()]);return n?r:r.data}catch(p){if(!m||!h)throw p;let k=await e.scanImage(a,{qrEngine:c,canvas:d,disallowCanvasResizing:f});return n?k:k.data}finally{b||e._postWorkerMessage(c,"close")}}setGrayscaleWeights(a,b,c,d=!0){e._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:a,green:b,
|
||||
blue:c,useIntegerApproximation:d})}setInversionMode(a){e._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static async createQrEngine(a){a&&console.warn("Specifying a worker path is not required and not supported anymore.");return!e._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):import("./qr-scanner-worker.min.js").then(b=>b.default)}_onPlay(){this._scanRegion=
|
||||
blue:c,useIntegerApproximation:d})}setInversionMode(a){e._postWorkerMessage(this._qrEnginePromise,"inversionMode",a)}static async createQrEngine(a){a&&console.warn("Specifying a worker path is not required and not supported anymore.");return!e._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):import("./qr-scanner-worker.min.js").then(b=>b.createWorker())}_onPlay(){this._scanRegion=
|
||||
this._calculateScanRegion(this.$video);this._updateOverlay();this.$overlay&&(this.$overlay.style.display="");this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video);this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(a){let b=Math.round(2/3*Math.min(a.videoWidth,a.videoHeight));return{x:Math.round((a.videoWidth-b)/2),y:Math.round((a.videoHeight-b)/2),width:b,height:b,downScaledWidth:this._legacyCanvasSize,
|
||||
downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var a=this.$video,b=a.videoWidth,c=a.videoHeight,d=a.offsetWidth,f=a.offsetHeight,h=a.offsetLeft,m=a.offsetTop,n=window.getComputedStyle(a),p=n.objectFit,k=b/c,r=d/f;switch(p){case "none":var g=b;var l=c;break;case "fill":g=d;l=f;break;default:("cover"===p?k>r:k<r)?(l=f,g=l*k):(g=d,l=g/k),"scale-down"===p&&(g=Math.min(g,b),l=Math.min(l,c))}var [v,w]=n.objectPosition.split(" ").map((t,x)=>{const q=
|
||||
parseFloat(t);return t.endsWith("%")?(x?f-l:d-g)*q/100:q});n=this._scanRegion.width||b;r=this._scanRegion.height||c;p=this._scanRegion.x||0;var u=this._scanRegion.y||0;k=this.$overlay.style;k.width=`${n/b*g}px`;k.height=`${r/c*l}px`;k.top=`${m+w+u/c*l}px`;c=/scaleX\(-1\)/.test(a.style.transform);k.left=`${h+(c?d-v-g:v)+(c?b-p-n:p)/b*g}px`;k.transform=a.style.transform}})}static _convertPoints(a,b){if(!b)return a;let c=b.x||0,d=b.y||0,f=b.width&&b.downScaledWidth?b.width/b.downScaledWidth:1;b=b.height&&
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"file":"qr-scanner.umd.min.js","sources":["src/qr-scanner.ts"],"sourcesContent":["class QrScanner {\n static readonly DEFAULT_CANVAS_SIZE = 400;\n static readonly NO_QR_CODE_FOUND = 'No QR code found';\n private static _disableBarcodeDetector = false;\n\n /** @deprecated */\n static set WORKER_PATH(workerPath: string) {\n console.warn('Setting QrScanner.WORKER_PATH is not required and not supported anymore. '\n + 'Have a look at the README for new setup instructions.');\n }\n\n static async hasCamera(): Promise<boolean> {\n try {\n return !!(await QrScanner.listCameras(false)).length;\n } catch (e) {\n return false;\n }\n }\n\n static async listCameras(requestLabels = false): Promise<Array<QrScanner.Camera>> {\n if (!navigator.mediaDevices) return [];\n\n const enumerateCameras = async (): Promise<Array<MediaDeviceInfo>> =>\n (await navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === 'videoinput');\n\n // Note that enumerateDevices can always be called and does not prompt the user for permission.\n // However, enumerateDevices only includes device labels if served via https and an active media stream exists\n // or permission to access the camera was given. Therefore, if we're not getting labels but labels are requested\n // ask for camera permission by opening a stream.\n let openedStream: MediaStream | undefined;\n try {\n if (requestLabels && (await enumerateCameras()).every((camera) => !camera.label)) {\n openedStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });\n }\n } catch (e) {\n // Fail gracefully, especially if the device has no camera or on mobile when the camera is already in use\n // and some browsers disallow a second stream.\n }\n\n try {\n return (await enumerateCameras()).map((camera, i) => ({\n id: camera.deviceId,\n label: camera.label || (i === 0 ? 'Default Camera' : `Camera ${i + 1}`),\n }));\n } finally {\n // close the stream we just opened for getting camera access for listing the device labels\n if (openedStream) {\n console.warn('Call listCameras after successfully starting a QR scanner to avoid creating '\n + 'a temporary video stream');\n QrScanner._stopVideoStream(openedStream);\n }\n }\n }\n\n readonly $video: HTMLVideoElement;\n readonly $canvas: HTMLCanvasElement;\n readonly $overlay?: HTMLDivElement;\n private readonly $codeOutlineHighlight?: SVGSVGElement;\n private readonly _onDecode?: (result: QrScanner.ScanResult) => void;\n private readonly _legacyOnDecode?: (result: string) => void;\n private readonly _legacyCanvasSize: number = QrScanner.DEFAULT_CANVAS_SIZE;\n private _preferredCamera: QrScanner.FacingMode | QrScanner.DeviceId = 'environment';\n private readonly _maxScansPerSecond: number = 25;\n private _lastScanTimestamp: number = -1;\n private _scanRegion: QrScanner.ScanRegion;\n private _codeOutlineHighlightRemovalTimeout?: number;\n private _qrEnginePromise: Promise<Worker | BarcodeDetector>\n private _active: boolean = false;\n private _paused: boolean = false;\n private _flashOn: boolean = false;\n private _destroyed: boolean = false;\n\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: QrScanner.ScanResult) => void,\n options: {\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n maxScansPerSecond?: number;\n highlightScanRegion?: boolean,\n highlightCodeOutline?: boolean,\n overlay?: HTMLDivElement,\n /** just a temporary flag until we switch entirely to the new api */\n returnDetailedScanResult?: true,\n },\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n canvasSize?: number,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(video: HTMLVideoElement, onDecode: (result: string) => void, canvasSize?: number);\n constructor(\n video: Line truncated
|
||||
{"version":3,"file":"qr-scanner.umd.min.js","sources":["src/qr-scanner.ts"],"sourcesContent":["class QrScanner {\n static readonly DEFAULT_CANVAS_SIZE = 400;\n static readonly NO_QR_CODE_FOUND = 'No QR code found';\n private static _disableBarcodeDetector = false;\n\n /** @deprecated */\n static set WORKER_PATH(workerPath: string) {\n console.warn('Setting QrScanner.WORKER_PATH is not required and not supported anymore. '\n + 'Have a look at the README for new setup instructions.');\n }\n\n static async hasCamera(): Promise<boolean> {\n try {\n return !!(await QrScanner.listCameras(false)).length;\n } catch (e) {\n return false;\n }\n }\n\n static async listCameras(requestLabels = false): Promise<Array<QrScanner.Camera>> {\n if (!navigator.mediaDevices) return [];\n\n const enumerateCameras = async (): Promise<Array<MediaDeviceInfo>> =>\n (await navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === 'videoinput');\n\n // Note that enumerateDevices can always be called and does not prompt the user for permission.\n // However, enumerateDevices only includes device labels if served via https and an active media stream exists\n // or permission to access the camera was given. Therefore, if we're not getting labels but labels are requested\n // ask for camera permission by opening a stream.\n let openedStream: MediaStream | undefined;\n try {\n if (requestLabels && (await enumerateCameras()).every((camera) => !camera.label)) {\n openedStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });\n }\n } catch (e) {\n // Fail gracefully, especially if the device has no camera or on mobile when the camera is already in use\n // and some browsers disallow a second stream.\n }\n\n try {\n return (await enumerateCameras()).map((camera, i) => ({\n id: camera.deviceId,\n label: camera.label || (i === 0 ? 'Default Camera' : `Camera ${i + 1}`),\n }));\n } finally {\n // close the stream we just opened for getting camera access for listing the device labels\n if (openedStream) {\n console.warn('Call listCameras after successfully starting a QR scanner to avoid creating '\n + 'a temporary video stream');\n QrScanner._stopVideoStream(openedStream);\n }\n }\n }\n\n readonly $video: HTMLVideoElement;\n readonly $canvas: HTMLCanvasElement;\n readonly $overlay?: HTMLDivElement;\n private readonly $codeOutlineHighlight?: SVGSVGElement;\n private readonly _onDecode?: (result: QrScanner.ScanResult) => void;\n private readonly _legacyOnDecode?: (result: string) => void;\n private readonly _legacyCanvasSize: number = QrScanner.DEFAULT_CANVAS_SIZE;\n private _preferredCamera: QrScanner.FacingMode | QrScanner.DeviceId = 'environment';\n private readonly _maxScansPerSecond: number = 25;\n private _lastScanTimestamp: number = -1;\n private _scanRegion: QrScanner.ScanRegion;\n private _codeOutlineHighlightRemovalTimeout?: number;\n private _qrEnginePromise: Promise<Worker | BarcodeDetector>\n private _active: boolean = false;\n private _paused: boolean = false;\n private _flashOn: boolean = false;\n private _destroyed: boolean = false;\n\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: QrScanner.ScanResult) => void,\n options: {\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n maxScansPerSecond?: number;\n highlightScanRegion?: boolean,\n highlightCodeOutline?: boolean,\n overlay?: HTMLDivElement,\n /** just a temporary flag until we switch entirely to the new api */\n returnDetailedScanResult?: true,\n },\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n calculateScanRegion?: (video: HTMLVideoElement) => QrScanner.ScanRegion,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(\n video: HTMLVideoElement,\n onDecode: (result: string) => void,\n onDecodeError?: (error: Error | string) => void,\n canvasSize?: number,\n preferredCamera?: QrScanner.FacingMode | QrScanner.DeviceId,\n );\n /** @deprecated */\n constructor(video: HTMLVideoElement, onDecode: (result: string) => void, canvasSize?: number);\n constructor(\n video: Line truncated
|
||||
+2
-2
@@ -15,9 +15,9 @@ function workerScriptToDynamicImport() {
|
||||
if (chunk.type !== 'chunk') {
|
||||
continue;
|
||||
}
|
||||
chunk.code = 'export default new Worker(URL.createObjectURL(new Blob([`'
|
||||
chunk.code = 'export const createWorker=()=>new Worker(URL.createObjectURL(new Blob([`'
|
||||
+ chunk.code.replace(/`/g, '\\`').replace(/\${/g, '\\${')
|
||||
+ '`]),{type: "application/javascript"}))';
|
||||
+ '`]),{type:"application/javascript"}))';
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
+2
-1
@@ -626,7 +626,8 @@ class QrScanner {
|
||||
return useNativeBarcodeDetector
|
||||
? new BarcodeDetector({ formats: ['qr_code'] })
|
||||
// @ts-ignore no types defined
|
||||
: (import('./qr-scanner-worker.min.js') as Promise<{ default: Worker }>).then((module) => module.default);
|
||||
: (import('./qr-scanner-worker.min.js') as Promise<{ createWorker: () => Worker }>)
|
||||
.then((module) => module.createWorker());
|
||||
}
|
||||
|
||||
private _onPlay(): void {
|
||||
|
||||
Reference in new issue
Block a user