Files
Ekklesia/surfaces/shell/tests/modularity.test.ts
T
ekklesiaandClaude Opus 5 c444ff570b feat: let one module contribute a browser renderer to another's capability
The platform has had a complete story for one module using another's
*backend* since ADR 0006 — capabilities, versioned ranges, provider
registration. It has had none at all for one module using another's *browser*
code, and every workaround is wrong in a way that matters: a consumer cannot
import a peer module, it cannot re-implement a renderer for a domain it does
not own, and a second `entrypoints` role would put the platform in charge of
deciding when a slot inside someone else's screen should be filled.

Add a generic browser contribution. `manifestVersion: 7` declares one:
namespaced id, its own version, a target capability, a compatible range, and
one artifact. That is the complete list, and the omissions are the decision —
no payload schema, slot, ordering, or rendering hint exists anywhere, so Core
cannot learn what a slide is because the declaration cannot express it.

Discovery resolves a contribution artifact through the *identical* loop every
other compiled entrypoint uses, inheriting the path, containment, symlink,
extension, and file-kind checks rather than getting a weaker copy of them. The
registry publishes one only when another eligible module provides the target
capability within the declared range; otherwise it is absent rather than
mounted and broken. `apps/api` serves it as a sibling of the artifact and
display routes, with the same policy: three lookup keys, one exact match, one
already-validated path, and one indistinguishable 404 for unknown, undeclared,
stale, and incompatible alike.

A consumer discovers through the host, never through a URL. Its descriptor
carries identity, version, and capability; the URL stays server-side and is
resolved exactly as `api.request("records")` is. A module can only ever see
contributions aimed at a capability it itself provides, and cannot name its
way to anything else — a mount for a withheld id fails without fetching.

The consumer owns the domain contract entirely. Input is opaque JSON, checked
structurally so a Date, a function, a cycle, or `undefined` fails at the
boundary rather than vanishing somewhere far from the mistake, and checked for
nothing else. A contributed renderer receives its own id and that input: no
API client, realtime, principal, configuration, database, storage, or
credential. Loading one grants its module nothing.

The contribution ABI is versioned separately from the module UI ABI, because
the two have different shapes and lifecycles and coupling them would force
every module to rebuild whenever either moved. It supports asynchronous
readiness, update-without-remount (a screen that remounted per tick would
restart animations and reload media), deterministic cleanup in a `finally`,
and sanitized failure that never carries the consumer's domain data. Each
renderer mounts in its own isolated root with its own stylesheet.

The template now declares a contribution, so `pnpm build` exercises the whole
authoring path, and the shell suite drives the full relationship — one module
discovering, mounting, updating, and unmounting another's React renderer with
neither importing the other.

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

256 lines
11 KiB
TypeScript

