get-one.js
This file
Path
lib/ipc/get-one.js
98 lines · 2.6 KiB · JavaScript
Last changed by
Fix IPC edge casesSindre Sorhusbefore adoption5f80cde
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import {once, on} from 'node:events';import {copyOptions} from '../utils/options.js';import { validateIpcMethod, throwOnEarlyDisconnect, disconnect, getStrictResponseError,} from './validation.js';import {getIpcEmitter, isConnected} from './forward.js';import {addReference, removeReference} from './reference.js';
export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');
// Like `[sub]process.once('message')` but promise-basedexport const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, rawOptions) => { const options = copyOptions(rawOptions); const {reference = true, filter} = options; const {signal} = options[internalGetOneMessageOptions] ?? {};
validateIpcMethod({ methodName: 'getOneMessage', isSubprocess, ipc, isConnected: isConnected(anyProcess), });
return getOneMessageAsync({ anyProcess, channel, isSubprocess, filter, reference, signal, });};
const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference, signal}) => { addReference(channel, reference); const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); const controller = new AbortController(); stopOnAbort(signal, controller);
try { return await Promise.race([ getMessage(ipcEmitter, filter, controller), throwOnDisconnect(ipcEmitter, isSubprocess, controller), throwOnStrictError(ipcEmitter, isSubprocess, controller), ]); } catch (error) { // When the internal `signal` stops the read, e.g. when a `.pipe()` is canceled, the subprocess keeps running and can still use IPC if (!signal?.aborted) { disconnect(anyProcess); }
throw error; } finally { controller.abort(); removeReference(channel, reference); }};
const stopOnAbort = (signal, controller) => { if (signal === undefined) { return; }
if (signal.aborted) { controller.abort(); return; }
signal.addEventListener('abort', () => { controller.abort(); }, {once: true, signal: controller.signal});};
const getMessage = async (ipcEmitter, filter, {signal}) => { if (filter === undefined) { const [message] = await once(ipcEmitter, 'message', {signal}); return message; }
for await (const [message] of on(ipcEmitter, 'message', {signal})) { if (filter(message)) { return message; } }};
const throwOnDisconnect = async (ipcEmitter, isSubprocess, {signal}) => { await once(ipcEmitter, 'disconnect', {signal}); throwOnEarlyDisconnect(isSubprocess);};
const throwOnStrictError = async (ipcEmitter, isSubprocess, {signal}) => { const [error] = await once(ipcEmitter, 'strict:error', {signal}); throw getStrictResponseError(error, isSubprocess);};