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]>
This commit is contained in:
ekklesia
2026-08-27 07:21:14 -05:00
co-authored by Claude Opus 5
parent e03d38fcab
commit 07835b7b56
38 changed files with 1460 additions and 204 deletions
+23 -16
View File
@@ -1,4 +1,4 @@
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import { MODULE_UI_ABI_VERSION, type ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import { act, Component, type ReactElement, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -9,6 +9,7 @@ import type {
HostEventSourceFactory,
HostEventSourceOptions,
} from "../src/host-protocol.js";
import { deepQuery, isolatedMountTarget, isolatedText } from "./support/isolated-dom.js";
declare global {
// eslint-disable-next-line no-var
@@ -154,6 +155,7 @@ function artifact(
) {
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id,
mount(element: Element, context: ModuleUiHostContext) {
if (options.mount) {
@@ -204,7 +206,7 @@ describe("display host — full-viewport boundary", () => {
});
expect(imported).toEqual([`${apiBaseUrl}/api/v1/module-ui/announcements/1.2.0/display`]);
expect(query("display-module-container")?.textContent).toBe("announcements:display");
expect(isolatedText(query("display-module-container"))).toBe("announcements:display");
expect(container.querySelector("header")).toBeNull();
expect(container.querySelector("nav")).toBeNull();
expect(container.querySelector("aside")).toBeNull();
@@ -239,7 +241,7 @@ describe("display host — full-viewport boundary", () => {
"realtime",
]);
expect(seenContext?.principal).toEqual({ kind: "authenticated", userId: "user-1" });
expect(query("display-module-container")?.textContent).toBe("permitted");
expect(isolatedText(query("display-module-container"))).toBe("permitted");
expect(
server.calls.some((call) => call.url.endsWith("/api/v1/modules/announcements/slides")),
).toBe(true);
@@ -255,6 +257,7 @@ describe("display host — full-viewport boundary", () => {
const requestedArtifacts: string[] = [];
const source = `
export default {
abi: ${MODULE_UI_ABI_VERSION},
id: "announcements",
version: "1.2.0",
mount(container, context) {
@@ -303,7 +306,7 @@ describe("display host — full-viewport boundary", () => {
expect(requestedArtifacts).toEqual([
`${apiBaseUrl}/api/v1/module-ui/announcements/1.2.0/display`,
]);
expect(container.querySelector('[data-testid="announcement-slide"]')?.getAttribute("src")).toBe(
expect(deepQuery(container, '[data-testid="announcement-slide"]')?.getAttribute("src")).toBe(
deliveryUrl,
);
expect(container.innerHTML).not.toContain("socket.io");
@@ -375,7 +378,10 @@ describe("display host — full-viewport boundary", () => {
};
await act(async () => root.render(<HostApp config={config} importModule={importer} />));
expect(container.textContent).toContain("announcement management");
// The management artifact rendered inside its own isolated root, not the shell's own tree.
expect(isolatedText(container.querySelector('[data-testid="module-container"]'))).toContain(
"announcement management",
);
expect(container.querySelector("nav")).not.toBeNull();
expect(requestedArtifacts).toEqual([`${apiBaseUrl}/api/v1/module-ui/announcements/1.2.0`]);
@@ -401,7 +407,7 @@ describe("display host — full-viewport boundary", () => {
`${apiBaseUrl}/api/v1/module-ui/announcements/1.2.0`,
`${apiBaseUrl}/api/v1/module-ui/announcements/1.2.0/display`,
]);
expect(container.querySelector('[data-testid="both-role-slide"]')?.getAttribute("src")).toBe(
expect(deepQuery(container, '[data-testid="both-role-slide"]')?.getAttribute("src")).toBe(
deliveryUrl,
);
expect(container.querySelector("nav")).toBeNull();
@@ -478,7 +484,7 @@ describe("display host — authentication and controlled failures", () => {
await act(async () => query("display-retry")?.click());
expect(query("display-error")).toBeNull();
expect(query("display-module-container")?.textContent).toBe("recovered");
expect(isolatedText(query("display-module-container"))).toBe("recovered");
expect(containers).toHaveLength(2);
expect(containers[0]).not.toBe(containers[1]);
expect(containers[0]?.isConnected).toBe(false);
@@ -508,7 +514,7 @@ describe("display host — authentication and controlled failures", () => {
);
await render({ apiBaseUrl, fetch: server.fetch }, importer);
expect(query("display-module-container")?.textContent).toContain("/srv/modules");
expect(isolatedText(query("display-module-container"))).toContain("/srv/modules");
consoleError.mockClear();
await act(async () => {
@@ -525,7 +531,7 @@ describe("display host — authentication and controlled failures", () => {
});
expect(query("display-error")).not.toBeNull();
expect(query("display-module-container")?.textContent).toBe("");
expect(isolatedText(query("display-module-container"))).toBe("");
expect(container.textContent).toBe("This display could not be loaded.Retry");
expect(container.textContent).not.toMatch(/secret|\/srv\//u);
expect(importer).toHaveBeenCalledTimes(1);
@@ -541,7 +547,7 @@ describe("display host — authentication and controlled failures", () => {
expect(importer).toHaveBeenCalledTimes(2);
expect(query("display-error")).toBeNull();
expect(query("display-module-container")?.textContent).toContain("/srv/modules");
expect(isolatedText(query("display-module-container"))).toContain("/srv/modules");
expect(mountedInto[0]?.isConnected).toBe(false);
expect(mountedInto[1]?.isConnected).toBe(true);
});
@@ -610,7 +616,7 @@ describe("display host — authentication and controlled failures", () => {
);
await act(async () => {
container.querySelector('[data-testid="display-media"]')?.dispatchEvent(
deepQuery(container, '[data-testid="display-media"]')?.dispatchEvent(
new ErrorEvent("error", {
bubbles: true,
cancelable: true,
@@ -620,7 +626,7 @@ describe("display host — authentication and controlled failures", () => {
});
expect(query("display-error")).toBeNull();
expect(query("display-media")).not.toBeNull();
expect(deepQuery(container, '[data-testid="display-media"]')).not.toBeNull();
expect(cleanup).not.toHaveBeenCalled();
});
@@ -686,7 +692,7 @@ describe("display host — independent instances and stale work", () => {
expect(cleanups).toHaveLength(1);
expect(container.querySelectorAll('[data-testid="display-module-container"]')).toHaveLength(1);
expect(query("display-module-container")?.textContent).toBe("announcements:display");
expect(isolatedText(query("display-module-container"))).toBe("announcements:display");
});
it("discards a late import into its detached container without disturbing the newer route", async () => {
@@ -728,7 +734,7 @@ describe("display host — independent instances and stale work", () => {
await render(config, importer);
await render(config, importer, "calendar");
expect(query("display-module-container")?.textContent).toBe("calendar-live");
expect(isolatedText(query("display-module-container"))).toBe("calendar-live");
const liveContainer = query("display-module-container");
await act(async () => {
@@ -737,8 +743,9 @@ describe("display host — independent instances and stale work", () => {
});
expect(query("display-module-container")).toBe(liveContainer);
expect(liveContainer?.textContent).toBe("calendar-live");
const staleContainer = mountedInto.find((element) => element !== liveContainer);
expect(isolatedText(liveContainer)).toBe("calendar-live");
const liveMountTarget = isolatedMountTarget(liveContainer);
const staleContainer = mountedInto.find((element) => element !== liveMountTarget);
expect(staleContainer?.isConnected).toBe(false);
expect(staleUnmounts).toEqual([staleContainer]);
});
+28 -19
View File
@@ -1,9 +1,10 @@
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import { MODULE_UI_ABI_VERSION, type ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { HostApp } from "../src/browser/HostApp.js";
import type { EkklesiaHostConfig } from "../src/host-protocol.js";
import { isolatedMountTarget, isolatedText } from "./support/isolated-dom.js";
declare global {
// eslint-disable-next-line no-var
@@ -99,6 +100,7 @@ interface ArtifactOptions {
function artifact(id: string, version: string, options: ArtifactOptions = {}) {
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id,
mount(element: Element, context: ModuleUiHostContext) {
options.mountedInto?.push(element);
@@ -443,7 +445,7 @@ describe("Ekklesia shell — browser authentication", () => {
expect(query("host-login")).toBeNull();
expect(query("host-logout")).not.toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
expect(importer).toHaveBeenCalledOnce();
expect(platform.calls.map((call) => new URL(call.url).pathname)).toEqual([
"/api/v1/principal",
@@ -565,6 +567,7 @@ describe("Ekklesia shell — logout and session expiration", () => {
},
async () => ({
default: {
abi: MODULE_UI_ABI_VERSION,
id: "example",
mount(element: Element, context: ModuleUiHostContext) {
element.textContent = "example mounted";
@@ -693,6 +696,7 @@ describe("Ekklesia shell — logout and session expiration", () => {
) {
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id: "example",
mount(element: Element, context: ModuleUiHostContext) {
capture.context = context;
@@ -770,7 +774,7 @@ describe("Ekklesia shell — logout and session expiration", () => {
});
expect(query("host-login")).toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
expect(capture.unmountCalls).toBe(0);
expect(platform.calls.filter((call) => call.url.endsWith("/api/v1/principal"))).toHaveLength(2);
});
@@ -790,7 +794,7 @@ describe("Ekklesia shell — logout and session expiration", () => {
});
expect(query("host-login")).toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
expect(capture.unmountCalls).toBe(0);
expect(platform.calls.filter((call) => call.url.endsWith("/api/v1/principal"))).toHaveLength(2);
});
@@ -920,7 +924,7 @@ describe("Ekklesia shell — Dashboard navigation", () => {
`${apiBaseUrl}/api/v1/module-ui/video/0.1.0`,
`${apiBaseUrl}/api/v1/module-ui/calendar/0.1.0`,
]);
expect(query("module-container")?.textContent).toBe("calendar mounted");
expect(isolatedText(query("module-container"))).toBe("calendar mounted");
});
it("mounts the identical artifact whichever group a module is presented in", async () => {
@@ -972,10 +976,11 @@ describe("Ekklesia shell — mount lifecycle", () => {
artifact("example", "0.1.0", { mountedInto }),
);
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
expect(query("module-loading")).toBeNull();
// The module was handed the shell's container, never the page root or the shell's own layout.
expect(mountedInto[0]).toBe(query("module-container"));
// The artifact receives the loader's isolated root, never the shell's own element (ADR 0040).
expect(mountedInto[0]).toBe(isolatedMountTarget(query("module-container")));
expect(mountedInto[0]).not.toBe(container);
expect(mountedInto[0]).not.toBe(document.body);
});
@@ -1002,7 +1007,7 @@ describe("Ekklesia shell — mount lifecycle", () => {
});
expect(query("module-loading")).not.toBeNull();
expect(query("module-container")?.textContent).toBe("");
expect(isolatedText(query("module-container"))).toBe("");
await act(async () => {
release?.();
@@ -1010,7 +1015,7 @@ describe("Ekklesia shell — mount lifecycle", () => {
});
expect(query("module-loading")).toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
});
it("unmounts the previous module when the selection changes", async () => {
@@ -1019,6 +1024,7 @@ describe("Ekklesia shell — mount lifecycle", () => {
const id = url.includes("/calendar/") ? "calendar" : "example";
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id,
mount(element: Element) {
element.textContent = `${id} mounted`;
@@ -1040,14 +1046,14 @@ describe("Ekklesia shell — mount lifecycle", () => {
},
importModule,
);
expect(query("module-container")?.textContent).toBe("example mounted");
expect(isolatedText(query("module-container"))).toBe("example mounted");
await act(async () => {
(query("select-calendar") as HTMLButtonElement).click();
});
expect(unmountedContainers).toHaveLength(1);
expect(query("module-container")?.textContent).toBe("calendar mounted");
expect(isolatedText(query("module-container"))).toBe("calendar mounted");
});
it("keeps a stale load from ever reaching the newer selection's container", async () => {
@@ -1065,6 +1071,7 @@ describe("Ekklesia shell — mount lifecycle", () => {
}
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id,
mount(element: Element) {
mountedInto.push(element);
@@ -1096,7 +1103,8 @@ describe("Ekklesia shell — mount lifecycle", () => {
(query("select-calendar") as HTMLButtonElement).click();
});
const liveContainer = query("module-container");
expect(liveContainer?.textContent).toBe("calendar mounted");
const liveMountTarget = isolatedMountTarget(liveContainer);
expect(isolatedText(liveContainer)).toBe("calendar mounted");
// Only now does the stale `example` import resolve.
await act(async () => {
@@ -1104,10 +1112,10 @@ describe("Ekklesia shell — mount lifecycle", () => {
await examplePending;
});
// It mounted into its own, already-discarded container — never the live one — and was torn
// It mounted into its own, already-discarded isolated root — never the live one — and was torn
// down immediately, so the newer selection is untouched.
expect(liveContainer?.textContent).toBe("calendar mounted");
const staleContainer = mountedInto.find((element) => element !== liveContainer);
expect(isolatedText(liveContainer)).toBe("calendar mounted");
const staleContainer = mountedInto.find((element) => element !== liveMountTarget);
expect(staleContainer).toBeDefined();
expect(staleContainer?.isConnected).toBe(false);
expect(unmountedContainers).toContain(staleContainer);
@@ -1140,7 +1148,7 @@ describe("Ekklesia shell — failure is host-owned", () => {
await render({ apiBaseUrl, fetch: platformFetch() }, async () => artifact("example", "9.9.9"));
expect(query("module-error")).not.toBeNull();
expect(query("module-container")?.textContent).toBe("");
expect(isolatedText(query("module-container"))).toBe("");
});
it("renders its own error when the module's mount throws", async () => {
@@ -1174,7 +1182,7 @@ describe("Ekklesia shell — failure is host-owned", () => {
});
expect(query("module-error")).toBeNull();
expect(query("module-container")?.textContent).toBe("calendar mounted");
expect(isolatedText(query("module-container"))).toBe("calendar mounted");
});
it("survives a module whose cleanup throws, and never re-runs it", async () => {
@@ -1185,6 +1193,7 @@ describe("Ekklesia shell — failure is host-owned", () => {
}
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id: "example",
mount(element: Element) {
element.textContent = "example mounted";
@@ -1212,7 +1221,7 @@ describe("Ekklesia shell — failure is host-owned", () => {
});
expect(cleanupCalls).toBe(1);
expect(query("module-container")?.textContent).toBe("calendar mounted");
expect(isolatedText(query("module-container"))).toBe("calendar mounted");
// Switch back and away again: the throwing cleanup ran once per mount, never re-invoked for an
// instance already torn down.
@@ -1223,6 +1232,6 @@ describe("Ekklesia shell — failure is host-owned", () => {
(query("select-calendar") as HTMLButtonElement).click();
});
expect(cleanupCalls).toBe(2);
expect(query("module-container")?.textContent).toBe("calendar mounted");
expect(isolatedText(query("module-container"))).toBe("calendar mounted");
});
});
@@ -0,0 +1,55 @@
/**
* Test helpers for reaching a mounted module artifact's DOM.
*
* Since ADR 0040 the generic loader mounts every declared browser artifact inside its own Shadow DOM
* root, so a module's elements are deliberately *not* in the host document's tree: `querySelector`
* on the shell's container cannot see them, and neither can a stray Dashboard stylesheet. These
* helpers walk into those open roots so a shell test can still assert on what a module rendered —
* which is exactly what a host's own diagnostics would do, and is why the roots are `open`.
*
* Deliberately test-only. Production shell code never reaches into an artifact's root; the module
* owns its contents.
*/
const ISOLATION_HOST_SELECTOR = "[data-ekklesia-module-ui]";
function isolatedRoots(root: ParentNode): readonly ShadowRoot[] {
return [...root.querySelectorAll(ISOLATION_HOST_SELECTOR)]
.map((host) => host.shadowRoot)
.filter((shadowRoot): shadowRoot is ShadowRoot => shadowRoot !== null);
}
/** The first match anywhere in `root`, including inside every mounted artifact's isolated root. */
export function deepQuery(root: ParentNode, selector: string): Element | null {
const direct = root.querySelector(selector);
if (direct) {
return direct;
}
for (const shadowRoot of isolatedRoots(root)) {
const nested = deepQuery(shadowRoot, selector);
if (nested) {
return nested;
}
}
return null;
}
/** Every match anywhere in `root`, host tree first, then each artifact's isolated root in order. */
export function deepQueryAll(root: ParentNode, selector: string): readonly Element[] {
return [
...root.querySelectorAll(selector),
...isolatedRoots(root).flatMap((shadowRoot) => [...deepQueryAll(shadowRoot, selector)]),
];
}
/** The text an artifact rendered, read from the exact element the loader hands its `mount` — so the
* stylesheet the loader installed alongside it is never mistaken for content. */
export function isolatedText(container: Element | null | undefined): string {
return isolatedMountTarget(container)?.textContent ?? "";
}
/** The element the loader passed to a mounted artifact's `mount`, for identity assertions. */
export function isolatedMountTarget(container: Element | null | undefined): Element | null {
const host = container?.querySelector(ISOLATION_HOST_SELECTOR);
return host?.shadowRoot?.querySelector("[data-ekklesia-module-ui-root]") ?? null;
}