Files
Ekklesia/packages/module-ui-host/src/isolated-root.ts
T
ekklesiaandClaude Opus 5 07835b7b56 feat: give module UI real stylesheets, and every artifact its own root
ADR 0023 refused stylesheet imports for a good reason: esbuild would emit a
`.css` sidecar beside the artifact, nothing would declare it, no host would
fetch it, and it would work in a local test and silently do nothing in a real
host. Inline style objects were the whole story. They cannot express
`:hover`, `:focus-visible`, `:disabled`, `@media`, or `@keyframes` — so an
accessible focus treatment was not expressible, and the shared elements added
in the previous commit are built from real CSS for exactly that reason.

Compile the stylesheet into the artifact instead of beside it. A module
imports plain `.css`; the canonical builder resolves local `@import`s through
a nested bundle and turns each file into its compiled text, which the author
declares as `defineModuleUi({ styles })`. One declared file still contains
everything: nothing extra to publish, nothing to fetch, and no way for CSS to
become an asset nobody serves. The build additionally fails if a CSS output
ever appears beside an artifact, so a future loader change cannot bring the
sidecar back. Two rules are enforced with their own codes: a module stylesheet
may reference `--ekklesia-*` and never declare one, and every `@import` must
resolve locally or the artifact would fetch styles at run time. Plain `.css`
only; other dialects are a toolchain decision needing their own ADR.

Then make the isolation real. The generic loader mounts every browser artifact
— primary, display, and later a contributed renderer — inside an open Shadow
DOM root it creates, installs the artifact's stylesheet there, and hands the
artifact an element inside it. Shadow DOM is the one mechanism a browser
actually enforces; a class prefix or a "scope your selectors" instruction is a
convention one mistake defeats, and the failure mode is a module silently
restyling the Dashboard. It applies unconditionally, including to artifacts
with no stylesheet, because a conditional boundary is one a module can fall
out of by editing a source file. Both wrappers are `display: contents` through
base rules installed before the artifact's own, so layout is unchanged and a
full-viewport display can still override `:host`. Unmount removes the whole
root in a `finally`, so a cleanup that throws cannot leave styles behind, and
remounting cannot accumulate a second copy.

This is a correctness boundary for styles and is not described as a sandbox:
the root is `open` precisely because module code is trusted, same-realm code
that could reach `document` anyway.

An artifact's DOM is no longer a direct child of the host's element, so the
mount ABI is versioned explicitly. `defineModuleUi` stamps
`MODULE_UI_ABI_VERSION` so it can never drift from the SDK the artifact
compiled against, and a version-1 artifact fails with its own code — "rebuild
your module", not a typo hunt. No dual acceptance, matching every manifest
cutover here. Migration is one `pnpm build`.

`pnpm boundaries` allows `.css` only under `src/ui/` and `src/display/`: a
stylesheet anywhere else in a module is the undeclared sidecar again, just
relocated.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-27 07:21:14 -05:00

109 lines
5.0 KiB
TypeScript

