Skip to content

Commit

Permalink
fix(worker): do not swallow errors when sending custom messages (#10984)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Dec 28, 2020
1 parent 0ab070c commit 0c75d62
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -48,6 +48,7 @@
- `[jest-transform]` [**BREAKING**] Refactor API to pass an options bag around rather than multiple boolean options ([#10753](https://github.com/facebook/jest/pull/10753))
- `[jest-transform]` [**BREAKING**] Refactor API of transformers to pass an options bag rather than separate `config` and other options ([#10834](https://github.com/facebook/jest/pull/10834))
- `[jest-worker]` [**BREAKING**] Use named exports ([#10623] (https://github.com/facebook/jest/pull/10623))
- `[jest-worker]` Do not swallow errors during serialization ([#10984] (https://github.com/facebook/jest/pull/10984))
- `[pretty-format]` [**BREAKING**] Convert to ES Modules ([#10515](https://github.com/facebook/jest/pull/10515))

### Chore & Maintenance
Expand Down
40 changes: 21 additions & 19 deletions packages/jest-worker/src/workers/messageParent.ts
Expand Up @@ -7,31 +7,33 @@

import {PARENT_MESSAGE_CUSTOM} from '../types';

const isWorkerThread = () => {
const isWorkerThread: boolean = (() => {
try {
// `Require` here to support Node v10
const {isMainThread, parentPort} = require('worker_threads');
return !isMainThread && parentPort;
const {
isMainThread,
parentPort,
} = require('worker_threads') as typeof import('worker_threads');
return !isMainThread && parentPort != null;
} catch {
return false;
}
};
})();

const messageParent = (
export default function messageParent(
message: unknown,
parentProcess: NodeJS.Process = process,
): void => {
try {
if (isWorkerThread()) {
// `Require` here to support Node v10
const {parentPort} = require('worker_threads');
parentPort.postMessage([PARENT_MESSAGE_CUSTOM, message]);
} else if (typeof parentProcess.send === 'function') {
parentProcess.send([PARENT_MESSAGE_CUSTOM, message]);
}
} catch {
parentProcess = process,
): void {
if (isWorkerThread) {
// `Require` here to support Node v10
const {
parentPort,
} = require('worker_threads') as typeof import('worker_threads');
// ! is safe due to `null` check in `isWorkerThread`
parentPort!.postMessage([PARENT_MESSAGE_CUSTOM, message]);
} else if (typeof parentProcess.send === 'function') {
parentProcess.send([PARENT_MESSAGE_CUSTOM, message]);
} else {
throw new Error('"messageParent" can only be used inside a worker');
}
};

export default messageParent;
}

0 comments on commit 0c75d62

Please sign in to comment.