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
+1
View File
@@ -1 +1,2 @@
export * from "./isolated-root.js";
export * from "./load-module-ui.js";
@@ -0,0 +1,108 @@
/**
* 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,
};
}
+47 -8
View File
@@ -4,6 +4,7 @@ import {
type ModuleUiUnmount,
parseModuleUiExport,
} from "@ekklesia/module-ui-sdk";
import { createIsolatedArtifactRoot, type IsolatedArtifactRoot } from "./isolated-root.js";
/**
* How a host obtains a module's UI artifact.
@@ -45,7 +46,11 @@ const defaultImporter: ModuleUiImporter = (url) => import(url);
export interface LoadModuleUiOptions {
readonly source: ModuleUiSource;
/** The element the module renders into. The host owns it; the module owns its contents. */
/**
* The element the loader builds this artifact's isolated root inside. The host owns it, the
* module owns its own root's contents, and the loader adds and removes exactly one child of its
* own (ADR 0040). The artifact never receives this element.
*/
readonly container: Element;
/** Supplied whole by the host. This package forwards it and never adds to it. */
readonly context: ModuleUiHostContext;
@@ -61,16 +66,28 @@ export interface MountedModuleUi {
/** Whether cleanup is still pending. Becomes `false` after the first {@link unmount}. */
readonly mounted: boolean;
/**
* Runs the module's cleanup, if it returned one. Idempotent: the first call cleans up, later
* This artifact's open shadow root. Exposed so a host's own tests and diagnostics can see what an
* artifact actually rendered; a host has no reason to write to it, and doing so would be reaching
* into content the module owns.
*/
readonly shadowRoot: ShadowRoot;
/**
* Runs the module's cleanup, if it returned one, then removes the isolated root the loader
* created — content and installed styles together. Idempotent: the first call cleans up, later
* calls do nothing. Safe when the module returned no cleanup function.
*/
unmount(): Promise<void>;
}
export type ModuleUiHostErrorCode = "MODULE_UI_IMPORT_FAILED" | "MODULE_UI_MOUNT_FAILED";
export type ModuleUiHostErrorCode =
| "MODULE_UI_IMPORT_FAILED"
| "MODULE_UI_ISOLATION_UNAVAILABLE"
| "MODULE_UI_MOUNT_FAILED";
const errorMessages: Readonly<Record<ModuleUiHostErrorCode, string>> = Object.freeze({
MODULE_UI_IMPORT_FAILED: "A module UI artifact could not be imported from its published URL.",
MODULE_UI_ISOLATION_UNAVAILABLE:
"A module UI artifact could not be given an isolated root in this environment.",
MODULE_UI_MOUNT_FAILED: "A module UI artifact failed while mounting.",
});
@@ -103,6 +120,12 @@ export class ModuleUiHostError extends Error {
*
* Nothing is mounted until the artifact's declared identity matches the manifest identity the host
* passed in, so a stale or mismatched bundle fails before it can render or run `mount`.
*
* Every artifact is mounted into its own isolated root the loader creates inside `container`
* (ADR 0040), and the artifact's declared `styles` are installed there. That is what keeps one
* module's stylesheet out of the Dashboard, out of another module, and out of another contributed
* renderer — and it applies identically to every role, so there is one mounting path rather than a
* styled one and an unstyled one.
*/
export async function loadModuleUi(options: LoadModuleUiOptions): Promise<MountedModuleUi> {
const { container, context, source } = options;
@@ -124,16 +147,26 @@ export async function loadModuleUi(options: LoadModuleUiOptions): Promise<Mounte
version: source.version,
});
// Built before `mount` runs and torn down again if `mount` throws, so a failed artifact leaves
// neither DOM nor styles behind.
let isolated: IsolatedArtifactRoot;
try {
isolated = createIsolatedArtifactRoot(container, definition.styles);
} catch (error) {
throw new ModuleUiHostError("MODULE_UI_ISOLATION_UNAVAILABLE", { cause: error });
}
let cleanup: ModuleUiUnmount | undefined;
try {
const result = await definition.mount(container, context);
const result = await definition.mount(isolated.mountTarget, context);
if (typeof result === "function") {
cleanup = result;
}
} catch (error) {
// No cleanup is registered for a mount that never completed, so the returned handle can never
// claim a failed module is mounted. The container is deliberately left untouched: the host owns
// it and decides what a failed mount should look like.
// claim a failed module is mounted. The host's own container is deliberately left as it was:
// the host owns it and decides what a failed mount should look like.
isolated.dispose();
throw new ModuleUiHostError("MODULE_UI_MOUNT_FAILED", { cause: error });
}
@@ -144,14 +177,20 @@ export async function loadModuleUi(options: LoadModuleUiOptions): Promise<Mounte
get mounted() {
return mounted;
},
shadowRoot: isolated.shadowRoot,
async unmount() {
if (!mounted) {
return;
}
// Marked unmounted before running cleanup, so a throwing cleanup surfaces to the host once
// and a second call never re-runs it.
// and a second call never re-runs it. The isolated root is removed in a `finally`, so a
// module whose cleanup throws still has its styles taken out of the page.
mounted = false;
await cleanup?.();
try {
await cleanup?.();
} finally {
isolated.dispose();
}
},
};
}
@@ -0,0 +1,4 @@
declare module "*.css" {
const stylesheet: string;
export default stylesheet;
}
@@ -1,15 +1,19 @@
import { defineModuleUi } from "@ekklesia/module-ui-sdk";
import styles from "./styles.css";
/**
* A real module UI compiled by the canonical pipeline. It imports the public SDK so the built
* artifact proves the whole loop closes: SDK source -> esbuild bundle -> browser URL -> host loader.
*
* React is deliberately absent — the module template already proves the React path end to end, and
* omitting it keeps this artifact small enough to serve as a `data:` URL.
* omitting it keeps this artifact small enough to serve as a `data:` URL. It does import a local
* stylesheet, so the built artifact also proves the CSS half of that loop: `.css` source -> compiled
* text inside the declared artifact -> installed in the isolated root at mount (ADR 0040).
*/
export default defineModuleUi({
id: "example",
version: "0.1.0",
styles,
async mount(container, context) {
const response = await context.api.request("records");
const label = context.principal.kind === "authenticated" ? context.principal.userId : "guest";
@@ -0,0 +1,5 @@
/* Compiled into the artifact by the canonical builder and installed into its isolated root by the
* loader (ADR 0040). It references a global token and declares none of its own. */
.artifact-label {
color: var(--ekklesia-text-primary);
}
@@ -1,7 +1,18 @@
// @vitest-environment happy-dom
import { ModuleUiContractError, type ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import {
MODULE_UI_ABI_VERSION,
ModuleUiContractError,
type ModuleUiHostContext,
} from "@ekklesia/module-ui-sdk";
import { describe, expect, it } from "vitest";
import { loadModuleUi, ModuleUiHostError, type ModuleUiImporter } from "../src/index.js";
import {
loadModuleUi,
MODULE_UI_ISOLATION_ATTRIBUTE,
MODULE_UI_ISOLATION_ROOT_ATTRIBUTE,
MODULE_UI_ISOLATION_STYLE_ATTRIBUTE,
ModuleUiHostError,
type ModuleUiImporter,
} from "../src/index.js";
/**
* A browser-loadable URL for a module built from source text.
@@ -15,10 +26,14 @@ function moduleUrl(source: string): string {
return `data:text/javascript;base64,${Buffer.from(source, "utf8").toString("base64")}`;
}
const validArtifact = (options: { id?: string; version?: string; cleanup?: boolean } = {}) => `
const validArtifact = (
options: { id?: string; version?: string; cleanup?: boolean; styles?: string } = {},
) => `
export default {
abi: ${MODULE_UI_ABI_VERSION},
id: ${JSON.stringify(options.id ?? "announcements")},
version: ${JSON.stringify(options.version ?? "1.2.0")},
${options.styles === undefined ? "" : `styles: ${JSON.stringify(options.styles)},`}
mount(container, context) {
globalThis.__mounts ??= [];
globalThis.__mounts.push({ moduleId: context.moduleId, container });
@@ -54,6 +69,20 @@ function container(): Element {
return element;
}
/**
* What the artifact actually rendered, reached the way a host's own diagnostics would: through the
* open shadow root the loader created. The host's container itself holds only the loader's one
* wrapper element, which is exactly the isolation ADR 0040 introduced.
*/
function artifactRoot(element: Element): Element | null {
const shadowHost = element.querySelector(`[${MODULE_UI_ISOLATION_ATTRIBUTE}]`);
return shadowHost?.shadowRoot?.querySelector(`[${MODULE_UI_ISOLATION_ROOT_ATTRIBUTE}]`) ?? null;
}
function artifactText(element: Element): string {
return artifactRoot(element)?.textContent ?? "";
}
const source = { moduleId: "announcements", version: "1.2.0" };
describe("generic module UI host loader", () => {
@@ -70,10 +99,99 @@ describe("generic module UI host loader", () => {
expect(mounted.moduleId).toBe("announcements");
expect(mounted.version).toBe("1.2.0");
expect(mounted.mounted).toBe(true);
expect(element.textContent).toBe("mounted:announcements");
expect(artifactText(element)).toBe("mounted:announcements");
});
it("passes the host's own container and context straight through", async () => {
it("mounts the artifact into an isolated root rather than the host's own container", async () => {
const element = container();
const mounted = await loadModuleUi({
source: { ...source, url: moduleUrl(validArtifact()) },
container: element,
context: hostContext([]),
});
// The host's container gained exactly one child: the loader's shadow host.
expect(element.children).toHaveLength(1);
const shadowHost = element.firstElementChild as Element;
expect(shadowHost.hasAttribute(MODULE_UI_ISOLATION_ATTRIBUTE)).toBe(true);
expect(shadowHost.shadowRoot).toBe(mounted.shadowRoot);
// Open, deliberately: this is a correctness boundary for styles, not a sandbox — an installed
// module is trusted code in the host's own realm and could reach `document` regardless.
expect(mounted.shadowRoot.mode).toBe("open");
// The artifact's DOM is not reachable from the host's own document tree.
expect(element.textContent).toBe("");
});
it("installs a declared stylesheet inside the isolated root, exactly once", async () => {
const element = container();
const mounted = await loadModuleUi({
source: { ...source, url: moduleUrl(validArtifact({ styles: ".posts{color:red}" })) },
container: element,
context: hostContext([]),
});
const styles = mounted.shadowRoot.querySelectorAll(
`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`,
);
expect(styles).toHaveLength(1);
expect(styles[0]?.textContent).toContain(".posts{color:red}");
// The host document never receives the artifact's rules.
expect(document.head.querySelector(`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`)).toBeNull();
});
it("installs the host's base rules before the artifact's own, so an artifact can override them", async () => {
const element = container();
const mounted = await loadModuleUi({
source: { ...source, url: moduleUrl(validArtifact({ styles: ":host{display:block}" })) },
container: element,
context: hostContext([]),
});
const stylesheet =
mounted.shadowRoot.querySelector(`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`)
?.textContent ?? "";
expect(stylesheet.indexOf(":host{display:contents}")).toBeLessThan(
stylesheet.indexOf(":host{display:block}"),
);
});
it("still mounts an artifact that declares no stylesheet", async () => {
const element = container();
const mounted = await loadModuleUi({
source: { ...source, url: moduleUrl(validArtifact()) },
container: element,
context: hostContext([]),
});
expect(artifactText(element)).toBe("mounted:announcements");
expect(
mounted.shadowRoot.querySelectorAll(`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`),
).toHaveLength(1);
});
it("never accumulates styles across repeated mounts of the same container", async () => {
const element = container();
const url = moduleUrl(validArtifact({ styles: ".posts{color:red}" }));
for (let attempt = 0; attempt < 3; attempt += 1) {
const mounted = await loadModuleUi({
source: { ...source, url },
container: element,
context: hostContext([]),
});
expect(
mounted.shadowRoot.querySelectorAll(`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`),
).toHaveLength(1);
await mounted.unmount();
expect(element.children).toHaveLength(0);
}
});
it("passes the isolated mount target and the host's context straight through", async () => {
const element = container();
const requested: string[] = [];
const context = hostContext(requested);
@@ -86,7 +204,9 @@ describe("generic module UI host loader", () => {
const mounts = (globalThis as { __mounts?: { moduleId: string; container: Element }[] })
.__mounts;
expect(mounts?.at(-1)?.container).toBe(element);
// The artifact receives the loader's isolated root, never the host's own element.
expect(mounts?.at(-1)?.container).toBe(artifactRoot(element));
expect(mounts?.at(-1)?.container).not.toBe(element);
expect(mounts?.at(-1)?.moduleId).toBe("announcements");
});
@@ -104,7 +224,7 @@ describe("generic module UI host loader", () => {
expect(requested.join(" ")).not.toContain("/api/v1/modules");
});
it("runs the module's cleanup on unmount without touching the host container", async () => {
it("runs the module's cleanup and removes the isolated root without touching the host container", async () => {
const element = container();
const parent = element.parentElement;
@@ -116,7 +236,8 @@ describe("generic module UI host loader", () => {
await mounted.unmount();
expect(mounted.mounted).toBe(false);
expect(element.textContent).toBe("");
// The artifact's root, and with it its styles, are gone.
expect(element.children).toHaveLength(0);
// The host owns the container; unmounting a module never removes it.
expect(element.parentElement).toBe(parent);
expect(document.body.contains(element)).toBe(true);
@@ -151,13 +272,15 @@ describe("generic module UI host loader", () => {
await expect(mounted.unmount()).resolves.toBeUndefined();
expect(mounted.mounted).toBe(false);
expect(element.children).toHaveLength(0);
});
it("marks an instance unmounted even when its cleanup throws, so it never re-runs", async () => {
const element = container();
const artifact = `
export default {
id: "announcements", version: "1.2.0",
abi: ${MODULE_UI_ABI_VERSION}, id: "announcements", version: "1.2.0",
styles: ".x{color:red}",
mount() { return () => { globalThis.__cleanupCalls = (globalThis.__cleanupCalls ?? 0) + 1; throw new Error("cleanup exploded"); }; },
};`;
@@ -169,6 +292,8 @@ describe("generic module UI host loader", () => {
await expect(mounted.unmount()).rejects.toThrow("cleanup exploded");
expect(mounted.mounted).toBe(false);
// A module that fails to clean up must not leave its stylesheet installed in the page.
expect(element.children).toHaveLength(0);
await expect(mounted.unmount()).resolves.toBeUndefined();
expect((globalThis as { __cleanupCalls?: number }).__cleanupCalls).toBe(1);
});
@@ -189,16 +314,17 @@ describe("generic module UI host loader", () => {
context: hostContext([]),
});
expect(first.textContent).toBe("mounted:announcements");
expect(second.textContent).toBe("mounted:announcements");
expect(artifactText(first)).toBe("mounted:announcements");
expect(artifactText(second)).toBe("mounted:announcements");
expect(a.shadowRoot).not.toBe(b.shadowRoot);
await a.unmount();
// Each handle owns its own cleanup state; unmounting one leaves the other alone.
expect(a.mounted).toBe(false);
expect(b.mounted).toBe(true);
expect(first.textContent).toBe("");
expect(second.textContent).toBe("mounted:announcements");
expect(first.children).toHaveLength(0);
expect(artifactText(second)).toBe("mounted:announcements");
});
describe("rejects an artifact before mounting it", () => {
@@ -209,7 +335,7 @@ describe("generic module UI host loader", () => {
await expect(
loadModuleUi({ source: { ...source, url }, container: element, context: hostContext([]) }),
).rejects.toMatchObject({ code: "MODULE_UI_IDENTITY_MISMATCH" });
expect(element.textContent).toBe("");
expect(element.children).toHaveLength(0);
});
it("when the version does not match the manifest", async () => {
@@ -219,7 +345,19 @@ describe("generic module UI host loader", () => {
await expect(
loadModuleUi({ source: { ...source, url }, container: element, context: hostContext([]) }),
).rejects.toMatchObject({ code: "MODULE_UI_IDENTITY_MISMATCH" });
expect(element.textContent).toBe("");
expect(element.children).toHaveLength(0);
});
it("when it was built against the previous mount ABI", async () => {
const element = container();
const url = moduleUrl(
'export default { id: "announcements", version: "1.2.0", mount() {} };',
);
await expect(
loadModuleUi({ source: { ...source, url }, container: element, context: hostContext([]) }),
).rejects.toMatchObject({ code: "MODULE_UI_ABI_UNSUPPORTED" });
expect(element.children).toHaveLength(0);
});
it("when there is no default export", async () => {
@@ -233,7 +371,9 @@ describe("generic module UI host loader", () => {
it("when the default export is not a module UI definition", async () => {
const element = container();
const url = moduleUrl('export default { id: "announcements", version: "1.2.0" };');
const url = moduleUrl(
`export default { abi: ${MODULE_UI_ABI_VERSION}, id: "announcements", version: "1.2.0" };`,
);
const failure = loadModuleUi({
source: { ...source, url },
@@ -263,11 +403,12 @@ describe("generic module UI host loader", () => {
}
});
it("reports a throwing mount as a mount failure and registers no cleanup", async () => {
it("reports a throwing mount as a mount failure, registers no cleanup, and removes the root", async () => {
const element = container();
const url = moduleUrl(`
export default {
id: "announcements", version: "1.2.0",
abi: ${MODULE_UI_ABI_VERSION}, id: "announcements", version: "1.2.0",
styles: ".x{color:red}",
mount(container) { container.textContent = "partial"; throw new Error("mount exploded"); },
};`);
@@ -284,9 +425,38 @@ describe("generic module UI host loader", () => {
expect((error as ModuleUiHostError).message).not.toContain("exploded");
expect((error as { cause?: Error }).cause?.message).toBe("mount exploded");
}
// No handle exists, so nothing can claim the module is mounted. The container is left exactly
// as the module left it: the host owns it and decides what a failed mount looks like.
expect(element.textContent).toBe("partial");
// No handle exists, so nothing can claim the module is mounted — and a failed mount leaves
// neither partial DOM nor an installed stylesheet behind in the host's container.
expect(element.children).toHaveLength(0);
});
it("reports an environment with no Shadow DOM as an isolation failure, never as an unisolated mount", async () => {
const element = container();
const detached = {
ownerDocument: document,
appendChild: element.appendChild.bind(element),
} as unknown as Element;
// A container whose created element cannot take a shadow root: the loader must refuse rather
// than fall back to mounting the artifact — and its styles — straight into the host's page.
const noShadow = new Proxy(detached, {
get(target, property, receiver) {
if (property === "ownerDocument") {
return {
createElement: () => ({ setAttribute: () => undefined }),
};
}
return Reflect.get(target, property, receiver);
},
});
await expect(
loadModuleUi({
source: { ...source, url: moduleUrl(validArtifact()) },
container: noShadow,
context: hostContext([]),
}),
).rejects.toMatchObject({ code: "MODULE_UI_ISOLATION_UNAVAILABLE" });
expect(element.children).toHaveLength(0);
});
it("accepts a host-supplied importer for bundlers that need their own escape hatch", async () => {
@@ -294,7 +464,14 @@ describe("generic module UI host loader", () => {
const seen: string[] = [];
const importModule: ModuleUiImporter = async (url) => {
seen.push(url);
return { default: { id: "announcements", version: "1.2.0", mount: () => undefined } };
return {
default: {
abi: MODULE_UI_ABI_VERSION,
id: "announcements",
version: "1.2.0",
mount: () => undefined,
},
};
};
const mounted = await loadModuleUi({
@@ -5,7 +5,20 @@ import { fileURLToPath } from "node:url";
import { buildModuleUi } from "@ekklesia/module-ui-build";
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
import { beforeAll, describe, expect, it } from "vitest";
import { loadModuleUi } from "../src/index.js";
import {
loadModuleUi,
MODULE_UI_ISOLATION_ATTRIBUTE,
MODULE_UI_ISOLATION_ROOT_ATTRIBUTE,
} from "../src/index.js";
/** What the artifact rendered, reached through the open shadow root the loader created (ADR 0040). */
function artifactText(container: Element): string {
const shadowHost = container.querySelector(`[${MODULE_UI_ISOLATION_ATTRIBUTE}]`);
return (
shadowHost?.shadowRoot?.querySelector(`[${MODULE_UI_ISOLATION_ROOT_ATTRIBUTE}]`)?.textContent ??
""
);
}
const fixtureDirectory = path.join(
path.dirname(fileURLToPath(import.meta.url)),
@@ -80,12 +93,32 @@ describe("loading a real compiled artifact", () => {
context: ekklesiaContext(requested),
});
expect(container.textContent).toBe("example:200:user-123");
expect(artifactText(container)).toBe("example:200:user-123");
await mounted.unmount();
expect(container.textContent).toBe("");
expect(container.children).toHaveLength(0);
expect(mounted.mounted).toBe(false);
});
it("compiles the fixture's stylesheet into the artifact and installs it in the isolated root", async () => {
const container = document.createElement("div");
// No sidecar: the whole stylesheet travels inside the one declared JavaScript artifact.
expect(artifactSource).toContain(".artifact-label");
const mounted = await loadModuleUi({
source: { moduleId: "example", version: "0.1.0", url: artifactUrl },
container,
context: ekklesiaContext([]),
});
const stylesheet = mounted.shadowRoot.querySelector("style")?.textContent ?? "";
expect(stylesheet).toContain(".artifact-label");
expect(stylesheet).toContain("var(--ekklesia-text-primary)");
expect(document.head.textContent ?? "").not.toContain(".artifact-label");
await mounted.unmount();
});
it("still rejects the real artifact when the host expects a different version", async () => {
await expect(
loadModuleUi({
@@ -118,8 +151,8 @@ describe("loading a real compiled artifact", () => {
// the module asked for "records" both times and resolved nothing itself.
expect(ekklesiaRequests).toEqual(["/api/v1/modules/example/records"]);
expect(standaloneRequests).toEqual(["https://example.test/api/records"]);
expect(ekklesiaContainer.textContent).toBe("example:200:user-123");
expect(standaloneContainer.textContent).toBe("example:200:guest");
expect(artifactText(ekklesiaContainer)).toBe("example:200:user-123");
expect(artifactText(standaloneContainer)).toBe("example:200:guest");
await inEkklesia.unmount();
await inStandalone.unmount();