/**
* The isolated root a host mounts a browser artifact into (ADR 0040).
*
* Every declared browser artifact — a module's primary UI, its display UI, and a contributed
* renderer — is mounted the same way, into its own Shadow DOM root the loader creates and owns:
*
* ```text
* host container ← the host's element; the loader never mutates it beyond this child
* └─ <div data-ekklesia-module-ui> ← shadow host, created and removed by the loader
* #shadow-root (open)
* ├─ <style data-ekklesia-module-ui-styles> base rules + the artifact's declared CSS
* └─ <div data-ekklesia-module-ui-root> ← the Element handed to mount()
* ```
*
* Shadow DOM is chosen because it is the one mechanism in a browser that actually **enforces** the
* rule rather than describing it: rules inside a shadow root do not apply outside it, and document
* rules do not apply inside it. A class-name convention, a build-time prefix, or a "please scope
* your selectors" instruction are all conventions a single mistake defeats, and the failure mode is
* a module silently restyling the Dashboard or another module's renderer.
*
* It is **not** a security boundary, and nothing here should be read as one. `mode: "open"` is
* deliberate: an installed module is trusted first-party code running in the host's own realm
* (ADR 0022, ADR 0024), it could reach `document` directly if it wanted to, and `mode: "closed"`
* would buy no protection while making the artifact's DOM unreachable to the host's own tests and
* diagnostics. This is a correctness boundary for *styles*, not a sandbox.
*
* Custom properties inherit through a shadow boundary, so the design tokens a host installed at its
* root (ADR 0039) are available inside every artifact with nothing passed and nothing imported.
*/
export const MODULE_UI_ISOLATION_ATTRIBUTE = "data-ekklesia-module-ui";
export const MODULE_UI_ISOLATION_STYLE_ATTRIBUTE = "data-ekklesia-module-ui-styles";
export const MODULE_UI_ISOLATION_ROOT_ATTRIBUTE = "data-ekklesia-module-ui-root";
/**
* The rules the host always installs, before any artifact CSS.
*
* Both wrappers are `display: contents`, so the two elements the loader adds contribute no boxes of
* their own and an artifact's own top-level elements lay out inside the host's container exactly as
* they did before isolation existed. They are declared as CSS rather than inline styles precisely so
* an artifact's own stylesheet — which the host appends *after* these — can override them when it
* genuinely needs a box to size.
*/
const BASE_STYLESHEET = `:host{display:contents}\n[${MODULE_UI_ISOLATION_ROOT_ATTRIBUTE}]{display:contents}`;
export interface IsolatedArtifactRoot {
/** The element handed to the artifact's `mount`. */
readonly mountTarget: Element;
/** The open shadow root, for a host's own tests and diagnostics. */
readonly shadowRoot: ShadowRoot;
/** Removes the whole isolated root — content and styles together. Idempotent. */
dispose(): void;
}
/**
* Builds one isolated root inside `container` and returns it.
*
* Nothing is attached to `container` until the shadow root, its stylesheet, and its mount target
* have all been created, so a host whose environment cannot provide Shadow DOM gets a thrown error
* and an untouched container rather than a half-built, unisolated mount.
*
* Each call creates a **fresh** root, and `dispose` removes it whole. That is what makes styles
* deterministic in both directions: a mount installs exactly one `<style>`, an unmount removes it
* with the element that owns it, and remounting cannot accumulate a second copy because there is
* nothing left to accumulate onto.
*/
export function createIsolatedArtifactRoot(
container: Element,
styles: string | undefined,
): IsolatedArtifactRoot {
const ownerDocument = container.ownerDocument;
if (!ownerDocument) {
throw new TypeError("A module UI container must belong to a document.");
}
const shadowHost = ownerDocument.createElement("div");
shadowHost.setAttribute(MODULE_UI_ISOLATION_ATTRIBUTE, "");
if (typeof shadowHost.attachShadow !== "function") {
throw new TypeError("This environment does not support Shadow DOM.");
}
const shadowRoot = shadowHost.attachShadow({ mode: "open" });
const style = ownerDocument.createElement("style");
style.setAttribute(MODULE_UI_ISOLATION_STYLE_ATTRIBUTE, "");
// The artifact's own CSS comes last, so it wins over the base rules above by ordinary cascade
// order rather than by anything the host has to special-case.
style.textContent = styles === undefined ? BASE_STYLESHEET : `${BASE_STYLESHEET}\n${styles}`;
shadowRoot.appendChild(style);
const mountTarget = ownerDocument.createElement("div");
mountTarget.setAttribute(MODULE_UI_ISOLATION_ROOT_ATTRIBUTE, "");
shadowRoot.appendChild(mountTarget);
container.appendChild(shadowHost);
let disposed = false;
return {
dispose: () => {
if (disposed) {
return;
}
disposed = true;
shadowHost.remove();
},
mountTarget,
shadowRoot,
};
}