+ if (taskFunctions == null) {
+ throw new Error('taskFunctions parameter is mandatory')
+ }
+ this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
+ if (typeof taskFunctions === 'function') {
+ this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
+ } else if (isPlainObject(taskFunctions)) {
+ let firstEntry = true
+ for (const [name, fn] of Object.entries(taskFunctions)) {
+ if (typeof fn !== 'function') {
+ throw new TypeError(
+ 'A taskFunctions parameter object value is not a function'
+ )
+ }
+ this.taskFunctions.set(name, fn.bind(this))
+ if (firstEntry) {
+ this.taskFunctions.set(DEFAULT_FUNCTION_NAME, fn.bind(this))
+ firstEntry = false
+ }
+ }
+ if (firstEntry) {
+ throw new Error('taskFunctions parameter object is empty')
+ }
+ } else {
+ throw new TypeError(
+ 'taskFunctions parameter is not a function or a plain object'
+ )
+ }
+ }
+
+ /**
+ * Worker message listener.
+ *
+ * @param message - Message received.
+ */
+ protected messageListener (message: MessageValue<Data, Data>): void {
+ if (message.ready != null && message.workerId === this.id) {
+ // Startup message received
+ this.workerReady()
+ } else if (message.statistics != null && message.workerId === this.id) {
+ // Statistics message received
+ this.statistics = message.statistics
+ } else if (message.checkAlive != null && message.workerId === this.id) {
+ // Check alive message received
+ message.checkAlive ? this.startCheckAlive() : this.stopCheckAlive()
+ } else if (
+ message.id != null &&
+ message.data != null &&
+ message.workerId === this.id
+ ) {
+ // Task message received
+ const fn = this.getTaskFunction(message.name)
+ if (isAsyncFunction(fn)) {
+ this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)