All files / src/lib engineLoader.ts

100% Statements 30/30
100% Branches 17/17
100% Functions 6/6
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 6715x 15x 15x   15x         59x 41x 41x   59x     295x 169x               169x       42x 42x                     15x 90x 60x   60x   30x       15x 52x 2x   52x 47x 47x     47x   5x     15x  
import { deviceId, scanditEngineLocation, userLicenseKey } from "../index";
import { BrowserHelper } from "./browserHelper";
import { EngineWorker, engineWorkerBlob } from "./workers/engineWorker";
 
export class EngineLoader {
  private preloadedEngineWorker?: EngineWorker;
  private preloadedEngineWorkerAvailable: boolean;
 
  constructor(preload: boolean) {
    if (preload) {
      this.preloadedEngineWorker = new Worker(URL.createObjectURL(engineWorkerBlob));
      EngineLoader.load(this.preloadedEngineWorker);
    }
    this.preloadedEngineWorkerAvailable = preload;
  }
 
  public static load(engineWorker: EngineWorker, preload: boolean = false, delayedRegistration: boolean = false): void {
    engineWorker.postMessage({
      type: "load-library",
      deviceId,
      libraryLocation: scanditEngineLocation,
      path: self.location.pathname,
      preload,
      deviceModelName: BrowserHelper.userAgentInfo.getDevice().model,
    });
    engineWorker.addEventListener(
      "message",
      (event) => {
        // istanbul ignore else
        if (event.data[0] === "status" && event.data[1] === "ready") {
          engineWorker.postMessage({
            type: "create-context",
            licenseKey: userLicenseKey,
            delayedRegistration,
          });
        }
      },
      { once: true }
    );
  }
 
  public getEngineWorker(): EngineWorker {
    if (this.preloadedEngineWorkerAvailable && this.preloadedEngineWorker != null) {
      this.preloadedEngineWorkerAvailable = false;
 
      return this.preloadedEngineWorker;
    } else {
      return new Worker(URL.createObjectURL(engineWorkerBlob));
    }
  }
 
  public returnEngineWorker(engineWorker: EngineWorker): void {
    if (this.preloadedEngineWorker == null) {
      this.preloadedEngineWorker = engineWorker;
    }
    if (this.preloadedEngineWorker === engineWorker) {
      this.preloadedEngineWorker.onmessage = null;
      this.preloadedEngineWorker.postMessage({
        type: "reset",
      });
      this.preloadedEngineWorkerAvailable = true;
    } else {
      engineWorker.terminate();
    }
  }
}