import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { beforeAll, describe, expect, it } from "vitest";
/**
* The proof that this shell is a *generic* host rather than an application that happens to render
* some known modules.
*
* Two levels, because they fail differently. At source level, a static import of a module would be
* an architectural mistake a reviewer should catch. At bundle level, a dynamic import that a bundler
* managed to resolve statically would be an invisible one: the code would look correct, the tests
* would pass, and installing a new module would silently do nothing until the shell was rebuilt.
*
* `happy-dom` replaces the global `URL` with the DOM implementation, which `node:fs` rejects, so
* everything here works in plain filesystem paths.
*/
const packageDirectory = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const sourceDirectory = path.join(packageDirectory, "src");
/** The complete set of packages this shell may reach for. `@ekklesia/module-ui-host` is the generic
* loader and `@ekklesia/module-ui-sdk` is the browser-side contract; no other `@ekklesia/*` package
* — and no module — may appear. */
/**
* The complete set of Ekklesia packages the shell may reach: the two browser contracts it mounts
* modules with, and the two design packages every Ekklesia screen is built from (ADR 0039). All
* four are browser-safe by construction and none of them names a module.
*/
const ALLOWED_EKKLESIA_IMPORTS = new Set([
"@ekklesia/design-tokens",
"@ekklesia/module-ui-host",
"@ekklesia/module-ui-sdk",
"@ekklesia/ui",
]);
async function sourceFiles(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
files.push(...(await sourceFiles(entryPath)));
} else if (/\.tsx?$/u.test(entry.name)) {
files.push(entryPath);
}
}
return files.sort();
}
function importSpecifiers(source: string): string[] {
const specifiers = new Set<string>();
const patterns = [
/\b(?:import|export)\s+(?:type\s+)?[^;]*?\bfrom\s*["']([^"'\n]+)["']/gu,
/\bimport\s*["']([^"'\n]+)["']/gu,
/\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/gu,
];
for (const pattern of patterns) {
for (const match of source.matchAll(pattern)) {
if (match[1]) {
specifiers.add(match[1]);
}
}
}
return [...specifiers];
}
let files: string[];
let sources: Map<string, string>;
beforeAll(async () => {
files = await sourceFiles(sourceDirectory);
sources = new Map(
await Promise.all(files.map(async (file) => [file, await readFile(file, "utf8")] as const)),
);
});
describe("the shell is coupled to no module", () => {
it("has source files to check", () => {
expect(files.length).toBeGreaterThan(3);
});
it("imports no module, template, or workspace package beyond the two browser contracts", () => {
for (const [file, source] of sources) {
for (const specifier of importSpecifiers(source)) {
const label = `${path.relative(packageDirectory, file)} -> ${specifier}`;
expect(specifier.includes("modules/"), label).toBe(false);
expect(specifier.includes("templates/"), label).toBe(false);
// Nothing may climb out of this package at all.
expect(specifier.startsWith("../../"), label).toBe(false);
if (specifier.startsWith("@ekklesia/")) {
expect(ALLOWED_EKKLESIA_IMPORTS.has(specifier), label).toBe(true);
}
}
}
});
it("performs no dynamic import of its own: all module loading goes through the generic loader", () => {
for (const [file, source] of sources) {
// Comment lines are dropped so a doc comment may still *describe* the loader's own
// `(url) => import(url)`. The authoritative check is the bundle-level one below, which counts
// dynamic imports in the emitted output where no comment survives.
const code = source
.split("\n")
.filter((line) => !/^\s*(\*|\/\/)/u.test(line))
.join("\n");
const dynamicImports = [...code.matchAll(/\bimport\s*\(/gu)];
expect(dynamicImports, path.relative(packageDirectory, file)).toEqual([]);
}
});
});
describe("the shell builds no module knowledge into its bundle", () => {
let bundle: string;
beforeAll(async () => {
// The real production bundle configuration, produced in memory so this test never depends on a
// previous `pnpm build` having run.
const result = await build({
absWorkingDir: packageDirectory,
bundle: true,
define: {
__EKKLESIA_API_BASE_URL__: '""',
"process.env.NODE_ENV": '"production"',
},
entryPoints: [path.join(sourceDirectory, "browser", "main.tsx")],
format: "esm",
jsx: "automatic",
logLevel: "silent",
minify: false,
platform: "browser",
target: "es2022",
write: false,
});
bundle = result.outputFiles.map((file) => file.text).join("\n");
}, 60_000);
it("leaves exactly the generic loaders' dynamic imports unresolved for run time", () => {
const dynamicImports = [...bundle.matchAll(/\bimport\s*\(/gu)];
// Exactly two, both `@ekklesia/module-ui-host`'s `(url) => import(url)`: one for a module UI
// artifact and one for a contributed renderer (ADR 0041). More would mean the shell acquired a
// loader of its own; fewer would mean the bundler resolved one away and installed code could
// never be fetched at run time.
expect(dynamicImports).toHaveLength(2);
expect(bundle.split("(url) => import(url)")).toHaveLength(3);
});
it("contains no module identity and no module API prefix", () => {
// The shell learns every module id, artifact URL, and API root from the inventory at run time.
// Any of these appearing in the bundle would mean it had been baked in instead.
expect(bundle).not.toContain("/api/v1/modules");
expect(bundle).not.toContain("/api/v1/module-ui/");
expect(bundle).not.toContain("ekklesia.module.json");
expect(bundle).not.toContain("entrypoints");
});
it("spells only the platform paths it genuinely owns", () => {
// The platform's own endpoints — never a module's. Everything module-specific arrives at run
// time from the navigation the server resolved.
expect(bundle).toContain('"/api/v1/principal"');
expect(bundle).toContain('"/api/v1/dashboard/navigation"');
expect(bundle).toContain('"/api/auth/sign-in/email"');
expect(bundle).toContain('"/api/auth/sign-out"');
// The shell reads the navigation view, which already contains the inventory; it never calls
// the host-neutral inventory endpoint itself.
expect(bundle).not.toContain('"/api/v1/module-ui"');
});
it("contains only the browser HTTP auth adapter, never Better Auth or server identity internals", () => {
expect(bundle.toLowerCase()).not.toContain("better-auth");
expect(bundle.toLowerCase()).not.toContain("drizzle");
expect(bundle).not.toContain("EKKLESIA_IDENTITY_SECRET");
expect(bundle).not.toContain("bootstrapPlatformOwner");
expect(bundle).not.toContain("session_token");
});
it("bakes in no group, label, or placement", () => {
// Grouping is server-resolved configuration. A group id or label appearing in the bundle would
// mean the shell had an opinion about an arrangement it must only render.
// Deliberately distinctive terms: a generic word like "media" appears inside React's own
// bundled source and would make this assertion meaningless rather than strict.
for (const term of ["planning", "sunday-production", "livestream", "calendar", "ungrouped-"]) {
expect(bundle.toLowerCase(), term).not.toContain(term);
}
});
it("uses neither eval nor a blob URL to load module code", () => {
expect(bundle).not.toContain("new Function(");
expect(bundle).not.toMatch(/\beval\s*\(/u);
expect(bundle).not.toContain("createObjectURL");
});
});
describe("the display host is a separate generic browser bundle", () => {
let bundle: string;
beforeAll(async () => {
const result = await build({
absWorkingDir: packageDirectory,
bundle: true,
define: {
__EKKLESIA_API_BASE_URL__: '""',
"process.env.NODE_ENV": '"production"',
},
entryPoints: [path.join(sourceDirectory, "display", "main.tsx")],
format: "esm",
jsx: "automatic",
logLevel: "silent",
minify: false,
platform: "browser",
target: "es2022",
write: false,
});
bundle = result.outputFiles.map((file) => file.text).join("\n");
}, 60_000);
it("contains the generic loaders' dynamic imports and no statically known module", () => {
// Two, both the generic loader's: a display artifact and a contributed renderer (ADR 0041).
expect([...bundle.matchAll(/\bimport\s*\(/gu)]).toHaveLength(2);
expect(bundle.split("(url) => import(url)")).toHaveLength(3);
expect(bundle).not.toContain("ekklesia.module.json");
expect(bundle).not.toContain("/api/v1/modules");
for (const moduleId of ["announcements", "calendar", "livestream", "signage"]) {
expect(bundle.toLowerCase()).not.toContain(moduleId);
}
});
it("knows only its host route resources, with no Dashboard application or transport coupling", () => {
expect(bundle).toContain('"/api/v1/module-displays"');
// Pairing is a display concern and lives here; the Dashboard bundle has its own management UI.
expect(bundle).toContain('"/api/v1/device-pairing/requests"');
expect(bundle).toContain('"/api/v1/device-pairing/claims"');
// And the display deliberately never asks the *human* principal endpoint: a paired device is
// anonymous to it, so consulting it would report every display in the building as signed out
// (ADR 0036). The descriptor reports the viewer instead.
expect(bundle).not.toContain('"/api/v1/principal"');
// A display never approves, lists, or revokes a device — that is the administrator's surface.
expect(bundle).not.toContain('"/api/v1/device-pairing/approvals"');
expect(bundle).not.toContain('"/api/v1/devices"');
expect(bundle).not.toContain('"/api/v1/dashboard/navigation"');
expect(bundle).not.toContain('"/api/auth/sign-in/email"');
expect(bundle).not.toContain('"/api/auth/sign-out"');
expect(bundle).not.toContain("Loading Ekklesia");
expect(bundle).not.toContain("Sign in to Ekklesia");
expect(bundle.toLowerCase()).not.toContain("socket.io");
expect(bundle.toLowerCase()).not.toContain("mqtt");
});
it("uses neither eval nor a blob URL to load display code", () => {
expect(bundle).not.toContain("new Function(");
expect(bundle).not.toMatch(/\beval\s*\(/u);
expect(bundle).not.toContain("createObjectURL");
});
});