@qr-platform/qr-code.js
Version:
QRCode.js is a professional JavaScript/TypeScript library for creating customized QR codes, offering a blend of simplicity and sophistication. With versatile styling options—dot shapes, colors, gradients, embedded images, borders, and text—it enables you
2 lines (1 loc) • 21.5 kB
JavaScript
import{Resvg as e}from"@resvg/resvg-js";import{Image as t}from"image-js";import r from"@undecaf/zbar-wasm/dist/zbar.wasm";const n=async(e,t)=>{try{t(await WebAssembly.instantiate(r,e),r)}catch(e){throw console.error("Zbar WASM: Error during instantiation:",e),e}},a=function(e){function t(e,t,r,n){return new(r||(r=Promise))((function(t,a){function i(e){try{o(n.next(e))}catch(e){a(e)}}function s(e){try{o(n.throw(e))}catch(e){a(e)}}function o(e){var n;e.done?t(e.value):(n=e.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,s)}o((n=n.apply(e,[])).next())}))}function r(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})})),r}"function"==typeof SuppressedError&&SuppressedError;var n={exports:{}};const a=r(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));function i(e,t){for(var r=0,n=e.length-1;n>=0;n--){var a=e[n];"."===a?e.splice(n,1):".."===a?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}var s=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,o=function(e){return s.exec(e).slice(1)};function c(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:"/";if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");n&&(e=n+"/"+e,t="/"===n.charAt(0))}return(t?"/":"")+(e=i(A(e.split("/"),(function(e){return!!e})),!t).join("/"))||"."}function u(e){var t=l(e),r="/"===p(e,-1);return(e=i(A(e.split("/"),(function(e){return!!e})),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function l(e){return"/"===e.charAt(0)}function d(){return u(A(Array.prototype.slice.call(arguments,0),(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))}function f(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=c(e).substr(1),t=c(t).substr(1);for(var n=r(e.split("/")),a=r(t.split("/")),i=Math.min(n.length,a.length),s=i,o=0;o<i;o++)if(n[o]!==a[o]){s=o;break}var u=[];for(o=s;o<n.length;o++)u.push("..");return(u=u.concat(a.slice(s))).join("/")}function h(e){var t=o(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."}function m(e,t){var r=o(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r}function g(e){return o(e)[3]}const _={extname:g,basename:m,dirname:h,sep:"/",delimiter:":",relative:f,join:d,isAbsolute:l,normalize:u,resolve:c};function A(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n<e.length;n++)t(e[n],n,e)&&r.push(e[n]);return r}var p="b"==="ab".substr(-1)?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)};const y=r(Object.freeze(Object.defineProperty({__proto__:null,basename:m,default:_,delimiter:":",dirname:h,extname:g,isAbsolute:l,join:d,normalize:u,relative:f,resolve:c,sep:"/"},Symbol.toStringTag,{value:"Module"})));!function(e){var t,r=(t="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,"undefined"!=typeof __filename&&(t=t||__filename),function(e={}){var r,n,i=e;i.ready=new Promise(((e,t)=>{r=e,n=t}));var s,o,c,u=Object.assign({},i),l="object"==typeof window,d="function"==typeof importScripts,f="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,h="";if(f){var m=a,g=y;h=d?g.dirname(h)+"/":__dirname+"/",s=(e,t)=>(e=F(e)?new URL(e):g.normalize(e),m.readFileSync(e,t?void 0:"utf8")),c=e=>{var t=s(e,!0);return t.buffer||(t=new Uint8Array(t)),t},o=(e,t,r,n=!0)=>{e=F(e)?new URL(e):g.normalize(e),m.readFile(e,n?void 0:"utf8",((e,a)=>{e?r(e):t(n?a.buffer:a)}))},!i.thisProgram&&process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),i.inspect=()=>"[Emscripten Module object]"}else(l||d)&&(d?h=self.location.href:"undefined"!=typeof document&&document.currentScript&&(h=document.currentScript.src),t&&(h=t),h=0!==h.indexOf("blob:")?h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},d&&(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var _,A,p,R=i.print||console.log.bind(console),v=i.printErr||console.error.bind(console);Object.assign(i,u),u=null,i.arguments&&i.arguments,i.thisProgram&&i.thisProgram,i.quit&&i.quit,i.wasmBinary&&(_=i.wasmBinary),i.noExitRuntime,"object"!=typeof WebAssembly&&D("no native wasm support detected");var E,B,b=!1;function I(){var e=A.buffer;i.HEAP8=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAP32=new Int32Array(e),i.HEAPU8=E=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAPU32=B=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=new Float64Array(e)}var w=[],Z=[],S=[],C=0,N=null;function D(e){i.onAbort&&i.onAbort(e),v(e="Aborted("+e+")"),b=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw n(t),t}var O,T;function P(e){return e.startsWith("data:application/octet-stream;base64,")}function F(e){return e.startsWith("file://")}function x(e){if(e==O&&_)return new Uint8Array(_);if(c)return c(e);throw"both async and sync fetching of the wasm failed"}function G(e,t,r){return function(e){if(!_&&(l||d)){if("function"==typeof fetch&&!F(e))return fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>x(e)));if(o)return new Promise(((t,r)=>{o(e,(e=>t(new Uint8Array(e))),r)}))}return Promise.resolve().then((()=>x(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(r,(e=>{v("failed to asynchronously prepare wasm: "+e),D(e)}))}P(O="zbar.wasm")||(T=O,O=i.locateFile?i.locateFile(T,h):h+T);var U,H=e=>{for(;e.length>0;)e.shift()(i)},$=e=>{var t=e-A.buffer.byteLength+65535>>>16;try{return A.grow(t),I(),1}catch(e){}},M="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,j=[null,[],[]],L=(e,t)=>{var r=j[e];0===t||10===t?((1===e?R:v)(((e,t)=>{for(var r=t+void 0,n=t;e[n]&&!(n>=r);)++n;if(n-t>16&&e.buffer&&M)return M.decode(e.subarray(t,n));for(var a="";t<n;){var i=e[t++];if(128&i){var s=63&e[t++];if(192!=(224&i)){var o=63&e[t++];if((i=224==(240&i)?(15&i)<<12|s<<6|o:(7&i)<<18|s<<12|o<<6|63&e[t++])<65536)a+=String.fromCharCode(i);else{var c=i-65536;a+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a})(r,0)),r.length=0):r.push(t)},V={d:()=>!0,e:function(){return Date.now()},c:e=>{var t=E.length,r=2147483648;if((e>>>=0)>r)return!1;for(var n,a=1;a<=4;a*=2){var i=t*(1+.2/a);i=Math.min(i,e+100663296);var s=Math.min(r,(n=Math.max(e,i))+(65536-n%65536)%65536);if($(s))return!0}return!1},f:e=>52,b:function(e,t,r,n,a){return 70},a:(e,t,r,n)=>{for(var a=0,i=0;i<r;i++){var s=B[t>>2],o=B[t+4>>2];t+=8;for(var c=0;c<o;c++)L(e,E[s+c]);a+=o}return B[n>>2]=a,0}};function W(){function e(){U||(U=!0,i.calledRun=!0,b||(H(Z),r(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)e=i.postRun.shift(),S.unshift(e);var e;H(S)}()))}C>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)e=i.preRun.shift(),w.unshift(e);var e;H(w)}(),C>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),e()}),1)):e()))}if(function(){var e,t,r,a,s={a:V};function o(e,t){var r,n=e.exports;return A=(p=n).g,I(),p.s,r=p.h,Z.unshift(r),function(){if(C--,i.monitorRunDependencies&&i.monitorRunDependencies(C),0==C&&N){var e=N;N=null,e()}}(),n}if(C++,i.monitorRunDependencies&&i.monitorRunDependencies(C),i.instantiateWasm)try{return i.instantiateWasm(s,o)}catch(e){v("Module.instantiateWasm callback failed with error: "+e),n(e)}(e=_,t=O,r=s,a=function(e){o(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||P(t)||F(t)||f||"function"!=typeof fetch?G(t,r,a):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,r).then(a,(function(e){return v("wasm streaming compile failed: "+e),v("falling back to ArrayBuffer instantiation"),G(t,r,a)}))))).catch(n)}(),i._ImageScanner_create=()=>(i._ImageScanner_create=p.i)(),i._ImageScanner_destory=e=>(i._ImageScanner_destory=p.j)(e),i._ImageScanner_set_config=(e,t,r,n)=>(i._ImageScanner_set_config=p.k)(e,t,r,n),i._ImageScanner_enable_cache=(e,t)=>(i._ImageScanner_enable_cache=p.l)(e,t),i._ImageScanner_recycle_image=(e,t)=>(i._ImageScanner_recycle_image=p.m)(e,t),i._ImageScanner_get_results=e=>(i._ImageScanner_get_results=p.n)(e),i._ImageScanner_scan=(e,t)=>(i._ImageScanner_scan=p.o)(e,t),i._Image_create=(e,t,r,n,a,s)=>(i._Image_create=p.p)(e,t,r,n,a,s),i._Image_destory=e=>(i._Image_destory=p.q)(e),i._Image_get_symbols=e=>(i._Image_get_symbols=p.r)(e),i._free=e=>(i._free=p.t)(e),i._malloc=e=>(i._malloc=p.u)(e),N=function e(){U||W(),U||(N=e)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return W(),e.ready});e.exports=r}(n);const R=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(n.exports);let v;function E(e={}){v=function(){return t(this,0,void 0,(function*(){const t=yield R(e);if(t)return t;throw Error("WASM was not loaded")}))}()}function B(){return t(this,0,void 0,(function*(){return v||E(),yield v}))}var b,I,w;e.ZBarSymbolType=void 0,(b=e.ZBarSymbolType||(e.ZBarSymbolType={}))[b.ZBAR_NONE=0]="ZBAR_NONE",b[b.ZBAR_PARTIAL=1]="ZBAR_PARTIAL",b[b.ZBAR_EAN2=2]="ZBAR_EAN2",b[b.ZBAR_EAN5=5]="ZBAR_EAN5",b[b.ZBAR_EAN8=8]="ZBAR_EAN8",b[b.ZBAR_UPCE=9]="ZBAR_UPCE",b[b.ZBAR_ISBN10=10]="ZBAR_ISBN10",b[b.ZBAR_UPCA=12]="ZBAR_UPCA",b[b.ZBAR_EAN13=13]="ZBAR_EAN13",b[b.ZBAR_ISBN13=14]="ZBAR_ISBN13",b[b.ZBAR_COMPOSITE=15]="ZBAR_COMPOSITE",b[b.ZBAR_I25=25]="ZBAR_I25",b[b.ZBAR_DATABAR=34]="ZBAR_DATABAR",b[b.ZBAR_DATABAR_EXP=35]="ZBAR_DATABAR_EXP",b[b.ZBAR_CODABAR=38]="ZBAR_CODABAR",b[b.ZBAR_CODE39=39]="ZBAR_CODE39",b[b.ZBAR_PDF417=57]="ZBAR_PDF417",b[b.ZBAR_QRCODE=64]="ZBAR_QRCODE",b[b.ZBAR_SQCODE=80]="ZBAR_SQCODE",b[b.ZBAR_CODE93=93]="ZBAR_CODE93",b[b.ZBAR_CODE128=128]="ZBAR_CODE128",b[b.ZBAR_SYMBOL=255]="ZBAR_SYMBOL",b[b.ZBAR_ADDON2=512]="ZBAR_ADDON2",b[b.ZBAR_ADDON5=1280]="ZBAR_ADDON5",b[b.ZBAR_ADDON=1792]="ZBAR_ADDON",e.ZBarConfigType=void 0,(I=e.ZBarConfigType||(e.ZBarConfigType={}))[I.ZBAR_CFG_ENABLE=0]="ZBAR_CFG_ENABLE",I[I.ZBAR_CFG_ADD_CHECK=1]="ZBAR_CFG_ADD_CHECK",I[I.ZBAR_CFG_EMIT_CHECK=2]="ZBAR_CFG_EMIT_CHECK",I[I.ZBAR_CFG_ASCII=3]="ZBAR_CFG_ASCII",I[I.ZBAR_CFG_BINARY=4]="ZBAR_CFG_BINARY",I[I.ZBAR_CFG_NUM=5]="ZBAR_CFG_NUM",I[I.ZBAR_CFG_MIN_LEN=32]="ZBAR_CFG_MIN_LEN",I[I.ZBAR_CFG_MAX_LEN=33]="ZBAR_CFG_MAX_LEN",I[I.ZBAR_CFG_UNCERTAINTY=64]="ZBAR_CFG_UNCERTAINTY",I[I.ZBAR_CFG_POSITION=128]="ZBAR_CFG_POSITION",I[I.ZBAR_CFG_TEST_INVERTED=129]="ZBAR_CFG_TEST_INVERTED",I[I.ZBAR_CFG_X_DENSITY=256]="ZBAR_CFG_X_DENSITY",I[I.ZBAR_CFG_Y_DENSITY=257]="ZBAR_CFG_Y_DENSITY",e.ZBarOrientation=void 0,(w=e.ZBarOrientation||(e.ZBarOrientation={}))[w.ZBAR_ORIENT_UNKNOWN=-1]="ZBAR_ORIENT_UNKNOWN",w[w.ZBAR_ORIENT_UP=0]="ZBAR_ORIENT_UP",w[w.ZBAR_ORIENT_RIGHT=1]="ZBAR_ORIENT_RIGHT",w[w.ZBAR_ORIENT_DOWN=2]="ZBAR_ORIENT_DOWN",w[w.ZBAR_ORIENT_LEFT=3]="ZBAR_ORIENT_LEFT";class Z{constructor(e,t){this.ptr=e,this.inst=t}checkAlive(){if(!this.ptr)throw Error("Call after destroyed")}getPointer(){return this.checkAlive(),this.ptr}}class S{constructor(e,t){this.ptr=e,this.ptr32=e>>2,this.buf=t,this.HEAP8=new Int8Array(t),this.HEAPU32=new Uint32Array(t),this.HEAP32=new Int32Array(t)}}class C extends S{get type(){return this.HEAPU32[this.ptr32]}get data(){const e=this.HEAPU32[this.ptr32+4],t=this.HEAPU32[this.ptr32+5];return Int8Array.from(this.HEAP8.subarray(t,t+e))}get points(){const e=this.HEAPU32[this.ptr32+7],t=this.HEAPU32[this.ptr32+8]>>2,r=[];for(let n=0;n<e;++n){const e=this.HEAP32[t+2*n],a=this.HEAP32[t+2*n+1];r.push({x:e,y:a})}return r}get orientation(){return this.HEAP32[this.ptr32+9]}get next(){const e=this.HEAPU32[this.ptr32+11];return e?new C(e,this.buf):null}get time(){return this.HEAPU32[this.ptr32+13]}get cacheCount(){return this.HEAP32[this.ptr32+14]}get quality(){return this.HEAP32[this.ptr32+15]}}class N extends S{get head(){const e=this.HEAPU32[this.ptr32+2];return e?new C(e,this.buf):null}}class D{constructor(t){this.type=t.type,this.typeName=e.ZBarSymbolType[this.type],this.data=t.data,this.points=t.points,this.orientation=t.orientation,this.time=t.time,this.cacheCount=t.cacheCount,this.quality=t.quality}static createSymbolsFromPtr(e,t){if(0==e)return[];let r=new N(e,t).head;const n=[];for(;null!==r;)n.push(new D(r)),r=r.next;return n}decode(e){return new TextDecoder(e).decode(this.data)}}class O extends Z{static createFromGrayBuffer(e,r,n,a=0){return t(this,0,void 0,(function*(){const t=yield B(),i=new Uint8Array(n),s=e*r;if(s!==i.byteLength)throw Error(`data length (${i.byteLength} bytes) does not match width and height (${s} bytes)`);const o=t._malloc(s);return t.HEAPU8.set(i,o),new this(t._Image_create(e,r,808466521,o,s,a),t)}))}static createFromRGBABuffer(e,r,n,a=0){return t(this,0,void 0,(function*(){const t=yield B(),i=new Uint8Array(n),s=e*r;if(4*s!==i.byteLength)throw Error(`data length (${i.byteLength} bytes) does not match width and height (${4*s} bytes)`);const o=t._malloc(s),c=o+s,u=t.HEAPU8;for(let e=o,t=0;e<c;e++,t+=4)u[e]=19595*i[t]+38469*i[t+1]+7472*i[t+2]>>16;return new this(t._Image_create(e,r,808466521,o,s,a),t)}))}destroy(){this.checkAlive(),this.inst._Image_destory(this.ptr),this.ptr=0}getSymbols(){this.checkAlive();const e=this.inst._Image_get_symbols(this.ptr);return D.createSymbolsFromPtr(e,this.inst.HEAPU8.buffer)}}class T extends Z{static create(){return t(this,0,void 0,(function*(){const e=yield B();return new this(e._ImageScanner_create(),e)}))}destroy(){this.checkAlive(),this.inst._ImageScanner_destory(this.ptr),this.ptr=0}setConfig(e,t,r){return this.checkAlive(),this.inst._ImageScanner_set_config(this.ptr,e,t,r)}enableCache(e=!0){this.checkAlive(),this.inst._ImageScanner_enable_cache(this.ptr,e)}recycleImage(e){this.checkAlive(),this.inst._ImageScanner_recycle_image(this.ptr,e.getPointer())}getResults(){this.checkAlive();const e=this.inst._ImageScanner_get_results(this.ptr);return D.createSymbolsFromPtr(e,this.inst.HEAPU8.buffer)}scan(e){return this.checkAlive(),this.inst._ImageScanner_scan(this.ptr,e.getPointer())}}const P=()=>t(void 0,0,void 0,(function*(){const t=yield T.create();return t.setConfig(e.ZBarSymbolType.ZBAR_NONE,e.ZBarConfigType.ZBAR_CFG_BINARY,1),t}));let F;const x=(e,r)=>t(void 0,0,void 0,(function*(){void 0===r&&(r=F||(yield P()),F=r);const t=r.scan(e);if(t<0)throw Error("Scan Failed");return 0===t?[]:e.getSymbols()})),G=(e,r,n,a)=>t(void 0,0,void 0,(function*(){const t=yield O.createFromRGBABuffer(r,n,e),i=yield x(t,a);return t.destroy(),i}));return e.ZBarImage=O,e.ZBarScanner=T,e.ZBarSymbol=D,e.getDefaultScanner=P,e.getInstance=B,e.scanGrayBuffer=(e,r,n,a)=>t(void 0,0,void 0,(function*(){const t=yield O.createFromGrayBuffer(r,n,e),i=yield x(t,a);return t.destroy(),i})),e.scanImageData=(e,r)=>t(void 0,0,void 0,(function*(){return yield G(e.data.buffer,e.width,e.height,r)})),e.scanRGBABuffer=G,e.setModuleArgs=E,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});a&&a.setModuleArgs&&a.setModuleArgs({instantiateWasm:n});let i=!1;const s=e=>{i&&console.debug("[QR Validator]",e)},o=new class{constructor(e={}){this.maxRetries=e.maxRetries??5,this.retryInterval=e.retryInterval??100,this.debug=e.debug??!1}log(e){this.debug&&console.log(`[QRValidatorZbarNode] ${e}`)}async validate(e,t=!1){try{if(!a.scanImageData)throw new Error("zbar-wasm library not found. Please ensure @undecaf/zbar-wasm is installed and loaded correctly.");return this.validateWithRetry(e,t)}catch(e){return this.log(`Validation error: ${e instanceof Error?e.message:String(e)}`),{isValid:!1,message:e instanceof Error?e.message:String(e),errorCode:"VALIDATION_ERROR",attempts:1,validator:"ZBar"}}}sleep(e){return new Promise((t=>setTimeout(t,e)))}async processImageResvg(t,r){try{const n=new e(t,{fitTo:{mode:"zoom",value:2}}).render(),a=n.width,i=n.height,s=n.pixels,o=Buffer.from(s);if(r)for(let e=0;e<o.length;e+=4)o[e]=255-o[e],o[e+1]=255-o[e+1],o[e+2]=255-o[e+2];return{imageData:{data:new Uint8ClampedArray(o),width:a,height:i},metadata:{width:a,height:i}}}catch(e){throw this.log(`Image processing error: ${e instanceof Error?e.message:String(e)}`),e}}async validateWithRetry(e,t){let r=0,n=null;const a=e;let i=!1;do{r++;try{const e=this.processImageResvg,{imageData:s}=await e(a,t);if(this.log(`Processed image ${s.width}x${s.height} pixels`),this.debug&&await this.saveDebugImage(s,`debug/qr-attempt-${r}-${i?"inverted":"normal"}`),n=await this.decodeQR(s),this.log(`Barcode scan attempt ${r}: ${n.success?"Success":"Failed"}`),n.success)return n.attempts=r,{isValid:!0,data:n.data,format:n.format,attempts:r,isInverted:t}}catch(e){this.log(`Attempt ${r} failed: ${e instanceof Error?e.message:String(e)}`),n={success:!1,error:e instanceof Error?e.message:String(e),errorCode:"PROCESSING_ERROR"}}!t||i?r<this.maxRetries&&await this.sleep(this.retryInterval):(i=!0,this.log("Switching to inverted image for next attempt"))}while(r<this.maxRetries);return{isValid:!1,attempts:r,message:`No barcode detected after ${r} attempts`,validator:"ZBar",errorCode:"DECODER_ERROR"}}async validateImageData(e){let t=0,r=null;do{t++;try{if(this.log(`Attempting to decode ImageData ${e.width}x${e.height} pixels (Attempt ${t})`),this.debug&&await this.saveDebugImage(e,`debug/qr-imagedata-attempt-${t}`),r=await this.decodeQR(e),this.log(`ImageData scan attempt ${t}: ${r.success?"Success":"Failed"}`),r.success)return r.attempts=t,{isValid:!0,data:r.data,format:r.format,attempts:t,isInverted:!1}}catch(e){this.log(`Attempt ${t} failed: ${e instanceof Error?e.message:String(e)}`),r={success:!1,error:e instanceof Error?e.message:String(e),errorCode:"PROCESSING_ERROR"}}t<this.maxRetries&&await this.sleep(this.retryInterval)}while(t<this.maxRetries);return{isValid:!1,attempts:t,message:`No barcode detected from ImageData after ${t} attempts`,errorCode:"DECODER_ERROR",validator:"ZBar"}}async saveDebugImage(e,r){try{const n=new t(e.width,e.height,e.data,{kind:"RGBA"}),a=`${r}-${Date.now()}`;await n.save(`${a}.png`,{format:"png"}),this.log(`Debug image saved to: ${a}`)}catch(e){this.log(`Failed to save debug image: ${e instanceof Error?e.message:String(e)}`)}}async decodeQR(e){try{let t;try{t=await a.scanImageData(e)}catch(e){this.log(`Error decoding QR code: ${e}`)}if(t&&t.length>0){const e=t[0],r=e.decode();return this.log(`Detected: ${e.typeName} - ${r}`),{success:!0,data:r,format:e.typeName||"UNKNOWN",confidence:.9,count:t.length,allSymbols:t.map((e=>({data:e.decode(),type:e.typeName,points:e.points})))}}return{success:!1,error:"No barcode detected",errorCode:"NO_BARCODE_DETECTED"}}catch(e){return this.log("Decoder error:"),console.error(e instanceof Error?e.message:String(e)),{success:!1,error:`Decoder error: ${e instanceof Error?e.message:String(e)}`,errorCode:"DECODER_ERROR"}}}}({maxRetries:3,debug:!1,retryInterval:300}),c={validateZbar:async(e,t=!1)=>{i=t||i,i&&console.time("scan-validator");const r=[{name:"Normal SVG",execute:async()=>{if(!e)throw new Error("No svg source");const t=await o.validate(e,!1);if(!t.isValid||!t.data)throw new Error("No text found in normal QR code");return{isValid:!0,isInverted:!1,data:t.data,message:t.message||"Decoded successfully.",attempts:t.attempts,validator:"ZBar"}}},{name:"Inverted SVG",execute:async()=>{if(!e)throw new Error("No svg source for inverted attempt");const t=await o.validate(e,!0);if(!t.isValid||!t.data)throw new Error("No text found in inverted QR code");return{isValid:!0,isInverted:!0,data:t.data,message:t.message||"Decoded successfully (inverted).",attempts:t.attempts,validator:"ZBar"}}}];for(const e of r)try{s(`Trying ${e.name} decode...`);const t=await e.execute();return i&&console.timeEnd("scan-validator"),t}catch(t){s(`${e.name} decode failed:`),s(t)}return i&&console.timeEnd("scan-validator"),{isValid:!1,message:"Failed to decode QR code after all attempts."}},validateZbarImageData:async(e,t=!1)=>{i=t||i,i&&console.time("scan-validator-imagedata");try{const t=await o.validateImageData(e);return i&&console.timeEnd("scan-validator-imagedata"),{isValid:t.isValid,isInverted:t.isInverted??!1,data:t.data,message:t.message||(t.isValid?"Decoded successfully from ImageData.":"Validation failed."),attempts:t.attempts,validator:"ZBar"}}catch(e){return s(`Error during Zbar ImageData validation: ${e}`),i&&console.timeEnd("scan-validator-imagedata"),{isValid:!1,isInverted:!1,message:e instanceof Error?e.message:"Unknown error during Zbar ImageData validation"}}}};export{c as qrValidatorZbar};