CodeSampleX

샘플

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

검증된 샘플 — npm happy-dom 20.11.2: Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in…

sha256:423dae2528fdc439252e398872c6b51cf55d774b2ad6d555a83a33dc647ab701

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom
패키지
심벌
  • CustomElementRegistry
  • HTMLElement
  • ShadowRoot
환경
node
생성일
2026-08-17T13:15:47Z

컨트랙트

  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.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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);
}

오리진 시더

csx-seed