|
7 | 7 |
|
8 | 8 | import {PARENT_MESSAGE_CUSTOM} from '../types'; |
9 | 9 |
|
10 | | -const isWorkerThread = () => { |
| 10 | +const isWorkerThread: boolean = (() => { |
11 | 11 | try { |
12 | 12 | // `Require` here to support Node v10 |
13 | | - const {isMainThread, parentPort} = require('worker_threads'); |
14 | | - return !isMainThread && parentPort; |
| 13 | + const { |
| 14 | + isMainThread, |
| 15 | + parentPort, |
| 16 | + } = require('worker_threads') as typeof import('worker_threads'); |
| 17 | + return !isMainThread && parentPort != null; |
15 | 18 | } catch { |
16 | 19 | return false; |
17 | 20 | } |
18 | | -}; |
| 21 | +})(); |
19 | 22 |
|
20 | | -const messageParent = ( |
| 23 | +export default function messageParent( |
21 | 24 | message: unknown, |
22 | | - parentProcess: NodeJS.Process = process, |
23 | | -): void => { |
24 | | - try { |
25 | | - if (isWorkerThread()) { |
26 | | - // `Require` here to support Node v10 |
27 | | - const {parentPort} = require('worker_threads'); |
28 | | - parentPort.postMessage([PARENT_MESSAGE_CUSTOM, message]); |
29 | | - } else if (typeof parentProcess.send === 'function') { |
30 | | - parentProcess.send([PARENT_MESSAGE_CUSTOM, message]); |
31 | | - } |
32 | | - } catch { |
| 25 | + parentProcess = process, |
| 26 | +): void { |
| 27 | + if (isWorkerThread) { |
| 28 | + // `Require` here to support Node v10 |
| 29 | + const { |
| 30 | + parentPort, |
| 31 | + } = require('worker_threads') as typeof import('worker_threads'); |
| 32 | + // ! is safe due to `null` check in `isWorkerThread` |
| 33 | + parentPort!.postMessage([PARENT_MESSAGE_CUSTOM, message]); |
| 34 | + } else if (typeof parentProcess.send === 'function') { |
| 35 | + parentProcess.send([PARENT_MESSAGE_CUSTOM, message]); |
| 36 | + } else { |
33 | 37 | throw new Error('"messageParent" can only be used inside a worker'); |
34 | 38 | } |
35 | | -}; |
36 | | - |
37 | | -export default messageParent; |
| 39 | +} |
0 commit comments