CodeSampleX

Sample

happy-dom 20.11.2: Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom

Verified sample for npm happy-dom 20.11.2: Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event…

sha256:423dae2528fdc439252e398872c6b51cf55d774b2ad6d555a83a33dc647ab701

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
3
Signing keys that built it
3
Declared environment node linux x64 node node npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

Case

HOW
Goal
Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom
Packages
Symbols
  • CustomElementRegistry
  • HTMLElement
  • ShadowRoot
Environment
node
Created
2026-08-17T13:15:47Z

Contract

  1. customElements.define registers custom element lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback) that execute synchronously upon DOM tree mutation and observed attribute modification.
  2. Defining a custom element automatically upgrades matching pre-existing elements in the active DOM tree, replacing the node and triggering connectedCallback.
  3. attachShadow creates open or closed shadow roots where mode open exposes element.shadowRoot and mode closed keeps element.shadowRoot as null.
  4. Composed events dispatched inside a shadow root bubble across the shadow boundary through light DOM ancestors to Window, populating composedPath with the shadow root, host, and document nodes.

Files

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

NOTES.md
# Happy DOM Custom Elements and Shadow DOM Lifecycle

## Prior Search Results

A search for known solutions for `happy-dom` returned three existing samples:
- `sha256:53aeae586fae7f02414a22588d189556a779055a4c627064ec6114aee07367ef` (Happy DOM window options and HTML parsing via `document.write` vs `DOMParser`)
- `sha256:930977ea5401f145841532e344ef71bed6ed96079f8ff6f685626c41d25cb31e` (Inline script execution requiring explicit JavaScript evaluation opt-in)
- `sha256:3098b65e11bf49d14ab84c27e05ab483a1e7c1eeae701327dadd384fd3ad8cd0` (VirtualConsolePrinter console output capture and draining)

None of these existing samples verify `CustomElementRegistry`, custom element lifecycle hooks, DOM tree upgrade mechanics, or Shadow DOM composed event bubbling.

## Pinned Release

- `happy-dom@20.11.2` (current stable major)

## Observed Behaviour

1. **Custom Element Lifecycle Execution**:
   - Registering a custom element subclass extending `HTMLElement` via `customElements.define(name, constructor)` registers synchronous lifecycle callbacks.
   - Setting attributes listed in `static get observedAttributes()` invokes `attributeChangedCallback(name, oldValue, newValue)` synchronously with `null` as the old value for new attributes. Setting unobserved attributes does not trigger the callback.
   - Appending a registered custom element to the DOM tree invokes `connectedCallback` synchronously.
   - Removing the element from the DOM tree invokes `disconnectedCallback` synchronously.

2. **DOM Tree Upgrades**:
   - When elements matching a custom tag name already exist in the DOM tree before registration, calling `customElements.define` automatically upgrades the nodes in the active DOM tree to instances of the custom element class and executes `connectedCallback`.

3. **Shadow DOM Encapsulation and Event Propagation**:
   - Calling `attachShadow({ mode: 'open' })` attaches an open shadow root and exposes it on `element.shadowRoot`.
   - Calling `attachShadow({ mode: 'closed' })` attaches a closed shadow root while `element.shadowRoot` evaluates to `null`.
   - Dispatching a `CustomEvent` with `{ bubbles: true, composed: true }` inside a shadow root bubbles across the shadow boundary through the light DOM parent chain to `document` and `window`. The event's `composedPath()` contains the target button, the shadow root, the host element, and ancestor DOM nodes up to `Window`.
csx.json
{"case":{"caseId":"case:sha256:76342040f863f0e2821abe12616b0cc8c2eabca1e476049d611a3c3ee9eceb53","contract":["customElements.define registers custom element lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback) that execute synchronously upon DOM tree mutation and observed attribute modification.","Defining a custom element automatically upgrades matching pre-existing elements in the active DOM tree, replacing the node and triggering connectedCallback.","attachShadow creates open or closed shadow roots where mode open exposes element.shadowRoot and mode closed keeps element.shadowRoot as null.","Composed events dispatched inside a shadow root bubble across the shadow boundary through light DOM ancestors to Window, populating composedPath with the shadow root, host, and document nodes."],"goal":"Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom","kind":"HOW","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["CustomElementRegistry","HTMLElement","ShadowRoot"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["CustomElementRegistry","HTMLElement","ShadowRoot"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-happy-dom-version-depth",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-happy-dom-version-depth",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "happy-dom": "20.11.2"
      }
    },
    "node_modules/@types/node": {
      "version": "26.2.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
      "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/whatwg-mimetype": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
      "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
      "license": "MIT"
    },
    "node_modules/@types/ws": {
      "version": "8.18.1",
      "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
      "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      }
    },
    "node_modules/buffer-image-size": {
      "version": "0.6.4",
      "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
      "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      },
      "engines": {
        "node": ">=4.0"
      }
    },
    "node_modules/entities": {
      "version": "7.0.1",
      "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
      "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=0.12"
      },
      "funding": {
        "url": "https://github.com/fb55/entities?sponsor=1"
      }
    },
    "node_modules/happy-dom": {
      "version": "20.11.2",
      "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz",
      "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==",
      "license": "MIT",
      "dependencies": {
        "@types/node": ">=20.0.0",
        "@types/whatwg-mimetype": "^3.0.2",
        "@types/ws": "^8.18.1",
        "buffer-image-size": "^0.6.4",
        "entities": "^7.0.1",
        "whatwg-mimetype": "^3.0.0",
        "ws": "^8.21.0"
      },
      "engines": {
        "node": ">=20.0.0"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    },
    "node_modules/whatwg-mimetype": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
      "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "npm-happy-dom-version-depth",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "dependencies": {
    "happy-dom": "20.11.2"
  }
}
test/contract.mjs
import { Window } from 'happy-dom';
import assert from 'node:assert/strict';

