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
+109 -16
View File
@@ -23,6 +23,8 @@ export type ModuleUiBuildErrorCode =
| "MODULE_UI_ENTRYPOINT_UNSAFE"
| "MODULE_UI_ENTRYPOINT_COLLISION"
| "MODULE_UI_SOURCE_MISSING"
| "MODULE_UI_STYLESHEET_INVALID"
| "MODULE_UI_STYLESHEET_UNDECLARED"
| "MODULE_UI_BUILD_FAILED";
export type ModuleUiArtifactKind = "ui" | "display";
@@ -34,6 +36,10 @@ const errorMessages: Readonly<Record<ModuleUiBuildErrorCode, string>> = Object.f
MODULE_UI_ENTRYPOINT_COLLISION:
"A display UI entrypoint must not overwrite another declared artifact.",
MODULE_UI_SOURCE_MISSING: "A declared module UI source entrypoint was not found.",
MODULE_UI_STYLESHEET_INVALID:
"A module stylesheet may not define a global Ekklesia theme variable or keep an unresolved @import.",
MODULE_UI_STYLESHEET_UNDECLARED:
"A module UI build produced a stylesheet beside its artifact. Every style must be compiled into the declared artifact.",
MODULE_UI_BUILD_FAILED: "A module UI bundle could not be produced.",
});
@@ -58,32 +64,97 @@ export class ModuleUiBuildError extends Error {
}
/**
* Rejects a stylesheet import instead of quietly emitting one.
*
* esbuild would happily bundle `import "./styles.css"` into a sidecar `index.css` next to the
* artifact. Nothing declares that file, no host loads it, and the manifest has no field for it — so
* it would work in a local test and silently do nothing in a real host. Module styling has no
* public loading contract yet (ADR 0023), so the build fails loudly rather than producing an
* undeclared asset. `scripts/check-boundaries.ts` rejects a `.css` file authored *inside* a module;
* this additionally covers a stylesheet reached through a dependency.
* A CSS custom property in Ekklesia's own global theme namespace, being **declared** rather than
* referenced. `var(--ekklesia-x)` and `var(--ekklesia-x, fallback)` are reads and are fine; only a
* `--ekklesia-x:` declaration matches, because that is what would invent a global theme variable
* outside the registry a future theme editor enumerates (ADR 0039).
*/
function rejectStylesheetImports(): Plugin {
const GLOBAL_THEME_DECLARATION = /--ekklesia-[a-z0-9-]*\s*:/iu;
/** An `@import` that survived compilation — a remote or otherwise unresolvable one. A local import
* is inlined by the nested bundle below and leaves nothing behind, so anything still here would make
* the artifact fetch a stylesheet at run time, which is exactly what "self-contained" excludes. */
const SURVIVING_IMPORT = /@import\s/iu;
/**
* Compiles each imported stylesheet into the artifact instead of emitting a sidecar.
*
* esbuild's default for `import "./styles.css"` from JavaScript is to collect every such stylesheet
* into an `index.css` output beside the artifact. Nothing declares that file, no host fetches it,
* and the manifest has no field for it — it would work in a local test and silently do nothing in a
* real host. ADR 0023 therefore rejected the import outright; ADR 0040 compiles it instead.
*
* Each `.css` import becomes a JavaScript module whose default export is that stylesheet's compiled
* text, produced by a nested esbuild run so local `@import`s are resolved and the result is one
* self-contained string. The author passes that string to `defineModuleUi({ styles })` and the host
* installs it into the artifact's isolated root. The declared `.js` artifact therefore remains the
* only file the platform publishes, exactly as before stylesheets existed.
*
* Other stylesheet dialects stay rejected. Adding one is a language and toolchain decision, not a
* detail of this pass, and would need its own ADR.
*/
const STYLESHEET_PLUGIN_NAME = "ekklesia-compile-stylesheet-imports";
function compileStylesheetImports(): Plugin {
const decoder = new TextDecoder();
return {
name: "ekklesia-reject-stylesheet-imports",
name: STYLESHEET_PLUGIN_NAME,
setup(pluginBuild) {
// No `u` flag, deliberately: esbuild compiles a plugin filter to a Go RE2 expression, which
// rejects `(?iu)` outright ("filter is not a valid Go regular expression"). This pattern is
// rejects `(?iu)` outright ("filter is not a valid Go regular expression"). These patterns are
// pure ASCII, so the flag would change nothing anyway.
pluginBuild.onResolve({ filter: /\.(css|s[ac]ss|less|styl|pcss|postcss)$/i }, (args) => ({
pluginBuild.onResolve({ filter: /\.(s[ac]ss|less|styl|pcss|postcss)$/i }, (args) => ({
errors: [
{
text:
"Module UI cannot import a stylesheet yet: there is no declared way for a host to " +
"load one. Use React inline style objects for now (ADR 0023).",
"Module UI supports plain .css only. Other stylesheet dialects have no compilation " +
"contract in this platform (ADR 0040).",
location: { file: args.importer },
},
],
}));
pluginBuild.onLoad({ filter: /\.css$/i }, async (args) => {
const compiled = await build({
bundle: true,
entryPoints: [args.path],
logLevel: "silent",
minify: false,
target: MODULE_UI_BUILD_TARGET,
write: false,
});
const stylesheet = compiled.outputFiles
.map((outputFile) => decoder.decode(outputFile.contents))
.join("\n");
if (GLOBAL_THEME_DECLARATION.test(stylesheet)) {
return {
errors: [
{
text:
"A module stylesheet may reference Ekklesia's global theme variables but must " +
"never declare one. Derive a private alias under your own prefix instead " +
"(ADR 0039).",
location: { file: args.path },
},
],
};
}
if (SURVIVING_IMPORT.test(stylesheet)) {
return {
errors: [
{
text:
"A module stylesheet left an unresolved @import. A declared artifact must be " +
"self-contained, so every import has to resolve to a local file (ADR 0040).",
location: { file: args.path },
},
],
};
}
return { contents: `export default ${JSON.stringify(stylesheet)};`, loader: "js" };
});
},
};
}
@@ -237,7 +308,7 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
minify: false,
outfile: artifact.outputFile,
platform: "browser",
plugins: [rejectStylesheetImports()],
plugins: [compileStylesheetImports()],
sourcemap: true,
target: MODULE_UI_BUILD_TARGET,
// Fail rather than silently shipping a partial bundle.
@@ -246,6 +317,17 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
// atomic with respect to parse/resolve/bundle failures rather than leaving a stale partial set.
write: false,
});
// Belt and braces on the stylesheet contract. The plugin above turns every `.css` import into
// JavaScript, so esbuild has nothing left to emit a stylesheet from — but a future option or
// loader change could reintroduce a sidecar, and a sidecar is precisely the failure this
// design exists to make impossible: a file nothing declares, no host fetches, and every local
// test silently passes without. Producing one fails the build rather than shipping it.
const sidecar = result.outputFiles.find(
(outputFile) => path.extname(outputFile.path).toLowerCase() === ".css",
);
if (sidecar) {
throw new ModuleUiBuildError("MODULE_UI_STYLESHEET_UNDECLARED", artifact.kind);
}
pendingWrites.push(
result.outputFiles.map((outputFile) => ({
contents: outputFile.contents,
@@ -253,10 +335,21 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
})),
);
} catch (error) {
if (error instanceof ModuleUiBuildError) {
throw error;
}
// esbuild's structured diagnostics are surfaced by the CLI; rethrow a sanitized error so a
// programmatic caller never receives raw paths or internals.
if (isRecord(error) && Array.isArray(error.errors)) {
throw Object.assign(new ModuleUiBuildError("MODULE_UI_BUILD_FAILED", artifact.kind), {
// A stylesheet the module authored broke one of this platform's own rules, rather than
// failing to compile. Reported with its own code so a caller can tell "your CSS is not
// allowed to do that" from "your TSX does not compile".
const code = error.errors.some(
(diagnostic) => isRecord(diagnostic) && diagnostic.pluginName === STYLESHEET_PLUGIN_NAME,
)
? "MODULE_UI_STYLESHEET_INVALID"
: "MODULE_UI_BUILD_FAILED";
throw Object.assign(new ModuleUiBuildError(code, artifact.kind), {
diagnostics: error.errors,
});
}
@@ -342,10 +342,10 @@ describe("module UI build", () => {
});
it.each([
"styles.css",
"theme.scss",
"layout.less",
])("rejects a %s import rather than emitting an undeclared sidecar asset", async (stylesheet) => {
"tokens.styl",
])("rejects a %s import: only plain CSS has a compilation contract", async (stylesheet) => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
@@ -358,47 +358,131 @@ describe("module UI build", () => {
await buildModuleUi({ moduleDirectory: directory });
expect.unreachable("expected the stylesheet import to be rejected");
} catch (error) {
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_BUILD_FAILED");
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_STYLESHEET_INVALID");
const diagnostics = (error as { diagnostics?: { text?: string }[] }).diagnostics ?? [];
expect(diagnostics.some((entry) => entry.text?.includes("cannot import a stylesheet"))).toBe(
true,
);
expect(diagnostics.some((entry) => entry.text?.includes("plain .css only"))).toBe(true);
}
});
it("never leaves a stylesheet sidecar next to the artifact", async () => {
it("compiles a plain stylesheet into the artifact instead of emitting a sidecar", async () => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
"src/ui/index.tsx": 'import "./styles.css";\nexport default {};',
"src/ui/styles.css": ".example { color: red; }",
"src/ui/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
"src/ui/styles.css": ".example { color: var(--ekklesia-text-primary); }",
},
});
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toBeInstanceOf(
ModuleUiBuildError,
);
const result = await buildModuleUi({ moduleDirectory: directory });
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
// The whole stylesheet travels inside the one declared artifact.
expect(artifact).toContain(".example");
expect(artifact).toContain("--ekklesia-text-primary");
// And nothing was emitted beside it. A sidecar is the exact failure this design prevents: a
// file nothing declares, no host fetches, and every local test silently passes without.
await expect(
readFile(path.join(directory, "dist", "ui", "index.css"), "utf8"),
).rejects.toThrow();
});
it("enforces the stylesheet boundary for display UI too", async () => {
it("resolves a local @import so the compiled stylesheet is self-contained", async () => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
"src/ui/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
"src/ui/styles.css": '@import "./base.css";\n.example { color: red; }',
"src/ui/base.css": ".base { display: grid; }",
},
});
const result = await buildModuleUi({ moduleDirectory: directory });
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
expect(artifact).toContain(".base");
expect(artifact).toContain(".example");
});
it("rejects a stylesheet that keeps an unresolved @import, so the artifact stays self-contained", async () => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
"src/ui/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
"src/ui/styles.css": '@import url("https://fonts.example.invalid/family.css");',
},
});
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toMatchObject({
code: "MODULE_UI_STYLESHEET_INVALID",
});
});
it("rejects a stylesheet that declares a global Ekklesia theme variable", async () => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
"src/ui/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
// Referencing a token is the contract; *declaring* one would invent a global theme variable
// outside the registry a future theme editor enumerates (ADR 0039).
"src/ui/styles.css": ":host { --ekklesia-text-primary: hotpink; }",
},
});
try {
await buildModuleUi({ moduleDirectory: directory });
expect.unreachable("expected the stylesheet to be rejected");
} catch (error) {
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_STYLESHEET_INVALID");
const diagnostics = (error as { diagnostics?: { text?: string }[] }).diagnostics ?? [];
expect(diagnostics.some((entry) => entry.text?.includes("never declare one"))).toBe(true);
}
});
it("accepts a private alias derived from a registered token", async () => {
const directory = await createModule({
ui: "./dist/ui/index.js",
files: {
"src/ui/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
"src/ui/styles.css":
":host { --example-gap: var(--ekklesia-spacing-sm); }\n.example { gap: var(--example-gap); }",
},
});
const artifact = await readFile(
(await buildModuleUi({ moduleDirectory: directory })).artifacts[0]?.outputFile ?? "",
"utf8",
);
expect(artifact).toContain("--example-gap");
});
it("compiles a display artifact's stylesheet the same way", async () => {
const directory = await createModule({
display: {
artifact: "./dist/display/index.js",
permission: "example.display.view",
},
files: {
"src/display/index.tsx": 'import "./styles.css";\nexport default {};',
"src/display/index.tsx": `
import styles from "./styles.css";
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
"src/display/styles.css": ".display { position: fixed; }",
},
});
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toMatchObject({
code: "MODULE_UI_BUILD_FAILED",
kind: "display",
});
const result = await buildModuleUi({ moduleDirectory: directory });
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
expect(artifact).toContain(".display");
await expect(readFile(path.join(directory, "dist/display/index.css"))).rejects.toThrow();
});
+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();
+13 -7
View File
@@ -1,12 +1,18 @@
import { type ModuleUiDefinition, parseModuleUiDefinition } from "./module-ui.js";
import {
MODULE_UI_ABI_VERSION,
type ModuleUiDefinition,
type ModuleUiDefinitionInput,
parseModuleUiDefinition,
} from "./module-ui.js";
/**
* The module author's entry point, mirroring `defineModuleRuntime` (ADR 0006): validate at authoring
* time, freeze, and preserve the literal type. A malformed definition fails where it was written
* rather than in a host, at mount time, in a browser.
* time, freeze, and stamp the browser mount ABI this artifact was built against. A malformed
* definition fails where it was written rather than in a host, at mount time, in a browser.
*
* The ABI marker is added here rather than written by the author, so it can never drift from the SDK
* the artifact actually compiled against — which is the whole point of having one (ADR 0040).
*/
export function defineModuleUi<const Definition extends ModuleUiDefinition>(
definition: Definition,
): Readonly<Definition> {
return parseModuleUiDefinition(definition) as Readonly<Definition>;
export function defineModuleUi(definition: ModuleUiDefinitionInput): ModuleUiDefinition {
return parseModuleUiDefinition({ ...definition, abi: MODULE_UI_ABI_VERSION });
}
+70 -5
View File
@@ -2,17 +2,38 @@ import type { ModuleUiHostContext } from "./host-context.js";
export type Awaitable<Value> = Value | PromiseLike<Value>;
/**
* The version of the browser mount ABI this package defines, and the only one a host accepts.
*
* Version 1 was `{ id, version, mount }` mounted straight into the host's own container. Version 2
* adds a declared `styles` stylesheet and makes every artifact mount inside an **isolated root** the
* host creates (ADR 0040). That is a behavioural change an artifact can observe — its DOM is no
* longer a direct child of the host's element — so it is versioned explicitly rather than
* introduced silently.
*
* There is deliberately no dual acceptance, exactly as there is none for a manifest version
* (ADR 0006, ADR 0014, ADR 0021, ADR 0033): an artifact built against version 1 fails to mount with
* `MODULE_UI_ABI_UNSUPPORTED` rather than being mounted under guessed semantics. Migration is to
* rebuild the module, which is one `pnpm build` — the canonical builder owns every option, and a
* module that declares no stylesheet needs no source change at all.
*
* `defineModuleUi` stamps this for the author. A module never writes it.
*/
export const MODULE_UI_ABI_VERSION = 2;
/**
* Released by a host when the module UI should be torn down. A module that acquires anything during
* `mount` — a framework root, a subscription, a timer, an event listener — must return one of these
* and release that work here, exactly as a backend module releases resources in its `stop` hook
* (ADR 0006). Returning nothing declares that the mount acquired nothing to release.
*
* A module never has to remove its declared `styles`: the host installed them into the isolated root
* it owns, and it removes that whole root after this runs.
*/
export type ModuleUiUnmount = () => Awaitable<void>;
/**
* What either compiled browser artifact (`entrypoints.ui` or `entrypoints.display.artifact`)
* default-exports (ADR 0021, ADR 0022, ADR 0033).
* What a module author passes to {@link defineModuleUi}.
*
* `id` and `version` are build-artifact identity markers, mirroring `ModuleRuntimeDefinition`
* exactly (ADR 0006): they let a host prove the UI bundle it imported was built from the module it
@@ -23,19 +44,38 @@ export type ModuleUiUnmount = () => Awaitable<void>;
* write that (ADR 0022), but React appears nowhere in this type — the contract is a mount function,
* so a module's internal framework choice, and a host's, can each change without renegotiating the
* platform boundary.
*
* `styles` is the artifact's own compiled CSS **text**, not a URL, a filename, or a sidecar
* (ADR 0040). A module imports its local `.css` files and the canonical builder compiles them into
* this string, so the declared JavaScript artifact stays exactly as self-contained as it was before
* stylesheets existed: there is no second file to publish, nothing for a host to fetch, and no way
* for a stylesheet to become an asset nothing serves. The host installs it into the artifact's
* isolated root at mount and removes it at unmount.
*/
export interface ModuleUiDefinition {
export interface ModuleUiDefinitionInput {
readonly id: string;
readonly version: string;
readonly styles?: string;
readonly mount: (
container: Element,
context: ModuleUiHostContext,
) => Awaitable<ModuleUiUnmount | void>;
}
/**
* What either compiled browser artifact (`entrypoints.ui` or `entrypoints.display.artifact`)
* default-exports (ADR 0021, ADR 0022, ADR 0033, ADR 0040): the author's declaration plus the ABI
* marker `defineModuleUi` stamped on it.
*/
export interface ModuleUiDefinition extends ModuleUiDefinitionInput {
readonly abi: number;
}
export type ModuleUiContractErrorCode =
| "MODULE_UI_EXPORT_MISSING"
| "MODULE_UI_DEFINITION_INVALID"
| "MODULE_UI_ABI_UNSUPPORTED"
| "MODULE_UI_STYLES_INVALID"
| "MODULE_UI_IDENTITY_MISMATCH";
const errorMessages: Readonly<Record<ModuleUiContractErrorCode, string>> = Object.freeze({
@@ -43,6 +83,10 @@ const errorMessages: Readonly<Record<ModuleUiContractErrorCode, string>> = Objec
"A module UI entrypoint must have a default export produced by defineModuleUi.",
MODULE_UI_DEFINITION_INVALID:
"A module UI definition must declare a non-empty id and version and a mount function, and nothing else.",
MODULE_UI_ABI_UNSUPPORTED:
"This module UI artifact was built for a different browser mount ABI. Rebuild the module against the current module UI SDK.",
MODULE_UI_STYLES_INVALID:
"A module UI definition's styles must be the artifact's compiled CSS text, as a non-empty string.",
MODULE_UI_IDENTITY_MISMATCH:
"The module UI artifact's id and version do not match the module it was loaded for.",
});
@@ -64,7 +108,7 @@ export class ModuleUiContractError extends Error {
}
}
const definitionKeys = new Set(["id", "mount", "version"]);
const definitionKeys = new Set(["abi", "id", "mount", "styles", "version"]);
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -80,12 +124,15 @@ function isNonEmptyString(value: unknown): value is string {
* grammar — there is exactly one place each of those is defined, and it is not here.
*/
export function isModuleUiDefinition(value: unknown): value is ModuleUiDefinition {
if (!isRecord(value)) {
if (!isRecord(value) || value.abi !== MODULE_UI_ABI_VERSION) {
return false;
}
if (Object.keys(value).some((key) => !definitionKeys.has(key))) {
return false;
}
if (value.styles !== undefined && !isNonEmptyString(value.styles)) {
return false;
}
return (
isNonEmptyString(value.id) &&
isNonEmptyString(value.version) &&
@@ -93,13 +140,31 @@ export function isModuleUiDefinition(value: unknown): value is ModuleUiDefinitio
);
}
/**
* Parses an artifact's default export.
*
* The ABI marker is checked **first and on its own**, so an artifact built against the previous
* mount ABI is reported as exactly that rather than as a malformed definition — the difference
* between "rebuild your module" and a developer hunting for a typo.
*/
export function parseModuleUiDefinition(value: unknown): ModuleUiDefinition {
if (!isRecord(value)) {
throw new ModuleUiContractError("MODULE_UI_DEFINITION_INVALID");
}
if (value.abi !== MODULE_UI_ABI_VERSION) {
throw new ModuleUiContractError("MODULE_UI_ABI_UNSUPPORTED");
}
if (value.styles !== undefined && !isNonEmptyString(value.styles)) {
throw new ModuleUiContractError("MODULE_UI_STYLES_INVALID");
}
if (!isModuleUiDefinition(value)) {
throw new ModuleUiContractError("MODULE_UI_DEFINITION_INVALID");
}
return Object.freeze({
abi: MODULE_UI_ABI_VERSION,
id: value.id,
mount: value.mount,
...(value.styles === undefined ? {} : { styles: value.styles }),
version: value.version,
});
}
@@ -2,23 +2,32 @@ import { beforeEach, describe, expect, it } from "vitest";
import {
defineModuleUi,
isModuleUiDefinition,
MODULE_UI_ABI_VERSION,
ModuleUiContractError,
type ModuleUiApiClient,
type ModuleUiDefinition,
type ModuleUiDefinitionInput,
type ModuleUiHostContext,
type ModuleUiRealtimeClient,
parseModuleUiDefinition,
parseModuleUiExport,
} from "../src/index.js";
function validDefinition(): ModuleUiDefinition {
function definitionInput(): ModuleUiDefinitionInput {
return { id: "announcements", version: "0.1.0", mount: (): void => undefined };
}
/** What a compiled artifact actually default-exports: the author's declaration plus the ABI marker
* `defineModuleUi` stamps on it (ADR 0040). */
function validDefinition(): ModuleUiDefinition {
return { abi: MODULE_UI_ABI_VERSION, ...definitionInput() };
}
/** The contract treats the container as an opaque host-supplied mount target, so a plain object
* with the one property the fixture touches is a faithful stand-in. No DOM is required to prove the
* contract, and this package deliberately does not take a DOM dependency to obtain one. */
const noop = (): void => undefined;
const abi = MODULE_UI_ABI_VERSION;
const noopRealtime: ModuleUiRealtimeClient = Object.freeze({
subscribe: () => Object.freeze({ close: noop }),
@@ -29,23 +38,66 @@ function fakeContainer(): Element & { textContent: string } {
}
describe("module UI definition contract", () => {
it("accepts and freezes a valid definition", () => {
const definition = defineModuleUi(validDefinition());
it("accepts, stamps the ABI on, and freezes a valid definition", () => {
const definition = defineModuleUi(definitionInput());
expect(definition.id).toBe("announcements");
expect(definition.version).toBe("0.1.0");
// Stamped by the SDK the artifact compiled against, never written by the author, so it can
// never drift from the contract the artifact was actually built for.
expect(definition.abi).toBe(MODULE_UI_ABI_VERSION);
expect(definition.styles).toBeUndefined();
expect(Object.isFrozen(definition)).toBe(true);
});
it("carries a declared stylesheet through as the artifact's own compiled CSS text", () => {
const definition = defineModuleUi({ ...definitionInput(), styles: ".a{color:red}" });
expect(definition.styles).toBe(".a{color:red}");
});
it("rejects an artifact built against a different mount ABI, with its own code", () => {
// The whole point of the marker: a version-1 artifact is reported as "rebuild your module",
// not as a malformed definition a developer would hunt for a typo in.
const versionOne = { id: "announcements", version: "0.1.0", mount: noop };
expect(isModuleUiDefinition(versionOne)).toBe(false);
try {
parseModuleUiDefinition(versionOne);
expect.unreachable("expected a contract error");
} catch (error) {
expect((error as ModuleUiContractError).code).toBe("MODULE_UI_ABI_UNSUPPORTED");
}
expect(() =>
parseModuleUiDefinition({ ...versionOne, abi: MODULE_UI_ABI_VERSION + 1 }),
).toThrowError(expect.objectContaining({ code: "MODULE_UI_ABI_UNSUPPORTED" }));
});
it.each<[string, unknown]>([
["a missing id", { version: "0.1.0", mount: noop }],
["a blank id", { id: " ", version: "0.1.0", mount: noop }],
["a non-string id", { id: 7, version: "0.1.0", mount: noop }],
["a missing version", { id: "announcements", mount: noop }],
["a blank version", { id: "announcements", version: "", mount: noop }],
["a missing mount", { id: "announcements", version: "0.1.0" }],
["a non-function mount", { id: "announcements", version: "0.1.0", mount: "render" }],
["an unknown property", { id: "announcements", version: "0.1.0", mount: noop, routes: [] }],
["a blank stylesheet", " "],
["a non-string stylesheet", 7],
["an array of stylesheets", [".a{}"]],
])("rejects %s", (_label, styles) => {
const candidate = { ...validDefinition(), styles };
expect(isModuleUiDefinition(candidate)).toBe(false);
expect(() => parseModuleUiDefinition(candidate)).toThrowError(
expect.objectContaining({ code: "MODULE_UI_STYLES_INVALID" }),
);
});
it.each<[string, unknown]>([
["a missing id", { abi, version: "0.1.0", mount: noop }],
["a blank id", { abi, id: " ", version: "0.1.0", mount: noop }],
["a non-string id", { abi, id: 7, version: "0.1.0", mount: noop }],
["a missing version", { abi, id: "announcements", mount: noop }],
["a blank version", { abi, id: "announcements", version: "", mount: noop }],
["a missing mount", { abi, id: "announcements", version: "0.1.0" }],
["a non-function mount", { abi, id: "announcements", version: "0.1.0", mount: "render" }],
[
"an unknown property",
{ abi, id: "announcements", version: "0.1.0", mount: noop, routes: [] },
],
])("rejects a definition with %s", (_label, candidate) => {
expect(isModuleUiDefinition(candidate)).toBe(false);
expect(() => parseModuleUiDefinition(candidate)).toThrowError(ModuleUiContractError);
@@ -64,7 +116,7 @@ describe("module UI definition contract", () => {
it("reports a malformed definition with a stable, sanitized code", () => {
try {
parseModuleUiDefinition({ id: "announcements" });
parseModuleUiDefinition({ abi, id: "announcements" });
expect.unreachable("expected a contract error");
} catch (error) {
expect(error).toBeInstanceOf(ModuleUiContractError);