(options)
| 24 | * @return {function(...[*]): {then}} |
| 25 | */ |
| 26 | export function defineWorkerModule(options) { |
| 27 | if ((!options || typeof options.init !== 'function') && !_allowInitAsString) { |
| 28 | throw new Error('requires `options.init` function') |
| 29 | } |
| 30 | let {dependencies, init, getTransferables, workerId} = options |
| 31 | |
| 32 | const onMainThread = defineMainThreadModule(options) |
| 33 | |
| 34 | if (workerId == null) { |
| 35 | workerId = '#default' |
| 36 | } |
| 37 | const id = `workerModule${++_workerModuleId}` |
| 38 | const name = options.name || id |
| 39 | let registrationPromise = null |
| 40 | |
| 41 | dependencies = dependencies && dependencies.map(dep => { |
| 42 | // Wrap raw functions as worker modules with no dependencies |
| 43 | if (typeof dep === 'function' && !dep.workerModuleData) { |
| 44 | _allowInitAsString = true |
| 45 | dep = defineWorkerModule({ |
| 46 | workerId, |
| 47 | name: `<${name}> function dependency: ${dep.name}`, |
| 48 | init: `function(){return (\n${stringifyFunction(dep)}\n)}` |
| 49 | }) |
| 50 | _allowInitAsString = false |
| 51 | } |
| 52 | // Grab postable data for worker modules |
| 53 | if (dep && dep.workerModuleData) { |
| 54 | dep = dep.workerModuleData |
| 55 | } |
| 56 | return dep |
| 57 | }) |
| 58 | |
| 59 | function moduleFunc(...args) { |
| 60 | if (!supportsWorkers()) { |
| 61 | return onMainThread(...args) |
| 62 | } |
| 63 | |
| 64 | // Register this module if needed |
| 65 | if (!registrationPromise) { |
| 66 | registrationPromise = callWorker(workerId,'registerModule', moduleFunc.workerModuleData) |
| 67 | const unregister = () => { |
| 68 | registrationPromise = null |
| 69 | registeredModules[workerId].delete(unregister) |
| 70 | } |
| 71 | ;(registeredModules[workerId] || (registeredModules[workerId] = new Set())).add(unregister) |
| 72 | } |
| 73 | |
| 74 | // Invoke the module, returning a promise |
| 75 | return registrationPromise.then(({isCallable}) => { |
| 76 | if (isCallable) { |
| 77 | return callWorker(workerId,'callModule', {id, args}) |
| 78 | } else { |
| 79 | throw new Error('Worker module function was called but `init` did not return a callable function') |
| 80 | } |
| 81 | }) |
| 82 | } |
| 83 | moduleFunc.workerModuleData = { |
no test coverage detected