event-pubsub
Small, synchronous, extensible publish/subscribe events for Node.js plus bundled and unbundled browsers.
It works with bundlers and without a bundler. Both paths execute the same native ESM source; direct browser use needs only a standard import map, not a build or transpilation step.
Release status:
6.1.1is the current npm and GitHub release.

npm install event-pubsub
import EventPubSub from 'event-pubsub';
const events = new EventPubSub();
events.on('ready', (payload) => {
console.log(payload);
});
events.emit('ready', {fast: true});
That bare import is also the bundler entry. In a native browser application with no bundler, keep the same import and add the complete import map shown below.
The same source is available directly to CommonJS on Node.js 22.12 or newer:
const EventPubSub = require('event-pubsub');
Measured dispatch speed
Bars show median nanoseconds per emit, whiskers show p25–p75, and dots show all seven samples. Every rate is derived from the same execution-only measurement; setup, warmup, validation, verification, serialization, file I/O, and CI orchestration are excluded. Lower latency is better. Open the interactive charts or raw schema v2 evidence.
Why this module
- Five fluent methods:
on,once,off,emit, andreset. - Synchronous, registration-order dispatch with wildcard subscribers first.
- One-shot subscribers are removed before invocation, including reentrant emits.
- Subscriber arrays remain live during an emit: additions can run in that emit, and specifically removed handlers are skipped before their turn. Removing a whole bucket or resetting the registry detaches it from future lookup while an already-active array finishes.
- Safe event names, including
__proto__,constructor, andtoString. - Isolated
listsnapshots that cannot mutate the live registry. - One native ESM source for Node.js
import/require(), bundled browser applications, and unbundled browser modules, without transpilation or a duplicate build. - One explicit production validator:
strong-type2.0.0, resolved through the package dependency boundary with an explicit browser entry and import map.
API
| Member | Signature | Behavior |
|---|---|---|
on |
on(type, handler, once = false) |
Register a persistent or explicitly one-shot handler. |
once |
once(type, handler) |
Register a handler removed immediately before its first call. |
off |
off(type = '*', handler = '*') |
Remove every matching handler or a whole event type. |
emit |
emit(type, ...payload) |
Run wildcard handlers, then typed handlers, synchronously. |
reset |
reset() |
Clear the complete registry. |
list |
get list() |
Return an isolated null-prototype object snapshot of handler arrays. |
All public mutators return the current instance. Event types must be strings, and on/once validate their handler immediately. For 5.x compatibility, off returns early for a missing type before validating its optional handler. Synchronous handler throws propagate to the publisher; return values and promises are ignored, so applications must handle asynchronous rejections themselves.
Wildcard events
* subscribers run before typed subscribers and receive the emitted type as their first argument.
events.on('*', (type, ...payload) => {
console.log(type, payload);
});
events.emit('invoice.paid', {id: 42});
The wildcard list entry is exposed at Symbol.for('event-pubsub-all').
Only the exact public string * maps to the internal wildcard Symbol. The ordinary string Symbol(event-pubsub-all) remains an exact typed event name and never aliases wildcard removal.
Browser use: bundled and unbundled
The 6.1.1 package imports strong-type by package name. Bundlers may use its explicit browser entry; native browsers do not read npm package metadata, so the import map selects index.js directly.
- With a standards-compatible bundler, both package names resolve normally. The release gate bundles and executes a packed conflicting-dependency consumer with Rollup 4.62.5 and node-resolve 16.0.3, configured only for JavaScript.
- Without a bundler, a modern browser runs the same files directly through native ESM. Put this import map before the first module script that starts the graph and serve the directory over HTTP(S):
<script type="importmap">
{
"imports": {
"event-pubsub": "./node_modules/event-pubsub/index.js",
"strong-type": "./node_modules/strong-type/index.js"
}
}
</script>
<script type="module">
import EventPubSub from 'event-pubsub';
</script>
That example is non-bundled browser code: the browser fetches both files from the mapped URLs and executes them directly. The paths are relative to the HTML document, so the static server must expose the shown node_modules files. Open the application through HTTP(S), not file://.
If the application uses a strict Content Security Policy, configure it to authorize the inline import-map and module scripts—for example, with an allowed nonce or hash.
If the application intentionally installs an incompatible strong-type at its root, npm keeps event-pubsub's exact 2.0.0 dependency nested. Scope the validator mapping to the event-pubsub referrer so the browser preserves that same dependency boundary:
<script type="importmap">
{
"imports": {
"event-pubsub": "./node_modules/event-pubsub/index.js",
"strong-type": "./node_modules/strong-type/index.js"
},
"scopes": {
"./node_modules/event-pubsub/": {
"strong-type": "./node_modules/event-pubsub/node_modules/strong-type/index.js"
}
}
}
</script>
Adjust the URLs to the package layout exposed by your static server. The release gate installs the packed tarball twice and executes both maps in real Chrome; the conflict fixture poisons the root validator so the scoped nested mapping cannot pass accidentally.
Complete verification summary
The shared host-neutral registry contains 131 unique checks. vanilla-test 2.1.1 executes the same inventory in Node and real Google Chrome.
| Suite | Cases | Focus |
|---|---|---|
| Unit | 16 | Exports, state, fluent identity, validation, and list shape |
| Functional | 26 | Registration, dispatch, wildcard, once, removal, reset, and chaining |
| Integration | 14 | Subclassing, routing, isolation, namespaces, lifecycle, and errors |
| Behavioral | 12 | Given/When/Then workflows, lifecycle boundaries, routing, failures, async effects, and live membership |
| Regression | 43 | Mutation, reentrancy, snapshots, safe names, throws, and registration-local once state |
| Interface | 20 | Playground parsing, safe display, bounded state, benchmark evidence, units, and chart scaling |
| Total | 131 | One registry used by direct tests and both coverage runtimes |
Runtime and CI matrix
| Verification | Runtime | Hosts | Result requirement |
|---|---|---|---|
| Direct shared suite | Node 22.12.0 and Node 24 | Ubuntu, macOS, Windows | 131/131 on every matrix job |
| Node coverage | Node 24.18.0 | Ubuntu | 131/131 and every native V8 gate at 100% |
| Browser coverage | Google Chrome Stable | Ubuntu | 131/131 and every native V8 gate at 100% |
| Packed consumer | Node 24 | Ubuntu | Exact tarball contents plus ESM/CommonJS execution of nested strong-type 2.0.0 under a poisoned root conflict |
| Packed unbundled browser | Chrome Stable | Ubuntu and local release host | Normal and scoped-conflict import maps execute the tarball directly over HTTP |
| Packed bundled browser | Rollup 4.62.5 + Chrome Stable | Ubuntu and local release host | A bundle resolves nested strong-type 2.0.0 and runs representative behavior under a poisoned root conflict |
| Shared-source package smoke | Node 22.12.0 | Ubuntu | The same packed index.js through ESM import and direct CommonJS require() |
| Execution benchmark | Node 24.18.0 | Ubuntu | Eight validated scenarios with execution-only timing boundaries |
| GitHub Pages | Node 24 | Ubuntu | 22 pages, both runtime reports, badges, benchmark JSON, scripts, links, and licenses |
Coverage gates
| Runtime | Executable ranges | Block ranges | Function ranges | Executable lines |
|---|---|---|---|---|
| Node 24.18.0 | 100% | 100% | 100% | 100% |
| Chrome Stable | 100% | 100% | 100% | 100% |
These are native V8 executable/block/function range and executable-line totals for index.js, not parser-derived Istanbul statement or branch counts. Node and Chrome produce independent HTML, JSON, LCOV, and normalized test-result artifacts.
Commands
| Command | Purpose |
|---|---|
npm test |
Stage event-pubsub with its nested exact validator and run all 131 checks in Node. |
npm run test:unit |
Run the 16 Unit cases. |
npm run test:functional |
Run the 26 Functional cases. |
npm run test:integration |
Run the 14 Integration cases. |
npm run test:behavioral |
Run the 12 Behavioral scenarios. |
npm run test:regression |
Run the 43 Regression cases. |
npm run test:interface |
Run the 20 Interface cases. |
npm run coverage |
Run all 131 checks independently in Node and real Chrome with 100% gates. |
npm run coverage:node |
Generate only the Node native V8 report. |
npm run coverage:chrome |
Generate only the real-Chrome native V8 report. |
npm run benchmark |
Record seven fixed-count latency samples for eight scenarios. |
npm run benchmark:smoke |
Validate the benchmark quickly without replacing published results. |
npm run test:package |
Pack, inspect, install, and exercise a clean consumer. |
npm run test:browser-consumer |
Pack and execute normal-map, scoped-conflict-map, and Rollup browser consumers in real Chrome. |
npm run site:check |
Validate all focused pages, exact test inventories, scripts, links, forms, and assets. |
npm run verify |
Run the complete local release gate. |
Published evidence
- Testing strategy and suite totals
- Live execution of all 131 checks
- Node test-result JSON
- Chrome test-result JSON
- Node HTML coverage
- Chrome HTML coverage
- Chrome coverage screenshot
- Execution-latency charts
- Raw benchmark schema v2 JSON
Complete test inventory
Every test name below is sourced from the shared registry. The focused Pages site presents the same inventory one suite per page.
Unit — 16 cases
- default and named exports reference the same class
- a fresh instance exposes an empty list snapshot
- instances own independent event registries
- on returns the current instance
- once returns the current instance
- off returns the current instance when the type is absent
- emit returns the current instance when the type is absent
- reset returns the current instance
- on requires a string event type
- on requires a function handler
- on requires a boolean once flag
- once delegates type validation to on
- once delegates handler validation to on
- off requires a string event type
- off validates a handler when the event exists
- emit requires a string event type
Functional — 26 cases
- on exposes the registered handler in list
- on preserves registration order in list
- duplicate registrations remain visible as separate entries
- emit runs a registered handler synchronously
- emit runs handlers in registration order
- emit forwards every payload argument by identity
- handlers run without an emitter-bound this value
- once runs a handler exactly once
- on with an explicit false once flag remains persistent
- on with an explicit true once flag matches once
- wildcard handlers receive the emitted type before payloads
- wildcard handlers run before typed handlers
- multiple wildcard handlers retain registration order
- once supports wildcard subscriptions
- wildcard handlers are exposed under the stable symbol
- off removes a matching handler
- off removes every duplicate registration of a handler
- off leaves nonmatching handlers registered
- off with a wildcard handler removes an event type
- off defaults the handler argument to wildcard removal
- off defaults the event type to wildcard subscriptions only
- off removes one wildcard handler without touching typed handlers
- reset removes typed and wildcard registrations
- emitting an unknown type does not run other typed handlers
- all public mutators support fluent chaining
- the same function can be once and persistent independently
Integration — 14 cases
- a subclass can publish state changes
- multiple instances isolate same-named topics
- namespaced topic strings remain exact
- a wildcard audit stream observes several domains
- a one-shot readiness gate coexists with persistent progress
- a request-style payload preserves callbacks by identity
- a handler can publish a second event synchronously
- a wildcard handler can route selected events
- reset provides a clean lifecycle boundary
- empty and whitespace topic names remain distinct
- unicode topic names and payloads pass through unchanged
- async handlers are invoked without delaying synchronous peers
- synchronous handler exceptions propagate to the publisher
- list supports operational introspection without exposing records
Behavioral — 12 scenarios
- given an audited order retry with one-time reservation and persistent projection, when the same order is published twice, then the audit leads both deliveries while reservation happens once
- given an order handler that publishes the next workflow stage, when an order is created, then the nested fulfillment stage completes before outer delivery continues
- given a one-time readiness gate that reenters its own topic, when the outer readiness signal arrives, then the gate is consumed before the nested signal
- given a mounted subscriber that observes application updates, when the subscriber unmounts, then later updates no longer reach it
- given listeners from an authenticated session, when logout resets the event hub and a new session starts, then only the new session observes later activity
- given a bridge that forwards only public topics to another hub, when private and public messages are published, then only public messages cross the boundary
- given a request carrying a reply callback, when a subscriber handles the request, then the caller receives the reply before publish returns
- given a wildcard normalizer and a typed consumer sharing a payload, when the payload is published, then the consumer and caller observe the normalized object
- given a one-time preflight followed by a failing persistent subscriber, when delivery is retried after the failure, then preflight stays consumed and the exact failure keeps reaching the publisher
- given an asynchronous side effect beside a synchronous projection, when the event is published, then publish returns after starting both without awaiting the side effect
- given subscriber membership that changes during a notification, when the current delivery adds one subscriber and removes another, then the added subscriber joins immediately and the removed one is skipped
- given two tenant hubs with the same topic names, when each tenant publishes an update, then each update stays within its originating tenant
Regression — 43 cases
__proto__is a safe event nameconstructoris a safe event nametoStringis a safe event namehasOwnPropertyis a safe event name- numeric-looking event names remain strings
- the wildcard symbol description remains an exact typed event
- off compares the remove-all handler sentinel strictly
- emitting the literal wildcard type invokes wildcard handlers once
- handlers added during typed dispatch run in that emit
- typed handlers added by a wildcard run in that emit
- wildcard handlers added during wildcard dispatch run in that emit
- handlers removed during dispatch do not run later in that dispatch
- a wildcard can remove a typed handler before the typed phase
- reset during typed dispatch leaves the active array running
- reset from a wildcard finishes that array but prevents typed dispatch
- once is removed before a reentrant emit
- persistent reentrant emits preserve nested registration order
- wildcard once is removed before a reentrant emit
- a throwing once handler remains removed
- a throwing once handler is absent from the next list snapshot
- a throwing persistent handler remains registered
- a thrown wildcard handler stops typed dispatch
- off with a nonmatching function preserves the type
- off ignores an invalid handler when the type is absent
- mutating a list array does not change the registry
- deleting a list property does not change the registry
- mutating a wildcard list snapshot does not change the registry
- frozen handler functions can be registered
- nonextensible handler functions can be registered
- duplicate once registrations each run once
- the same handler can be wildcard-once and typed-persistent
- registration does not write the old once symbol onto handlers
- the same handler can be once and persistent in one bucket
- the same handler has independent state across instances
- typed once removal does not skip the next registration
- wildcard once removal does not skip the next registration
- a sole once handler can add a handler to its live bucket
- off all during dispatch leaves the active array running
- stale once cleanup cannot delete a fresh same-name bucket
- an earlier once remains consumed when a later handler throws
- persistent self-removal preserves shifted-array iteration
- wildcard-only emits remain chainable
- reset instances accept new registrations immediately
Interface — 20 cases
- the playground parses no-argument mode
- the playground preserves one exact text argument
- the playground parses an empty JSON argument array
- the playground spreads several JSON arguments
- invalid playground JSON is an explicit syntax error
- a non-array JSON argument source is rejected
- typed playground subscriptions preserve whitespace
- wildcard playground subscriptions resolve to star
- typed star subscriptions require wildcard mode
- event-type display quotes invisible characters
- safe value formatting exposes undefined
- safe value formatting marks circular references
- safe value formatting bounds long output
- bounded timeline retention keeps chronological tail entries
- benchmark evidence accepts all eight unique scenarios
- benchmark evidence rejects the wrong schema version
- benchmark evidence rejects duplicate or internally inconsistent scenarios
- benchmark dispatch selection returns four scenarios
- benchmark durations choose readable nanosecond and microsecond units
- benchmark chart values clamp and expose equivalent throughput
Benchmark interpretation
The benchmark reports median execution latency—nanoseconds per named operation—with p25, p75, min, max, and every raw sample. Fixed-count loops use exactly two process.hrtime.bigint() readings around the execution boundary. Dispatch scenarios use distinct minimal observable subscribers, then verify their accumulated effects after timing so empty callbacks cannot become an optimizer-only lower bound. Setup, validation, calibration, warmup, post-run checks, summary work, JSON serialization, file I/O, Node startup, and CI orchestration are excluded. The charts never present total benchmark or workflow duration as module execution time.
Documentation
- Overview
- Guide
- API
- Examples
- Event console playground
- Mutation playground scenarios
- All 131 tests
- Node and Chrome coverage
- Benchmark overview
- Dispatch latency chart
- Lifecycle latency charts
- Benchmark methodology
- 5.x → 6.x migration
- Security policy
- Changelog
Runtime support
- Node.js 22.12.0 or newer for production, development, and direct CommonJS
require()of the native ESM source. - Bundled browser applications; the bundler resolves
event-pubsubandstrong-typefrom package metadata normally. - Unbundled modern browsers with native modules, private class fields,
Symbol, and import maps; no build step is required. Map both package names, with a scoped validator mapping when npm nests it.
License
MIT. See licence.