import {casePixels,hash,gtin} from './inputs.js'; let scan,cleanup=()=>{};const allFormats=new URL(self.location).searchParams.get('scope')==='formats';const formats=allFormats?['EAN13','EAN8','UPCA','UPCE','QRCode','DataMatrix','PDF417','Aztec','MaxiCode','Code128','Code39','Code93','ITF','Codabar','DataBar','DataBarExpanded']:['EAN13','EAN8','UPCA','UPCE']; async function init(engine){if(engine==='native'){if(!('BarcodeDetector'in self))throw new Error('Native BarcodeDetector unavailable; no fallback is used.');const supported=await BarcodeDetector.getSupportedFormats(),selected=allFormats?supported:['ean_13','ean_8','upc_a','upc_e'].filter(x=>supported.includes(x));if(!selected.length)throw new Error('Native retail formats unavailable.');const detector=new BarcodeDetector({formats:selected});scan=async image=>{const start=performance.now(),r=await detector.detect(image),reads=r.map(x=>({format:x.format,text:x.rawValue,polygon:x.cornerPoints.map(p=>[p.x,p.y])}));return{ms:performance.now()-start,reads}};return{engine,api:'BarcodeDetector',supported,selected,backendVersion:'not exposed by browser',fallback:false}} if(engine==='zxing'){const zx=await import('./vendor/zxing/es/reader/index.js');await zx.prepareZXingModule({overrides:{wasmBinary:new Uint8Array(await(await fetch('./vendor/zxing/reader/zxing_reader.wasm')).arrayBuffer())},fireImmediately:true});scan=async image=>{const start=performance.now(),r=await zx.readBarcodes(image,{formats}),reads=r.filter(x=>x.isValid).map(x=>({format:x.format,text:x.text,polygon:Object.values(x.position).map(p=>[p.x,p.y])}));return{ms:performance.now()-start,reads}};return{engine,version:'3.1.5',formats,defaults:zx.defaultReaderOptions}} if(engine==='zbar'){const zb=await import('./vendor/zbar/index.mjs');zb.setModuleArgs({locateFile:()=>new URL('./vendor/zbar/zbar.wasm',self.location).href});const types={EAN13:zb.ZBarSymbolType.ZBAR_EAN13,EAN8:zb.ZBarSymbolType.ZBAR_EAN8,UPCA:zb.ZBarSymbolType.ZBAR_UPCA,UPCE:zb.ZBarSymbolType.ZBAR_UPCE,...(allFormats?{QRCode:zb.ZBarSymbolType.ZBAR_QRCODE,Code128:zb.ZBarSymbolType.ZBAR_CODE128,Code39:zb.ZBarSymbolType.ZBAR_CODE39,Code93:zb.ZBarSymbolType.ZBAR_CODE93,ITF:zb.ZBarSymbolType.ZBAR_I25,Codabar:zb.ZBarSymbolType.ZBAR_CODABAR,DataBar:zb.ZBarSymbolType.ZBAR_DATABAR,DataBarExpanded:zb.ZBarSymbolType.ZBAR_DATABAR_EXP}: {})};scan=async image=>{const scanner=await zb.ZBarScanner.create();try{scanner.enableCache(false);scanner.setConfig(zb.ZBarSymbolType.ZBAR_NONE,zb.ZBarConfigType.ZBAR_CFG_ENABLE,0);for(const t of Object.values(types))scanner.setConfig(t,zb.ZBarConfigType.ZBAR_CFG_ENABLE,1);const start=performance.now(),r=await zb.scanRGBABuffer(image.data.buffer,image.width,image.height,scanner),reads=r.map(x=>({format:Object.keys(types).find(f=>types[f]===x.type)??x.typeName,text:x.decode(),polygon:x.points.map(p=>[p.x,p.y])}));return{ms:performance.now()-start,reads}}finally{scanner.destroy()}};return{engine,version:'0.11.0',formats,cache:false,scannerCreationTimed:false}} if(engine==='tapirscan'){const version=new URL(self.location).searchParams.get('version');if(!['1.5.0','1.4.0','1.3.0','1.2.2'].includes(version))throw Error('Unsupported pinned release');const {Scanner}=await import('/artifacts/'+version+'/package/dist/index.js'),params=new URL(self.location).searchParams,options=params.has('turbo')?{experimentalTurbo:Number(params.get('turbo')),eanAddOnPolicy:'ignore'}:{mode:params.get('mode')||'medium'},scanner=await Scanner.create({...options,formats,wasmBaseUrl:new URL('/artifacts/'+version+'/package/wasm/',self.location).href});scan=async image=>{const start=performance.now(),r=scanner.scan(image),reads=r.barcodes.map(x=>({format:x.format,text:x.text,polygon:x.polygon}));return{ms:performance.now()-start,reads,unfinished:r.unfinished}};return{engine,version,options,formats}} // Quagga2 mirrors Quagga.decodeSingle inside the worker: luma at full size, bilinear resampling to inputStream.size (Quagga's // default 800 px long side, or native size for quagga-full), crop to whole locator patches, then locate and decode; all timed. // The npm bundle runs with the live demo's two guarded fixes that let Quagga.init/start accept a raw ImageWrapper in a worker. if(engine==='quagga'||engine==='quagga-full'){const bytes=await(await fetch('./vendor/quagga/quagga.min.js')).arrayBuffer();let code=new TextDecoder().decode(bytes); for(const [from,to]of[['if(!ui.framegrabber)throw new Error','if(ui.onUIThread&&!ui.framegrabber)throw new Error'],['else{var n;e.context.framegrabber.attachData(null===(n=e.context.inputImageWrapper)||void 0===n?void 0:n.data),e.context.framegrabber.grab(),e.locateAndDecode()}','else{e.locateAndDecode()}']]){if(code.split(from).length!==2)throw new Error('Quagga2 bundle differs from 1.12.1; review the raw-input fixes.');code=code.replace(from,()=>to)} const module={exports:{}};new Function('module','exports','window',code)(module,module.exports,self);const Q=module.exports.default??module.exports,size=engine==='quagga'?800:null; const readers=['ean_reader','ean_8_reader','upc_reader','upc_e_reader',...(allFormats?['code_128_reader','code_39_reader','code_93_reader','codabar_reader','i2of5_reader']:[])],config={numOfWorkers:0,locate:true,locator:{halfSample:false,patchSize:'medium'},decoder:{readers,multiple:true}}; // Quagga's calculatePatchSize (barcode_locator), used by checkImageConstraints to crop the input. const divisors=n=>{const lo=[],hi=[];for(let i=1;i<=Math.sqrt(n);i++)if(n%i===0){lo.push(i);if(i!==n/i)hi.unshift(Math.floor(n/i))}return lo.concat(hi)}; const patch=(x,y)=>{const a=divisors(x),b=divisors(y),common=a.filter(v=>b.includes(v)),list=[8,10,15,20,32,60,80],idx=3,wide=Math.max(x,y),want=Math.floor(wide/list[idx]); const pick=d=>{let i=0,found=d[Math.floor(d.length/2)];while(i0)found=Math.abs(d[i]-want)>Math.abs(d[i-1]-want)?d[i-1]:d[i];return want/foundlist[idx-1]/list[idx]?found:null}; return pick(common)??pick(divisors(wide))??pick(divisors(want*list[idx]))??null}; scan=async image=>{const start=performance.now(),{width:W,height:H,data}=image,gray=new Uint8Array(W*H);for(let i=0;i1?size:Math.floor(W/H*size)):W,ch=size?(W/H>1?Math.floor(H/W*size):size):H,sx=W/cw,sy=H/ch;let canvas=gray; if(cw!==W||ch!==H){canvas=new Uint8Array(cw*ch);for(let y=0;y{const done=v=>{Q.offProcessed(done);resolve(v)};Q.onProcessed(done);try{Q.init(config,e=>{if(e){Q.offProcessed(done);reject(e instanceof Error?e:new Error(String(e)))}else Q.start()},new Q.ImageWrapper({x:w,y:h,type:'XYSize'},input))}catch(e){Q.offProcessed(done);reject(e)}}); const found=Array.isArray(result)?result:result?.barcodes??(result?[result]:[]),reads=found.filter(r=>r?.codeResult?.code).map(r=>({format:r.codeResult.format,text:r.codeResult.code,polygon:(r.box??[]).map(([x,y])=>[x*sx,y*sy])}));return{ms:performance.now()-start,reads}}; return{engine,version:'1.12.1',bundleSha256:await hash(bytes),bundlePatch:'raw ImageWrapper start in workers (same guarded substitutions as the live demo)',inputSize:size??'native',pipeline:'decodeSingle equivalent: luma, bilinear resampling, crop to locator patches',...config}} // ZXing-JS (@zxing/library, TypeScript port of Java ZXing): its ESM build uses extensionless imports, so the self-contained // UMD bundle is evaluated. Each scan mirrors BrowserMultiFormatReader.decodeFromImageElement: a full-size canvas copy read via // HTMLCanvasElementLuminanceSource (the only source with the 90° rotation TRY_HARDER uses) and HybridBinarizer, retried with // GlobalHistogramBinarizer on NotFound. An OffscreenCanvas replaces the canvas; rotation gets its temporary canvas from a stand-in // ownerDocument. One symbol per call (no multi reader). zxingjs keeps TRY_HARDER off, as html5-qrcode and most wrappers do. if(engine==='zxingjs'||engine==='zxingjs-harder'){const bytes=await(await fetch('./vendor/zxingjs/umd/index.min.js')).arrayBuffer(),exports={};new Function('exports','module',new TextDecoder().decode(bytes))(exports,{exports});const Z=exports,harder=engine==='zxingjs-harder'; const formatNames={[Z.BarcodeFormat.EAN_13]:'EAN13',[Z.BarcodeFormat.EAN_8]:'EAN8',[Z.BarcodeFormat.UPC_A]:'UPCA',[Z.BarcodeFormat.UPC_E]:'UPCE',...(allFormats?Object.fromEntries([['QR_CODE','QRCode'],['DATA_MATRIX','DataMatrix'],['PDF_417','PDF417'],['AZTEC','Aztec'],['MAXICODE','MaxiCode'],['CODE_128','Code128'],['CODE_39','Code39'],['CODE_93','Code93'],['ITF','ITF'],['CODABAR','Codabar'],['RSS_14','DataBar'],['RSS_EXPANDED','DataBarExpanded']].map(([k,v])=>[Z.BarcodeFormat[k],v])):{})},hints=new Map([[Z.DecodeHintType.POSSIBLE_FORMATS,Object.keys(formatNames).map(Number)]]);if(harder)hints.set(Z.DecodeHintType.TRY_HARDER,true);const reader=new Z.MultiFormatReader();reader.setHints(hints); const ownerDocument={createElement:()=>new OffscreenCanvas(1,1)},decode=bitmap=>{try{return reader.decode(bitmap,hints)}finally{reader.reset()}}; scan=async image=>{const start=performance.now(),canvas=new OffscreenCanvas(image.width,image.height);canvas.ownerDocument=ownerDocument;canvas.getContext('2d').putImageData(image instanceof ImageData?image:new ImageData(image.data,image.width,image.height),0,0);let r=null; try{try{r=decode(new Z.BinaryBitmap(new Z.HybridBinarizer(new Z.HTMLCanvasElementLuminanceSource(canvas,false))))}catch(e){if(!(e instanceof Z.NotFoundException))throw e;r=decode(new Z.BinaryBitmap(new Z.GlobalHistogramBinarizer(new Z.HTMLCanvasElementLuminanceSource(canvas,false))))}} catch(e){if(!(e instanceof Z.NotFoundException||e instanceof Z.ChecksumException||e instanceof Z.FormatException))throw e} const reads=r?[{format:formatNames[r.getBarcodeFormat()]??String(r.getBarcodeFormat()),text:r.getText(),polygon:r.getResultPoints().map(p=>[p.getX(),p.getY()])}]:[];return{ms:performance.now()-start,reads}}; return{engine,version:'0.23.0',bundleSha256:await hash(bytes),api:'BrowserMultiFormatReader.decode equivalent: HTMLCanvasElementLuminanceSource, HybridBinarizer then GlobalHistogramBinarizer',formats,tryHarder:harder,maxSymbols:1}} throw new Error('Unknown engine')} self.onmessage=async({data:d})=>{try{if(d.type==='init'){postMessage({type:'ready',environment:await init(d.engine)});return}if(d.type!=='case')return;const c=d.case;let image;try{image=d.pixels??await casePixels(c,d.assets)}catch(e){postMessage({type:'result',result:{id:c.id,status:'input-error',error:String(e)}});return}const rgbaSha256=await hash(image.data);if(c.referenceRgbaSha256&&c.referenceRgbaSha256!==rgbaSha256){postMessage({type:'result',result:{id:c.id,status:'pixel-mismatch',error:'Pixels differ from original baseline; not scored as a scanner failure',rgbaSha256,referenceRgbaSha256:c.referenceRgbaSha256}});return}const warmupErrors=[];if(d.warmup)for(let i=0;i<3;i++)try{await scan(image)}catch(e){warmupErrors.push(String(e))}const repeats=[];for(let i=0;i<3;i++)try{repeats.push({status:'ok',...await scan(image)})}catch(e){repeats.push({status:'error',error:String(e)})}const valid=repeats.filter(x=>x.status==='ok'),times=valid.map(x=>x.ms).sort((a,b)=>a-b),reads=valid[0]?.reads??[],expected=new Set(c.expected.map(x=>x.canonicalGtin14)),got=new Set(reads.map(x=>gtin(x.format,x.text)).filter(Boolean)),canonical=reads.map(x=>gtin(x.format,x.text)),negative=c.expected.length===0;postMessage({type:'result',result:{id:c.id,status:valid.length===3?'ok':'scan-error',width:image.width,height:image.height,rgbaSha256,repeats,warmupCalls:d.warmup?3:0,warmupErrors,medianMs:times.length===3?times[1]:null,correct:!negative&&valid.length===3&&[...expected].every(x=>got.has(x)),expectedValueCount:expected.size,matchedValueCount:[...expected].filter(x=>got.has(x)).length,negative,negativeDetection:negative&&valid.some(x=>x.reads.length>0),unexpectedReads:canonical.filter(x=>!x||!expected.has(x)).length,unstablePayloads:valid.some(x=>JSON.stringify(x.reads.map(r=>[r.format,r.text]).sort())!==JSON.stringify(reads.map(r=>[r.format,r.text]).sort())),coverageMetric:'expected distinct payloads, not physical instances'}})}catch(e){postMessage({type:'fatal',error:String(e)})}};