Skip to content

A standalone implementation of the DOM Events APIs, extracted from the Node.js codebase, for usage in WinterCG runtimes.

License

MIT and 2 other licenses found

Licenses found

MIT
LICENCE
MIT
LICENCE-abort-controller
Unknown
LICENCE-nodejs
Notifications You must be signed in to change notification settings

shirakaba/dom-events-wintercg

Repository files navigation

DOM Events implementation for WinterCG

npm status

A polyfill for the DOM Events APIs:

Implementation extracted from the Node.js codebase as of 10th March 2024 (version 21.7.1, I believe). Some simplified internals extracted from readable-stream.

To clarify, this project is not affiliated with WinterCG (i.e. is not an official work). It merely implements part of the WinterCG Common Minimum API proposal.

Installation

Install this npm package as follows, depending on which package manager you're using.

  • npm:

    npm install --save dom-events-wintercg
  • Yarn:

    yarn add dom-events-wintercg
  • pnpm:

    pnpm add dom-events-wintercg
  • Bun:

    bun add dom-events-wintercg
  • Deno: No need to install. Just add the npm: specifier when importing.

Usage

As a polyfill

Run this polyfill in your app's entrypoint file so that it fills in the APIs as early as possible in the app lifecycle.

import { polyfill } from 'dom-events-wintercg';

polyfill(globalThis);

// Event, EventTarget, and CustomEvent will now be available in global scope

const eventTarget = new EventTarget();
const event = new Event('click', {});
eventTarget.addEventListener('click', (event) => {
  console.log(`Fired "${event.type}" event!`, event);
});
eventTarget.dispatchEvent(event, 'abc');

And for TypeScript typings, add the DOM lib in tsconfig.json:

{
  "compilerOptions": {
    "lib": ["DOM"],
    // ...
  }
}

As a module

Here, we import from the npm package each time we want to use an API, rather than polyfilling globally.

import { Event, EventTarget } from 'dom-events-wintercg';

const eventTarget = new EventTarget();
const event = new Event('click', {});
eventTarget.addEventListener('click', (event) => {
  console.log(`Fired "${event.type}" event!`, event);
});
eventTarget.dispatchEvent(event, 'abc');

Some limited TypeScript typings will be inferred from the library's JavaScript source code, but if you'd rather use the lib.dom.d.ts typings built into TypeScript (which I would recommend), then:

  1. Add the DOM lib in tsconfig.json:

    {
      "compilerOptions": {
        "lib": ["DOM"],
        // ...
      }
    }
  2. Do this little dance:

    import {
      Event as EventImpl,
      EventTarget as EventTargetImpl,
    } from 'dom-events-wintercg';
    
    // Redeclare the implementation using the types from lib.dom.d.ts
    const Event = EventImpl as unknown as Event;
    const EventTarget = EventTargetImpl as unknown as EventTarget;
    
    const eventTarget = new EventTarget();
    const event = new Event('click', {});
    eventTarget.addEventListener('click', (event) => {
      console.log(`Fired "${event.type}" event!`, event);
    });
    eventTarget.dispatchEvent(event, 'abc');

Via a bundler

This is my best-effort attempt to document usage with a bundler. These instructions are untested, so please open a PR if you find they need tweaking!

In all cases, you can set up TypeScript typings via adding the DOM lib to your tsconfig.json:

{
  "compilerOptions": {
    "lib": ["DOM"],
    // ...
  }
}

Below, I'll describe for each bundler how to integrate this package into your bundle.

Webpack 5

This configuration ensures that CustomEvent, Event, and EventTarget are available from global scope:

const webpackConfig = {
  plugins: [
    new webpack.ProvidePlugin({
      CustomEvent: ['dom-events-wintercg', 'CustomEvent'],
      Event: ['dom-events-wintercg', 'Event'],
      EventTarget: ['dom-events-wintercg', 'EventTarget'],
    }),
  ],
};

Additionally, you can polyfill some of the Node.js events module (e.g. to use a Node.js library in a browser app) as follows. ⚠️ Be warned that while this package implements CustomEvent, Event, and EventTarget, it does not implement all the APIs in the Node.js events module. For example, it does not implement EventEmitter.

  const webpackConfig = {
+   resolve: {
+     fallback: {
+       events: require.resolve('dom-events-wintercg'),
+     },
+   },
    plugins: [
      new webpack.ProvidePlugin({
        CustomEvent: ['dom-events-wintercg', 'CustomEvent'],
        Event: ['dom-events-wintercg', 'Event'],
        EventTarget: ['dom-events-wintercg', 'EventTarget'],
      }),
    ],
  };

Prerequisities

Your JS engine or runtime must support the following APIs (this is a non-exhaustive list):

Differences from browser EventTarget

Beyond the differences explained in the Node.js SDK docs, see this excellent article from NearForm about how they first brought EventTarget to Node.js, which covers some of the compromises they had to make in the implementation. In particular, there is no concept of bubbling or capturing, and event.preventDefault() is a bit useless, as it never has a "default action" to prevent.

Integrating into runtimes

This library, being runtime-agnostic, does nothing to keep the event loop alive for Worker event listeners. See the Node.js internals for how they implemented that.

About

A standalone implementation of the DOM Events APIs, extracted from the Node.js codebase, for usage in WinterCG runtimes.

Resources

License

MIT and 2 other licenses found

Licenses found

MIT
LICENCE
MIT
LICENCE-abort-controller
Unknown
LICENCE-nodejs

Stars

Watchers

Forks

Packages

No packages published