Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/js/node/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,12 @@ function onAbortedCallback(promise: Promise<void>) {
$resolvePromiseWithFirstResolvingFunctionCallCheck(promise, undefined);
}

// Its own function so the listener's scope holds `promise` and not aborted()'s `resource`. Not
// onAbortedCallback.bind(): that looks up `bind` on Function.prototype, which user code can replace.
function createAbortedListener(promise: Promise<void>) {
return () => onAbortedCallback(promise);
}

function aborted(signal: AbortSignal, resource: object) {
if (!$isObject(signal) || !(signal instanceof AbortSignal)) {
throw $ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal);
Expand All @@ -642,14 +648,8 @@ function aborted(signal: AbortSignal, resource: object) {
}

const promise = $newPromise();
const listener = onAbortedCallback.bind(undefined, promise);
signal.addEventListener(
"abort",
// Do not leak the current scope into the listener.
// Instead, create a new function.
listener,
resistStopPropagation({ __proto__: null, once: true }),
);
const listener = createAbortedListener(promise);
signal.addEventListener("abort", listener, resistStopPropagation({ __proto__: null, once: true }));

if (!lazyAbortedRegistry) {
lazyAbortedRegistry = new FinalizationRegistry(({ ref, listener }) => {
Expand Down
15 changes: 15 additions & 0 deletions test/js/node/util/test-aborted.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,18 @@ test("aborted resolves every waiter on the same signal with undefined", async ()
expect(await Promise.all([first, second])).toEqual([undefined, undefined]);
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0);
});

test("aborted does not hand its internal settle function to a patched Function.prototype.bind", () => {
const originalBind = Function.prototype.bind;
const receivers: Function[] = [];
Function.prototype.bind = function (this: Function, ...args: any[]) {
receivers.push(this);
return originalBind.apply(this, args as [any, ...any[]]);
};
try {
aborted(new AbortController().signal, {});
} finally {
Function.prototype.bind = originalBind;
}
expect(receivers).toEqual([]);
});