From d9f2b58629dbdf726d485018f2eacefc880aea40 Mon Sep 17 00:00:00 2001 From: atlowChemi Date: Thu, 29 Jun 2023 13:19:24 +0300 Subject: [PATCH] util: allow safely adding listener to abortSignal --- lib/util.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/util.js b/lib/util.js index 7fb7994e6536ba..d891fad9742581 100644 --- a/lib/util.js +++ b/lib/util.js @@ -43,6 +43,7 @@ const { ObjectValues, ReflectApply, StringPrototypePadStart, + SymbolDispose, } = primordials; const { @@ -63,6 +64,7 @@ const { } = require('internal/util/inspect'); const { debuglog } = require('internal/util/debuglog'); const { + validateAbortSignal, validateFunction, validateNumber, } = require('internal/validators'); @@ -73,6 +75,7 @@ const { deprecate, getSystemErrorMap, getSystemErrorName: internalErrorName, + kEmptyObject, promisify, toUSVString, defineLazyProperties, @@ -86,6 +89,7 @@ function lazyAbortController() { } let internalDeepEqual; +let kResistStopPropagation; /** * @deprecated since v4.0.0 @@ -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, { __proto__: null, ...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,