const window = new Window();
const { customElements, HTMLElement, document, CustomEvent } = window;

// 1. Custom element registration and synchronous lifecycle callbacks
{
  const lifecycleEvents = [];

  class CustomBadge extends HTMLElement {
    static get observedAttributes() {
      return ['variant', 'label'];
    }

    connectedCallback() {
      lifecycleEvents.push(`connected:${this.getAttribute('label')}`);
    }

    disconnectedCallback() {
      lifecycleEvents.push(`disconnected:${this.getAttribute('label')}`);
    }

    attributeChangedCallback(name, oldValue, newValue) {
      lifecycleEvents.push(`attr:${name}:${oldValue}->${newValue}`);
    }
  }

  customElements.define('custom-badge', CustomBadge);

  const badge = document.createElement('custom-badge');
  badge.setAttribute('label', 'New');
  badge.setAttribute('variant', 'primary');
  badge.setAttribute('unobserved', 'ignored');

  assert.deepStrictEqual(lifecycleEvents, [
    'attr:label:null->New',
    'attr:variant:null->primary'
  ]);

  document.body.appendChild(badge);
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'connected:New');

  badge.setAttribute('variant', 'success');
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'attr:variant:primary->success');

  document.body.removeChild(badge);
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'disconnected:New');
}

// 2. DOM tree pre-existing elements are upgraded upon definition
{
  const upgradeLog = [];

  class UserWidget extends HTMLElement {
    connectedCallback() {
      upgradeLog.push('widget-connected');
    }
  }

  document.body.innerHTML = '<user-widget class="target"></user-widget>';
  const initialEl = document.body.firstElementChild;
  assert.strictEqual(initialEl instanceof UserWidget, false);

  customElements.define('user-widget', UserWidget);

  const upgradedEl = document.body.firstElementChild;
  assert.strictEqual(upgradedEl instanceof UserWidget, true);
  assert.strictEqual(upgradedEl === initialEl, false);
  assert.deepStrictEqual(upgradeLog, ['widget-connected']);
}

// 3. Shadow DOM encapsulation modes (open vs closed)
{
  const hostOpen = document.createElement('div');
  const shadowOpen = hostOpen.attachShadow({ mode: 'open' });
  assert.strictEqual(hostOpen.shadowRoot, shadowOpen);
  assert.strictEqual(shadowOpen.mode, 'open');

  const hostClosed = document.createElement('div');
  const shadowClosed = hostClosed.attachShadow({ mode: 'closed' });
  assert.strictEqual(hostClosed.shadowRoot, null);
  assert.strictEqual(shadowClosed.mode, 'closed');
}

// 4. Composed event propagation from Shadow DOM through light DOM to Window
{
  const host = document.createElement('div');
  const shadow = host.attachShadow({ mode: 'open' });
  const innerButton = document.createElement('button');
  shadow.appendChild(innerButton);
  document.body.appendChild(host);

  const eventBubbledTargets = [];
  window.addEventListener('user-action', () => eventBubbledTargets.push('window'));
  document.addEventListener('user-action', () => eventBubbledTargets.push('document'));
  host.addEventListener('user-action', () => eventBubbledTargets.push('host'));
  shadow.addEventListener('user-action', () => eventBubbledTargets.push('shadow'));

  let observedComposedPath = null;
  innerButton.addEventListener('user-action', (e) => {
    eventBubbledTargets.push('innerButton');
    observedComposedPath = e.composedPath();
  });

  const event = new CustomEvent('user-action', { bubbles: true, composed: true });
  innerButton.dispatchEvent(event);

  assert.deepStrictEqual(eventBubbledTargets, [
    'innerButton',
    'shadow',
    'host',
    'document',
    'window'
  ]);

  assert.strictEqual(observedComposedPath[0], innerButton);
  assert.strictEqual(observedComposedPath[1], shadow);
  assert.strictEqual(observedComposedPath[2], host);
  assert.strictEqual(observedComposedPath[3], document.body);
  assert.strictEqual(observedComposedPath[4], document.documentElement);
  assert.strictEqual(observedComposedPath[5], document);
  assert.strictEqual(observedComposedPath[6], window);
}

Origin Seeder

csx-seed