license import { Marker } from '../../defs/marker.js' ; import { isImageData } from '../utils/is-image-data.js' ; export class BarcodeDetectorPolyfill { static loadedFrom : URL ; private readonly canvas = document . createElement ( 'canvas' ) ; private readonly ctx = this . canvas . getContext ( '2d' ) ! ; private hasLoaded : boolean ; private worker : Worker ; private isReadyInternal : Promise < boolean > ; get isReady ( ) { return this . isReadyInternal ; } constructor ( path = 'barcode-detector_worker.js' ) { this . hasLoaded = false ; let prefix = '/' ; if ( typeof BarcodeDetectorPolyfill . loadedFrom !== 'undefined' ) { const prefixUrl = new URL ( path , BarcodeDetectorPolyfill . loadedFrom ) ; path = prefixUrl . href ; prefix = prefixUrl . href . replace ( /lib.*/ , '' ) ; } this . worker = new Worker ( path ) ; this . worker . postMessage ( prefix ) ; ( window as any ) . barcodeDetectorWorker = this . worker ; this . isReadyInternal = new Promise ( ( resolve , reject ) => { this . worker . onmessage = ( e ) => { if ( e . data === 'ready' ) { this . hasLoaded = true ; resolve ( this . hasLoaded ) ; } else { reject ( new Error ( 'Unexpected worker response' ) ) ; } } ; } ) ; window . addEventListener ( 'unload' , ( ) => { this . worker . terminate ( ) ; } ) ; } async detect ( pixels ) { if ( ! this . hasLoaded ) { return null ; } return new Promise ( async ( resolve ) => { let imageData ; if ( isImageData ( pixels ) ) { imageData = pixels ; } else { let width = pixels . width ; let height = pixels . height ; if ( 'naturalWidth' in pixels && pixels . naturalWidth ) { width = pixels . naturalWidth ; } if ( 'naturalHeight' in pixels && pixels . naturalHeight ) { height = pixels . naturalHeight ; } this . canvas . width = width ; this . canvas . height = height ; this . ctx . drawImage ( pixels , 0 , 0 ) ; imageData = this . ctx . getImageData ( 0 , 0 , this . canvas . width , this . canvas . height ) ; } this . worker . onmessage = ( evt ) => { resolve ( evt . data ) ; } ; this . worker . postMessage ( imageData ) ; } ) ; } } if ( ! ( 'BarcodeDetector' in self ) ) { const script = document . currentScript as HTMLScriptElement ; ( window as any ) . BarcodeDetector = BarcodeDetectorPolyfill ; BarcodeDetectorPolyfill . loadedFrom = new URL ( script . src , window . location . toString ( ) ) ; }