Skip to content

Conversation

williamkapke
Copy link
Contributor

@williamkapke williamkapke commented Sep 3, 2025

Fix call to Array.prototype.slice with context

Description

This PR fixes a critical bug in the EventEmitter polyfill where Array.prototype.slice is called without proper context, causing a runtime error when an EventEmitter has more than 6 listeners.

The Bug

The current implementation has a typo in the array cloning function:

// Current (broken):
return Array.prototype.slice(arr)  

// Should be:
return Array.prototype.slice.call(arr)

This causes TypeError: Cannot read properties of undefined (reading 'apply') when emitting events with >6 listeners.

How to Reproduce

<!DOCTYPE html>
<html>
<body>
  <script type="module">
    import { EventEmitter } from "https://esm.sh/node/events.mjs";
    
    const emitter = new EventEmitter();
    
    // Add 7 listeners (breaks with >6)
    for (let i = 0; i < 7; i++) {
      emitter.on("test", () => console.log(`Listener ${i}`));
    }
    
    // Throws: TypeError: Cannot read properties of undefined (reading 'apply')
    emitter.emit("test");
  </script>
</body>
</html>

This is returning an empty array when listeners are > 6
@williamkapke williamkapke requested a review from pi0 as a code owner September 3, 2025 04:28
williamkapke added a commit to elevationai/cuss2-ts that referenced this pull request Sep 3, 2025
- Added vendor/node-events-fixed.ts with arrayClone bug fix
- The bug: Array.prototype.slice(arr) should be Array.prototype.slice.call(arr)
- This causes "Cannot read properties of undefined (reading 'apply')" with >6 listeners
- Updated import map to use local fixed version instead of node:events
- Added return types to satisfy deno lint no-slow-types rule
- This is temporary until unjs/unenv#518 is merged and deployed
Copy link
Member

@pi0 pi0 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@pi0 pi0 changed the title Fix call to Array.prototype.slice with context fix(node:events): call to Array.prototype.slice with context Sep 4, 2025
@pi0 pi0 merged commit 4215704 into unjs:main Sep 4, 2025
2 checks passed
@pi0
Copy link
Member

pi0 commented Sep 4, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants