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:
co-authored by
Claude Opus 5
parent
e03d38fcab
commit
07835b7b56
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user