OverviewFilesCommitsIssuesDocsReleasesPeers

mirall-cli / node_modules / bare-worker / lib / worker-thread.js

54 lines · javascript ref:
const Module = require('bare-module')
const WorkerState = require('./worker-state')

const state = new WorkerState()

Bare.argv.splice(1, Bare.argv.length, state.entry, ...state.argv.map((arg) => String(arg)))

// Expose the other end of the parent port's IPC stream as the conventional
// `Bare.IPC` binary duplex stream.
Bare.IPC = state.port.IPC

Bare.on('newListener', onnewlistener)
  .on('removeListener', onremovelistener)
  .on('uncaughtException', onerror)
  .on('unhandledRejection', onerror)

const cache = Object.create(null)

for (const [, source] of state.preloads) {
  Module.load(
    new URL(`bare:/worker/preload-${Math.random().toString(16).slice(2)}.bundle`),
    source,
    { cache }
  )
}

Module.load(new URL('bare:/worker.bundle'), state.source, { cache })

function onnewlistener(name, fn) {
  if (fn === onremovelistener || fn === onerror) return

  switch (name) {
    case 'uncaughtException':
    case 'unhandledRejection':
      Bare.off(name, onerror)
  }
}

function onremovelistener(name, fn) {
  if (fn === onremovelistener || fn === onerror) return

  switch (name) {
    case 'uncaughtException':
    case 'unhandledRejection':
      if (Bare.listenerCount(name) === 0) Bare.on(name, onerror)
  }
}

async function onerror(error) {
  await state.port._error(error)

  Bare.exitCode = 1
}