Skip to content

Commit

Permalink
util: allow safely adding listener to abortSignal
Browse files Browse the repository at this point in the history
  • Loading branch information
atlowChemi committed Jun 29, 2023
1 parent e8810b9 commit 416dafb
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const {
ObjectValues,
ReflectApply,
StringPrototypePadStart,
SymbolDispose,
} = primordials;

const {
Expand All @@ -63,6 +64,7 @@ const {
} = require('internal/util/inspect');
const { debuglog } = require('internal/util/debuglog');
const {
validateAbortSignal,
validateFunction,
validateNumber,
} = require('internal/validators');
Expand All @@ -73,6 +75,7 @@ const {
deprecate,
getSystemErrorMap,
getSystemErrorName: internalErrorName,
kEmptyObject,
promisify,
toUSVString,
defineLazyProperties,
Expand All @@ -86,6 +89,7 @@ function lazyAbortController() {
}

let internalDeepEqual;
let kResistStopPropagation;

/**
* @deprecated since v4.0.0
Expand Down Expand Up @@ -345,11 +349,31 @@ function getSystemErrorName(err) {
return internalErrorName(err);
}

function addSafeAbortSignalAbortListener(signal, listener, options = kEmptyObject) {
if (signal === undefined) {
throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)
}
validateAbortSignal(signal, 'signal');
kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation;
signal.addEventListener('abort', listener, { ...options, [kResistStopPropagation]: true });
const removeEventListener = () => {
signal.removeEventListener('abort', listener, options);
};
return {
__proto__: null,
removeEventListener,
[SymbolDispose]() {
removeEventListener();
},
};
}

// Keep the `exports =` so that various functions can still be monkeypatched
module.exports = {
_errnoException: errnoException,
_exceptionWithHostPort: exceptionWithHostPort,
_extend,
addSafeAbortSignalAbortListener,
callbackify,
debug: debuglog,
debuglog,
Expand Down

0 comments on commit 416dafb

Please sign in to comment.