diff --git a/.changeset/ui-facade-ssr-and-primitive-expose.md b/.changeset/ui-facade-ssr-and-primitive-expose.md new file mode 100644 index 000000000..ce12f3c03 --- /dev/null +++ b/.changeset/ui-facade-ssr-and-primitive-expose.md @@ -0,0 +1,6 @@ +--- +"everything-dev": minor +"every-plugin": minor +--- + +The `@/ui` facade renders real markup server-side and the expose slims to shadcn primitives (issue #1260). SSR: the host compose threads a session-bound expose resolver through `constructTree` into the generated routeConfig loaders, which register it into the caller's bundled `everything-dev/ui/remote` before route modules evaluate — so facade components resolve through the SAME container generation the tree was minted from (integrity-verified, generation-keyed caches), and the client hydrates the same components once the browser expose lands, with React selective hydration keeping server HTML visible until then. The `render-null-on-server` gate in `remoteComponent` is gone; the `null` fallback only shows without server HTML. Generated routeConfig loaders take the optional resolver argument and register it; client construction omits it. The core ui's node container now ships the `./components` expose. The expose ships shadcn primitives only (`ui/src/components/expose.ts` — everything under `ui/`); app-flavored components (ConfirmDialog, Markdown, stepper, info rows, error surface, …) stay source-owned in the core barrel and never ride the expose, and the scaffold prune protects the expose file so child providers keep the capability surface. SSR documents preload the expose's static dependency chunks (resolved from the core's mf-manifest, best-effort) instead of discovering them after remoteEntry → manifest → hydrate. The published manifest carries the expose surface (`components: [{ expose, exports }]`) for agent-facing discovery, and `remoteComponent` is documented provider-indirection: any composed source's exposes resolve server-side, not just the core's. diff --git a/docs/adr/0064-facade-ssr-and-primitive-expose.md b/docs/adr/0064-facade-ssr-and-primitive-expose.md new file mode 100644 index 000000000..6aef590e2 --- /dev/null +++ b/docs/adr/0064-facade-ssr-and-primitive-expose.md @@ -0,0 +1,113 @@ +# 0064 — The facade resolves server-side; the expose ships primitives only + +Date: 2026-12-02 +Status: Accepted + +Amends: [ADR 0059](./0059-host-surface-and-federated-capabilities.md) §4 (the SSR story +spike verdict 077 item 2 left open, and the expose surface line), and the compose +contract ([ADR 0008](./0008-manifest-composition-and-plugin-mounts.md) — the +`ConstructInput` seam). Closes issue #1260. + +## Context + +The typed `@/ui` facade shipped client-only: `remoteComponent` rendered `null` on the +server and the document carried an empty pending gate for every facade component. +First use serialized gate → hydration → first-render fetch → render. The `./components` +expose carried app-flavored components alongside the shadcn primitives, so a cold +consumer paid for the core's page furniture (Markdown's react-markdown stack, +ConfirmDialog, the error surface) it would never render. + +## Decision + +### 1. SSR: the facade resolves through the composition's own containers + +Server-side facade resolution rides the compose session — not a second loading path: + +- The host builds ONE session-bound expose resolver per compose (`ssrExposeResolverOf`) + and hands it to `constructTree`. Resolution is an integrity-verified expose load + through `FederationLoader` — the same generation-keyed caches every other expose load + rides, so a cached module can never serve into a newer generation's render. +- The engine forwards the resolver to every generated routeConfig loader + (`RouteConfigRef` takes it as an optional argument). Each loader registers it into the + caller's own bundled `everything-dev/ui/remote` (`registerSsrExposeResolver`) BEFORE + dynamically importing its route module, so the facade components those modules create + resolve through the stash at render time. +- The stash is module-level per container graph. Each generation's containers are + distinct module instances, so the binding is generation-scoped by construction — no + global registry that a concurrent compose could repoint mid-render, no new shared + singleton, no AsyncLocalStorage. The resolver crosses containers as a plain function + argument, and the stash module is deliberately import-free: a routeConfig expose with + any static import splits into an external chunk that the dev loopback plane would + otherwise resolve against the plugin's web dev server (see Dev loopback below). +- Client construction omits the resolver; the client path is unchanged (compose-payload + registration + `loadRemote`). On the server without a session (CSR shell), component + loads hold the boundary in its fallback and `remoteModule` fails with a named error — + the previous behavior. + +The `render-null-on-server` gate in `remoteComponent` is deleted. The server streams the +resolved component; the client hydrates the same component once the browser expose +lands, and until then React's selective hydration keeps the server HTML visible — no +mismatch, no flash. The `null` fallback only shows where there is no server HTML +(client-side navigations before the expose is cached). + +The core ui's node container ships the `./components` expose — resolution happens +against the same built artifacts the browser gets, not a parallel server bundle. + +Preload: the SSR document preloads the expose's STATIC dependency chunks +(`assets.js.sync` from the core's browser mf-manifest, attached to the core remote in +the compose payload and emitted by the head links). The manifest's async list is the +app's whole dynamic graph and is never a preload source. Resolution is best-effort — +an absent or unparseable manifest yields no hints, never a compose failure. + +Dev loopback: the loopback plane rewrites the SSR container entry's stamped publicPath +to its own loopback directory. Served unmodified, the container fetches expose chunks +from the plugin's web dev server, where a same-named web chunk (routeConfig ships in +both environments) shadows the node bytes and executes `self`-style web chunks in +node. + +Discovery: the core's manifest carries the expose surface +(`components: [{ expose, exports }]`), generated from the expose files at manifest +generation — the agent-facing catalog ADR 0059 §4 promised. + +### 2. The expose ships shadcn primitives only + +`./components` points at `ui/src/components/expose.ts`: everything under `ui/`, nothing +else. App-flavored components (ConfirmDialog, Markdown, stepper, info rows, local-date, +UnderConstruction) and the error surface (RootError, RootNotFound, RouterError, +DocumentFallback) stay source-owned in the core barrel (`index.ts` re-exports the +expose plus the app-flavored files, so the core's own `@/components` surface is +unchanged). A facade consumer that needs an app-flavored component owns its source — +the same choice ADR 0059 makes the default everywhere else. + +The scaffold prune protects the expose file: a child runtime acts as its own provider, +and `bos mf check` gates the capability against the expose, so pruning it would break +the child's own facade contract. + +## Consequences + +- Facade components render in the SSR document; the docs search input and settings tabs + land in the server HTML. +- First-use cost on a cold consumer drops to the primitives' chunk set; the + react-markdown stack leaves the expose graph entirely. +- Plugin exposes resolve server-side too (the resolver maps any composed source key) — + the auth profile section remotes get the same SSR treatment for free. +- Mixed-generation renders stay impossible: resolution goes through the session the + tree was built from, not a global. +- A rebuild of every ui workspace is required (the generated routeConfig shape changed); + mixed old-plugin/new-host compositions fail at generation skew, loudly, as always. + +## Alternatives rejected + +- **Imports from source inside the SSR container**: build-time coupling between plugin + bundles and the core's source; breaks provider replacement entirely. +- **A global resolver registry keyed by provider name**: a concurrent compose of a new + generation repoints it mid-render — mixed generations mix React copies (the exact + crash class ADR 0049 eliminated). +- **A React context + `everything-dev/ui/remote` as a new shared singleton**: correct + generation scoping, but it widens the strict-singleton trust surface and forces a + fleet rebuild for a seam one function argument provides for free. +- **A second `./app-components` expose**: keeps app-flavored components facade-loadable, + but nothing promises they stay coherent at runtime (they are page furniture, not + capabilities) — source ownership is the honest contract for them. +- **Preloading the manifest's async chunk list**: that list is the app's whole dynamic + graph (~9.6 MB in this build), not the expose's dependencies. diff --git a/host/src/services/local-dist-server.ts b/host/src/services/local-dist-server.ts index d2efef762..2ce4f5236 100644 --- a/host/src/services/local-dist-server.ts +++ b/host/src/services/local-dist-server.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync, statSync } from "node:fs"; import { createServer, type Server } from "node:http"; import path from "node:path"; +import { UI_REMOTE_SERVER_ENTRY_FILENAME } from "everything-dev/ui/manifest"; export interface LocalDistServer { baseUrl: string; @@ -24,9 +25,9 @@ const contentTypeOf = (filePath: string) => MIME_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream"; /** - * Serves a built ui dist directory over loopback HTTP so the host's standard - * remote-loading flow can consume the local node container. Dev only — - * production ui sources always arrive over HTTP from the CDN. + * Serves a built ui dist over loopback HTTP for the host's remote-loading + * flow (dev only). The SSR entry response rewrites the container's stamped + * dev-server publicPath to its own loopback directory (why: ADR 0064). */ export async function startLocalDistServer(rootDir: string): Promise { const normalizedRoot = path.resolve(rootDir); @@ -51,7 +52,19 @@ export async function startLocalDistServer(rootDir: string): Promise((resolve, reject) => { diff --git a/host/src/services/ui-compose.ts b/host/src/services/ui-compose.ts index 9b70bec60..13b36262d 100644 --- a/host/src/services/ui-compose.ts +++ b/host/src/services/ui-compose.ts @@ -1,13 +1,9 @@ /** * Manifest composition for SSR (ADR 0008): manifests + route configs in → - * host-built tree out, digest-cached per resolved config. - * - * Production: the core ui's `./compose` engine (executing inside the core - * container's module graph — constructed routes are minted by the same - * react/router instance that renders them) + `./routeConfig` import maps over - * MF, plugin remotes as consumers (`import: false` — the core provides). - * Local dev: the same modules imported from source — one module graph, one - * React by construction, no MF in the server path. + * host-built tree out, digest-cached per resolved config. Production: the + * core ui's `./compose` engine (executing inside the core container's module + * graph) + `./routeConfig` import maps over MF; local dev: the same exposes + * from the loopback container server — one React by construction. * * The digest covers plugin keys + MF names + manifests + the imported * MOUNT_REGISTRY_VERSION; deployment URLs are excluded so disk and prod @@ -24,11 +20,14 @@ import { digestOf, entryUrls, MANIFEST_FILENAME, + MF_MANIFEST_FILENAME, + manifestBaseOf, type NavManifest, type PluginManifest, parsePluginManifest, type RemoteEntry, type RouteConfigModule, + type SsrExposeResolver, UI_REMOTE_SERVER_ENTRY_FILENAME, } from "everything-dev/ui/manifest"; import { asDigest, fetchVerified } from "everything-dev/verify"; @@ -201,10 +200,21 @@ export interface UiComposeCacheState { remoteManifests: Map; variants: Map; lastGood: CachedLastGood | null; + facadePreload: Map; +} + +interface CachedFacadePreload { + chunks: string[]; + fetchedAt: number; } export function createUiComposeCacheState(): UiComposeCacheState { - return { remoteManifests: new Map(), variants: new Map(), lastGood: null }; + return { + remoteManifests: new Map(), + variants: new Map(), + lastGood: null, + facadePreload: new Map(), + }; } const runFetch = (url: string, init?: RequestInit): Promise => fetch(url, init); @@ -437,25 +447,84 @@ const digestOfSources = Effect.fn("digestOfSources")(function* (composable: Comp }); }); -const clientPayloadOf = (composable: ComposableSource[], digest: string): ComposePayload => ({ +const clientPayloadOf = ( + composable: ComposableSource[], + digest: string, + facadePreload?: string[], +): ComposePayload => ({ digest, remotes: composable.flatMap(({ source, manifest }) => { if (!source.uiEntry) return []; return [ { - // The client matches remotes to manifests by `key === manifest.name`; - // the manifest name IS the composition identity (ADR 0008 §2). The - // MF container name is separate deployment detail. + // the manifest name IS the composition identity (ADR 0008 §2); the + // MF container name is separate deployment detail key: manifest.name, name: source.mfName, entry: source.uiEntry, ...(source.browserManifestUrl ? { manifestUrl: source.browserManifestUrl } : {}), + ...(source.key === CORE_UI_KEY && facadePreload?.length ? { preload: facadePreload } : {}), }, ]; }), manifests: composable.map(({ manifest }) => manifest), }); +/** The core's components-expose static chunks (assets.js.sync) from its + * mf-manifest — SSR preload hints. The async list is the app's whole graph. */ +export function facadeChunkUrlsOf(doc: unknown, base: string): string[] { + if (!doc || typeof doc !== "object") return []; + const exposes = (doc as { exposes?: unknown }).exposes; + if (!Array.isArray(exposes)) return []; + const paths: string[] = []; + const collect = (node: unknown): void => { + if (typeof node === "string") { + if (node.endsWith(".js")) paths.push(node); + } else if (Array.isArray(node)) { + for (const child of node) collect(child); + } + }; + for (const entry of exposes) { + if (!entry || typeof entry !== "object") continue; + const { name, assets } = entry as { name?: unknown; assets?: unknown }; + if (typeof name !== "string" || name.replace(/^\.\//, "") !== "components") continue; + collect((assets as { js?: { sync?: unknown } } | undefined)?.js?.sync); + } + return [ + ...new Set( + paths.map((path) => (/^https?:\/\//.test(path) ? path : `${base}${path.replace(/^\//, "")}`)), + ), + ]; +} + +/** Dev-local ui sources carry no browser-manifest URL — the dev server serves + * it beside the fixed-name entry. */ +function browserManifestUrlOf(source: UiSource): string | undefined { + if (source.browserManifestUrl) return source.browserManifestUrl; + const entry = source.uiEntry; + if (!entry) return undefined; + const base = entry.split("?")[0]?.replace(/\/remoteEntry\.js$/, ""); + return base ? `${base}/${MF_MANIFEST_FILENAME}` : undefined; +} + +const coreFacadePreloadOf = Effect.fn("coreFacadePreloadOf")(function* ( + source: UiSource, + cache: UiComposeCacheState, +) { + const url = browserManifestUrlOf(source); + if (!url) return []; + const cached = cache.facadePreload.get(url); + const now = yield* Clock.currentTimeMillis; + if (cached && now - cached.fetchedAt < MANIFEST_TTL_MS) return cached.chunks; + const chunks = yield* Effect.tryPromise(async () => { + const response = await runFetch(url); + if (!response.ok) throw new Error(`mf-manifest fetch ${response.status} for ${url}`); + return facadeChunkUrlsOf(JSON.parse(await response.text()), manifestBaseOf(url)); + }).pipe(Effect.catch(() => Effect.succeed([] as string[]))); + cache.facadePreload.set(url, { chunks, fetchedAt: now }); + return chunks; +}); + function rememberVariant( cache: UiComposeCacheState, variantKey: string, @@ -469,10 +538,8 @@ function rememberVariant( * Wait for one local source's SSR container, or recover to the last-good * generation (#940): while a previous compose succeeded, an unavailable * container (a concurrent build's transient wipe) serves that generation - * loud instead of failing the request — bounded by the recovery budget so - * requests never park behind bytes a build is rewriting. Without a last-good - * generation there is nothing to serve: the failure stays loud (cold boots - * keep the full wait budget). + * loud instead of failing the request — bounded by the recovery budget. No + * last-good generation: the failure stays loud (cold boots keep the budget). */ const waitOrLastGood = Effect.fn("waitOrLastGood")(function* ( entry: RemoteEntry, @@ -507,6 +574,45 @@ const waitOrLastGood = Effect.fn("waitOrLastGood")(function* ( return lastGood.variant; }); +interface SsrResolverDeps { + env: BosEnv; + loader: FederationLoader["Service"]; + session: CompositionSession; + entryBySourceKey: Map; +} + +/** The session-bound expose resolver handed to `constructTree`: facades + * resolve through the generation the tree was minted from. */ +function ssrExposeResolverOf(deps: SsrResolverDeps): SsrExposeResolver { + return (providerKey, expose) => { + const entry = deps.entryBySourceKey.get(providerKey); + if (!entry) { + return Promise.reject( + new Error( + `ssr expose resolution: source "${providerKey}" is not part of this composition's healthy set`, + ), + ); + } + return Effect.gen(function* () { + const entryUrl = requireSsrEntryUrl(entry, deps.env); + yield* deps.loader.verifyIntegrity({ + remoteName: entry.name, + remoteUrl: entry.ssrUrl, + entryUrl, + integrity: entry.ssrIntegrity, + }); + return yield* deps.loader.loadExpose({ + remoteName: entry.name, + entryUrl, + expose: `${entry.name}/${expose.replace(/^\.\//, "")}`, + unwrapDefault: false, + bypassModuleCache: false, + session: deps.session, + }); + }).pipe(Effect.timeout("30 seconds"), Effect.runPromise); + }; +} + /** Variant cache identity: the structural digest plus a variant key * component — the deployment digest (SSR integrity) in prod, the src * manifest mtime AND built container mtime in dev — so a code-only @@ -635,6 +741,7 @@ export const composeUi = Effect.fn("composeUi")(function* ( const digest = yield* digestOfSources(healthy); + const facadePreload = yield* coreFacadePreloadOf(core, cache); const variantKey = `${digest}::${variantCacheKey(healthySources)}`; const isDev = healthySources.some((source) => source.localRoot); const now = yield* Clock.currentTimeMillis; @@ -659,6 +766,15 @@ export const composeUi = Effect.fn("composeUi")(function* ( return { key: ref.key, manifest, routeConfig: routeConfigFor }; }, rootOptions: coreRouteConfig.rootMeta, + ssrExposeResolver: ssrExposeResolverOf({ + env: config.env, + loader, + session, + entryBySourceKey: new Map([ + [core.key, coreEntry], + ...nonCore.map(({ source }, i) => [source.key, pluginEntries[i]!] as const), + ]), + }), }), ); @@ -681,7 +797,7 @@ export const composeUi = Effect.fn("composeUi")(function* ( routeTree: constructed.rootRoute, digest, nav: constructed.nav, - clientPayload: clientPayloadOf(healthy, digest), + clientPayload: clientPayloadOf(healthy, digest, facadePreload), }; rememberVariant( cache, diff --git a/host/tests/unit/facade-preload.test.ts b/host/tests/unit/facade-preload.test.ts new file mode 100644 index 000000000..31e8a7f45 --- /dev/null +++ b/host/tests/unit/facade-preload.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { facadeChunkUrlsOf } from "../../src/services/ui-compose"; + +const manifestFixture = { + metaData: { name: "ui", publicPath: "/" }, + exposes: [ + { + id: "a1", + name: "Hydrate", + assets: { js: { sync: ["static/js/async/__federation_expose_Hydrate.1e5a.js"] } }, + }, + { + id: "b2", + name: "components", + assets: { + js: { + sync: [ + "static/js/async/__federation_expose_components.4dd5.js", + "static/js/async/src_components_expose_ts.9850.js", + "static/js/async/src_components_expose_ts.9850.js", + ], + async: [ + "static/js/async/vendors-node_modules_better-auth.js", + "static/js/async/vendors-node_modules_tanstack_devtools.js", + ], + }, + }, + }, + ], +}; + +describe("facadeChunkUrlsOf", () => { + it("collects only the components expose's static sync chunks, deduped, base-joined", () => { + const urls = facadeChunkUrlsOf(manifestFixture, "https://ui.example/app/"); + expect(urls).toEqual([ + "https://ui.example/app/static/js/async/__federation_expose_components.4dd5.js", + "https://ui.example/app/static/js/async/src_components_expose_ts.9850.js", + ]); + }); + + it("matches exposes regardless of the ./ prefix", () => { + const doc = { + exposes: [ + { + name: "./components", + assets: { js: { sync: ["static/js/async/x.js"] } }, + }, + ], + }; + expect(facadeChunkUrlsOf(doc, "/")).toEqual(["/static/js/async/x.js"]); + }); + + it("keeps absolute chunk URLs as-is", () => { + const doc = { + exposes: [ + { + name: "components", + assets: { js: { sync: ["https://cdn.example/x.js"] } }, + }, + ], + }; + expect(facadeChunkUrlsOf(doc, "https://ui.example/")).toEqual(["https://cdn.example/x.js"]); + }); + + it("yields nothing for absent, malformed, or expose-less manifests", () => { + expect(facadeChunkUrlsOf(undefined, "/")).toEqual([]); + expect(facadeChunkUrlsOf({}, "/")).toEqual([]); + expect(facadeChunkUrlsOf({ exposes: "nope" }, "/")).toEqual([]); + expect(facadeChunkUrlsOf({ exposes: [{ name: "Hydrate" }] }, "/")).toEqual([]); + }); +}); diff --git a/packages/every-plugin/src/build/ui/factory.ts b/packages/every-plugin/src/build/ui/factory.ts index f7acdb6c9..3389fefcf 100644 --- a/packages/every-plugin/src/build/ui/factory.ts +++ b/packages/every-plugin/src/build/ui/factory.ts @@ -57,7 +57,7 @@ export const CORE_UI_WEB_ENTRY = "./src/entry.gen.ts"; export const CORE_UI_WEB_EXPOSES: Record = { "./Hydrate": "./src/hydrate.gen.tsx", - "./components": "./src/components/index.ts", + "./components": "./src/components/expose.ts", }; export const CORE_UI_NODE_ENTRY = "./src/router.server.gen.tsx"; @@ -66,6 +66,7 @@ export const CORE_UI_NODE_EXPOSES: Record = { "./Router": "./src/router.server.gen.tsx", "./compose": "./src/compose.gen.ts", "./routeConfig": "./src/routeConfig.gen.ts", + "./components": "./src/components/expose.ts", }; export function createCoreUiRsbuildConfig({ domain, account }: CoreUiRsbuildConfigInput = {}) { @@ -84,6 +85,7 @@ export function createCoreUiRsbuildConfig({ domain, account }: CoreUiRsbuildConf webExposes: CORE_UI_WEB_EXPOSES, nodeEntry: CORE_UI_NODE_ENTRY, nodeExposes: CORE_UI_NODE_EXPOSES, + componentExposeFiles: [{ expose: "./components", file: "src/components/expose.ts" }], copy: [ { from: path.join(workspaceRoot, "public"), to: "./" }, ...platformSkillCopies(workspaceRoot), diff --git a/packages/every-plugin/src/build/ui/manifest-plugin.ts b/packages/every-plugin/src/build/ui/manifest-plugin.ts index 12e161a4e..16220b9a0 100644 --- a/packages/every-plugin/src/build/ui/manifest-plugin.ts +++ b/packages/every-plugin/src/build/ui/manifest-plugin.ts @@ -4,16 +4,16 @@ import { generateUiManifest } from "../../ui/manifest/generator"; /** * Rsbuild plugin that keeps a ui source's generated artifacts fresh during * builds and dev watch: manifest.gen.json + routeConfig.gen.ts are - * regenerated in plugin setup (before any environment compiles, so the - * `./routeConfig` MF expose resolves), and again on every build/dev-compile - * start. The stock routeTree write is redirected to a scratch path — - * TanStackRouterRspack owns src/routeTree.gen.ts (its autoCodeSplitting - * options differ from the manifest pass). + * regenerated in plugin setup (before any environment compiles) and again + * on every build/dev-compile start. The stock routeTree write is redirected + * to a scratch path — TanStackRouterRspack owns src/routeTree.gen.ts. */ export interface UiManifestGenPluginOptions { workspaceRoot: string; pluginName: string; + /** provider role only: expose surfaces for the `components` block */ + componentExposeFiles?: Array<{ expose: string; file: string }>; } const inFlight = new Map>(); @@ -36,6 +36,9 @@ export function uiManifestGenPlugin(options: UiManifestGenPluginOptions): Rsbuil workspaceRoot: options.workspaceRoot, pluginName: options.pluginName, emitRouteTree: false, + ...(options.componentExposeFiles + ? { componentExposeFiles: options.componentExposeFiles } + : {}), }), ); diff --git a/packages/every-plugin/src/build/ui/rsbuild-config.ts b/packages/every-plugin/src/build/ui/rsbuild-config.ts index 048a9c638..fd1ef53a2 100644 --- a/packages/every-plugin/src/build/ui/rsbuild-config.ts +++ b/packages/every-plugin/src/build/ui/rsbuild-config.ts @@ -54,6 +54,9 @@ export interface UiRsbuildConfigOptions { /** routes dir relative to the rsbuild cwd — folder-form ui sources live at * `ui/src/routes` while the build runs from the plugin root */ routesDirectory?: string; + /** provider role only: expose surfaces catalogued into the manifest's + * `components` capability block (ADR 0059 §4) */ + componentExposeFiles?: Array<{ expose: string; file: string }>; } export { sanitizeContainerName }; @@ -101,11 +104,16 @@ export function createUiRsbuildConfig(options: UiRsbuildConfigOptions): RsbuildC copy = [], define, routesDirectory, + componentExposeFiles, } = options; const workspaceRootAbsolute = path.resolve(workspaceRoot); const normalizedName = sanitizeContainerName(pkg.name); const manifestGen = () => - uiManifestGenPlugin({ workspaceRoot: workspaceRootAbsolute, pluginName: manifestName }); + uiManifestGenPlugin({ + workspaceRoot: workspaceRootAbsolute, + pluginName: manifestName, + ...(componentExposeFiles ? { componentExposeFiles } : {}), + }); const cssLayers = role === "consumer" ? cssLayersPlugin(manifestName) : cssLayersPlugin(); const withCssLayers = (options: PostCSSLoaderOptions): void => { diff --git a/packages/every-plugin/src/ui/manifest/construct.ts b/packages/every-plugin/src/ui/manifest/construct.ts index ab41477d0..a959b2fa8 100644 --- a/packages/every-plugin/src/ui/manifest/construct.ts +++ b/packages/every-plugin/src/ui/manifest/construct.ts @@ -1,6 +1,6 @@ import type { AnyRoute } from "@tanstack/react-router"; import { createRootRoute, createRoute, Outlet } from "@tanstack/react-router"; -import { CORE_UI_PLUGIN_KEY } from "./contract"; +import { CORE_UI_PLUGIN_KEY, type SsrExposeResolver } from "./contract"; import { digestOf } from "./descriptor"; import type { PluginManifest, RouteRecord } from "./manifest-schema"; import { MOUNT_REGISTRY, type MountId, resolveMountSegment } from "./mount-registry"; @@ -16,14 +16,10 @@ import { ROUTE_OPTION_KEYS, type RouteConfigModule, type RouteOptionsBundle } fr * cannot ship a route that escapes its mount's guard because plugins never * construct route objects. * - * Mounts are the ONLY cross-source parenting points: a root-level - * pathless layout file (`_public.tsx`) declares the mount for the whole - * composition (exactly one declaring source per mount); every other - * source's routes live under the same `_mount/` directory prefix and - * parent onto the shared mount route. This module executes inside the - * core ui's module graph (production MF expose `./compose`, dev source - * import) so constructed routes are minted by the same react/router - * instance that renders them. + * Mounts are the ONLY cross-source parenting points; this module executes + * inside the core ui's module graph (production MF expose `./compose`) so + * constructed routes are minted by the same react/router instance that + * renders them. */ /** @@ -56,6 +52,10 @@ export interface ConstructInput { rootOptions?: RouteOptionsBundle; /** Guard per mount id — beforeLoads supplied by the composing framework. */ guards?: Partial>; + /** SSR only: the session-bound expose resolver forwarded to every + * routeConfig loader so `@/ui` facades resolve real components server-side + * through this composition's containers (ADR 0059 §4). */ + ssrExposeResolver?: SsrExposeResolver; } export interface ConstructedTree { @@ -164,7 +164,7 @@ export async function constructTree(input: ConstructInput): Promise Promise; + /** * MF container naming rule shared by the build (rsbuild config) and runtime * config resolution — the host must register remotes under exactly the name diff --git a/packages/every-plugin/src/ui/manifest/generator.ts b/packages/every-plugin/src/ui/manifest/generator.ts index 59f23d3d4..6937f1694 100644 --- a/packages/every-plugin/src/ui/manifest/generator.ts +++ b/packages/every-plugin/src/ui/manifest/generator.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { Generator, getConfig } from "@tanstack/router-generator"; @@ -15,20 +16,13 @@ import { ROUTE_OPTION_KEYS } from "./route-config"; /** * The load-bearing generator step (ADR 0008 §2). Rides - * `@tanstack/router-generator`'s scan (Generator.run + getCrawlingResult) - * and emits, per ui source workspace: - * - * - src/routeTree.gen.ts via the stock generator run (plugin-local - * standalone DX — never consumed by the host) - * - src/manifest.gen.json pure data: ids, paths, nesting, mounts, files - * - src/routeConfig.gen.ts generated import map of per-route option - * bundles + lifted `__root` meta - * - * Nothing hand-maintained: the only inputs are the route files. Root-level - * pathless layouts derive mounts via the registry; unknown mounts, routes + * `@tanstack/router-generator`'s scan and emits, per ui source workspace: + * src/routeTree.gen.ts (stock generator run — plugin-local standalone DX), + * src/manifest.gen.json (pure data: ids, paths, nesting, mounts, files), and + * src/routeConfig.gen.ts (generated import map of per-route option bundles + + * lifted `__root` meta). Inputs: the route files only. Unknown mounts, routes * under a missing mount layout, and duplicate sibling paths are hard errors - * here (cross-plugin path collisions are enforced at construction time — - * see `constructTree`). + * here (cross-plugin path collisions are enforced at `constructTree`). */ export interface ManifestGeneratorOptions { @@ -47,6 +41,8 @@ export interface ManifestGeneratorOptions { * autoCodeSplitting options differ); only manifest + routeConfig persist. */ emitRouteTree?: boolean; + /** Expose surfaces for the manifest's `components` block (provider only). */ + componentExposeFiles?: Array<{ expose: string; file: string }>; } interface ScanNode { @@ -59,6 +55,13 @@ interface ScanNode { const idOf = (node: { routePath?: string }): string => (node.routePath ?? "").replace(/^\//, ""); +/** The stash module the generated loaders register the SSR resolver into — + * dynamically imported inside each loader body: the routeConfig expose keeps + * an empty static graph (import-free exposes inline into the SSR container + * entry; an external chunk resolves through the dev server's publicPath and + * executes web-format chunks in node). */ +const SSR_RESOLVER_IMPORT = "everything-dev/ui/ssr-registry"; + function importPathOf(file: string): string { return `./routes/${file.replace(/\.tsx$/, "").replace(/\.ts$/, "")}`; } @@ -74,6 +77,7 @@ export async function generateUiManifest( srcDir = "./src", typeImport = "everything-dev/ui/manifest", emitRouteTree = true, + componentExposeFiles, } = options; const routeTreeTarget = emitRouteTree @@ -183,10 +187,29 @@ export async function generateUiManifest( throw new Error(`manifest generation failed for ${pluginName}:\n ${errors.join("\n ")}`); } + const components = (componentExposeFiles ?? []).map(({ expose, file }) => { + const content = readFileSync(path.resolve(workspaceRoot, file), "utf8"); + const names: string[] = []; + for (const match of content.matchAll(/export\s*\{([^}]+)\}/gs)) { + for (const raw of (match[1] ?? "").split(",")) { + const name = raw + .trim() + .replace(/^type\s+/, "") + .replace(/\s+as\s+.*$/, ""); + if (name && !names.includes(name)) names.push(name); + } + } + if (names.length === 0) { + throw new Error(`component expose "${file}" exports nothing`); + } + return { expose, exports: names }; + }); + const manifest: PluginManifest = PluginManifestSchema.parse({ name: pluginName, manifestVersion: MANIFEST_VERSION, routes, + ...(components.length > 0 ? { components } : {}), }); const resolvedSrc = path.resolve(workspaceRoot, srcDir); @@ -200,7 +223,13 @@ export async function generateUiManifest( .filter((r) => r.file) .map( (r) => - ` ${JSON.stringify(r.id)}: () => import(${JSON.stringify(importPathOf(r.file!))}).then((m) => pick(m.Route.options)),`, + ` ${JSON.stringify(r.id)}: async (ssr) => {\n` + + ` if (ssr) {\n` + + ` const { registerSsrExposeResolver } = await import(${JSON.stringify(SSR_RESOLVER_IMPORT)});\n` + + ` registerSsrExposeResolver(ssr);\n` + + ` }\n` + + ` return import(${JSON.stringify(importPathOf(r.file!))}).then((m) => pick(m.Route.options));\n` + + ` },`, ); const rootImport = `import { Route as __rootRoute } from ${JSON.stringify(importPathOf(rootRouteNode.filePath ?? "__root"))};`; diff --git a/packages/every-plugin/src/ui/manifest/manifest-schema.ts b/packages/every-plugin/src/ui/manifest/manifest-schema.ts index e094bc4fc..6e615c799 100644 --- a/packages/every-plugin/src/ui/manifest/manifest-schema.ts +++ b/packages/every-plugin/src/ui/manifest/manifest-schema.ts @@ -3,16 +3,14 @@ import { MOUNTS } from "./mount-registry"; /** * manifest.gen.json — pure data emitted by the generator from route files - * only (ADR 0008 §2). Nothing here is hand-maintained; this schema is the - * composition contract and the audit/marketplace surface. The host refuses - * unknown `manifestVersion` majors. + * only (ADR 0008 §2). This schema is the composition contract; the host + * refuses unknown `manifestVersion` majors. */ /** - * The manifest contract major this code speaks. Emitted by the generator and - * enforced at every load (the host parses through `parsePluginManifest`; the - * client parse of the compose payload checks it — a skewed major degrades to - * the core-only tree instead of silently mis-constructing). + * The manifest contract major this code speaks. Enforced at every load — + * a skewed major degrades to the core-only tree instead of silently + * mis-constructing. */ export const MANIFEST_VERSION = 2; export const SUPPORTED_MANIFEST_VERSION = MANIFEST_VERSION; @@ -32,6 +30,15 @@ export const RouteRecordSchema = z.object({ file: z.string().optional(), }); +export const ComponentSurfaceSchema = z.object({ + /** the MF expose path, e.g. "./components" */ + expose: z.string(), + /** export names, values and types, in declaration order */ + exports: z.array(z.string()), +}); + +export type ComponentSurface = z.infer; + export const PluginManifestSchema = z.object({ /** Plugin key — derived from the workspace/config key by the emitter. */ name: z.string(), @@ -45,12 +52,12 @@ export const PluginManifestSchema = z.object({ }) .optional(), routes: z.array(RouteRecordSchema), + /** Capability surfaces a core ui provider publishes (ADR 0059 §4) — what + * `@/ui` resolves, read from the expose files at manifest generation. */ + components: z.array(ComponentSurfaceSchema).optional(), }); -/** - * The load-time contract check — one diagnostic for a manifest from a - * different framework major. Every manifest load goes through this. - */ +/** The load-time contract check — a manifest from a different major fails. */ export function parsePluginManifest(data: unknown): PluginManifest { const parsed = PluginManifestSchema.parse(data); if (parsed.manifestVersion !== SUPPORTED_MANIFEST_VERSION) { @@ -71,12 +78,8 @@ export type RouteRecord = z.infer; export type PluginManifest = z.infer; export type Manifest = z.infer; -/** - * The client compose payload — the runtime-config `ui.compose` block the - * server embeds and the client reconstructs the tree from. Single home: - * everything-dev's client-config schema, the hydrate client, and the host's - * ui-compose all derive from this schema. - */ +/** The client compose payload — the `ui.compose` block the server embeds + * and the client reconstructs the tree from. */ export const ComposeRemoteSchema = z.object({ key: z.string(), name: z.string(), @@ -84,6 +87,10 @@ export const ComposeRemoteSchema = z.object({ /** the remote's (hashed) browser-manifest URL — preferred over deriving * one from `entry` by stripping the legacy fixed entry name */ manifestUrl: z.string().optional(), + /** browser chunk URLs to preload from the SSR document (the core ui's + * components expose) — collapses the remoteEntry → manifest → chunk + * waterfall behind document parse instead of hydration */ + preload: z.array(z.string()).optional(), }); export const ComposePayloadSchema = z diff --git a/packages/every-plugin/src/ui/manifest/route-config.ts b/packages/every-plugin/src/ui/manifest/route-config.ts index 4672f9617..798d3d4bf 100644 --- a/packages/every-plugin/src/ui/manifest/route-config.ts +++ b/packages/every-plugin/src/ui/manifest/route-config.ts @@ -10,6 +10,7 @@ */ import type { ReactNode } from "react"; +import type { SsrExposeResolver } from "./contract"; export interface RouteHeadData { meta?: Array>; @@ -40,7 +41,7 @@ export interface RouteOptionsBundle { notFoundComponent?: (props: any) => ReactNode; } -export type RouteConfigRef = () => Promise; +export type RouteConfigRef = (ssrExposeResolver?: SsrExposeResolver) => Promise; export type RouteConfigModule = { routeConfigLoaders: Record; diff --git a/packages/every-plugin/tests/unit/core-ui-exposes.test.ts b/packages/every-plugin/tests/unit/core-ui-exposes.test.ts index a8cc77340..6de61aba2 100644 --- a/packages/every-plugin/tests/unit/core-ui-exposes.test.ts +++ b/packages/every-plugin/tests/unit/core-ui-exposes.test.ts @@ -11,13 +11,14 @@ describe("core ui build surface", () => { expect(CORE_UI_WEB_ENTRY).toBe("./src/entry.gen.ts"); expect(CORE_UI_WEB_EXPOSES).toEqual({ "./Hydrate": "./src/hydrate.gen.tsx", - "./components": "./src/components/index.ts", + "./components": "./src/components/expose.ts", }); expect(CORE_UI_NODE_ENTRY).toBe("./src/router.server.gen.tsx"); expect(CORE_UI_NODE_EXPOSES).toEqual({ "./Router": "./src/router.server.gen.tsx", "./compose": "./src/compose.gen.ts", "./routeConfig": "./src/routeConfig.gen.ts", + "./components": "./src/components/expose.ts", }); }); }); diff --git a/packages/everything-dev/package.json b/packages/everything-dev/package.json index 485d0382f..a1b90b785 100644 --- a/packages/everything-dev/package.json +++ b/packages/everything-dev/package.json @@ -317,6 +317,15 @@ "import": "./dist/ui/remote.mjs", "require": "./dist/ui/remote.cjs" }, + "./ui/ssr-registry": { + "development": { + "types": "./src/ui/ssr-registry.ts", + "import": "./src/ui/ssr-registry.ts" + }, + "types": "./dist/ui/ssr-registry.d.mts", + "import": "./dist/ui/ssr-registry.mjs", + "require": "./dist/ui/ssr-registry.cjs" + }, "./ui/router-client": { "development": { "types": "./src/ui/router-client.tsx", diff --git a/packages/everything-dev/skills/ui-integration/SKILL.md b/packages/everything-dev/skills/ui-integration/SKILL.md index 297524cd7..36aa98af7 100644 --- a/packages/everything-dev/skills/ui-integration/SKILL.md +++ b/packages/everything-dev/skills/ui-integration/SKILL.md @@ -173,13 +173,7 @@ The types come from the auto-generated `api-types.gen.ts`, which merges every pl ### Error Handling -Network/fetch errors are automatically caught by the `RPCLink` interceptor and shown as a toast: - -``` -"Unable to connect to API" — The API is currently unavailable. -``` - -Procedure-level errors (like `UNAUTHORIZED`, `NOT_FOUND`) are thrown as `ORPCError` instances and should be caught inline: +Network/fetch errors are automatically caught by the `RPCLink` interceptor and shown as a toast ("Unable to connect to API" — The API is currently unavailable). Procedure-level errors (like `UNAUTHORIZED`, `NOT_FOUND`) are thrown as `ORPCError` instances and should be caught inline: ```ts try { @@ -266,9 +260,7 @@ Use `sessionQueryOptions()` for standardized session fetching with TanStack Quer ```ts // In a route loader: -const session = await queryClient.ensureQueryData( - sessionQueryOptions(authClient, context.session), -); +const session = await queryClient.ensureQueryData(sessionQueryOptions(authClient, context.session)); ``` ```ts @@ -342,8 +334,11 @@ nav declaration names it as a string (`icon: "cube"`). - Plugin UIs import generic primitives (Button, Card, Input, ...) from the generated typed facade **`@/ui`**: `bos types gen` emits `src/ui.gen.ts` and maps the tsconfig alias; components resolve the active provider through the - runtime compose payload and render client-side (SSR shows nothing for them). - Hooks and helpers ride `loadComponents()`. + runtime compose payload. The SSR document renders real markup — the compose + session resolves the components expose server-side — and the client hydrates + the same components once the browser expose lands. The expose ships shadcn + primitives only; app-flavored components (ConfirmDialog, Markdown, page + furniture) stay source-owned. Hooks and helpers ride `loadComponents()`. - Source ownership is the customization path: copy the reference implementation from the provider's `components/ui/` (or `bos import` it) and restyle against the shared semantic tokens plus `data-slot`/state classes (ADR 0059). Never diff --git a/packages/everything-dev/src/services/codegen/ui-facade.ts b/packages/everything-dev/src/services/codegen/ui-facade.ts index c49546f58..8c5b1e385 100644 --- a/packages/everything-dev/src/services/codegen/ui-facade.ts +++ b/packages/everything-dev/src/services/codegen/ui-facade.ts @@ -55,10 +55,10 @@ export function uiFacadeConsumers(runtimeConfig: RuntimeConfig): UiFacadeConsume } function emitProviderDeclarations(providerRoot: string, projectRoot: string): string { - const entry = join(providerRoot, "src", "components", "index.ts"); + const entry = join(providerRoot, "src", "components", "expose.ts"); if (!existsSync(entry)) { throw new Error( - `the core ui provider publishes no components barrel — expected src/components/index.ts`, + `the core ui provider publishes no components expose — expected src/components/expose.ts`, ); } if (!existsSync(join(providerRoot, "tsconfig.json"))) { @@ -72,7 +72,7 @@ function emitProviderDeclarations(providerRoot: string, projectRoot: string): st outDir, relative(projectRoot, join(providerRoot, "src")), "components", - "index.d.ts", + "expose.d.ts", ); const newestSource = newestSourceMtime(join(providerRoot, "src")); if (existsSync(emittedEntry) && statSync(emittedEntry).mtimeMs >= newestSource) { @@ -270,10 +270,10 @@ interface FacadeSurface { } function facadeSurface(treeRoot: string): FacadeSurface { - const indexDts = join(treeRoot, "components", "index.d.ts"); - const barrelDir = dirname(indexDts); + const exposeDts = join(treeRoot, "components", "expose.d.ts"); + const barrelDir = dirname(exposeDts); const surface: FacadeSurface = { components: [], types: [], bare: [] }; - for (const entry of parseBarrelExports(readFileSync(indexDts, "utf8"))) { + for (const entry of parseBarrelExports(readFileSync(exposeDts, "utf8"))) { if (entry.kind === "type") { surface.types.push(entry.name); continue; @@ -296,9 +296,10 @@ function facadeContent(treeImportPath: string, surface: FacadeSurface): string { "// `bos build` (gitignored). Typed facade over the active core ui provider's", "// `./components` expose (ADR 0059 §4): components resolve the provider", "// through the runtime compose payload, are typed against the provider's", - "// emitted declarations, and render nothing on the server until the client", - "// loads them; hooks and helpers ride `loadComponents()` inside a client", - "// effect.", + "// emitted declarations, and render real markup on the server through the", + "// compose session's SSR expose resolver — the client hydrates the same", + "// components once the browser expose lands; hooks and helpers ride", + "// `loadComponents()` inside a client effect.", 'import { remoteComponent, remoteModule } from "everything-dev/ui/remote";', ]; if (surface.components.length > 0) { @@ -379,7 +380,7 @@ export const emitUiFacadesEffect = Effect.fn("emitUiFacades")(function* ( if (writeIfChanged(target, rewritten)) copied++; } const facadePath = join(consumer.workspaceRoot, FACADE_FILENAME); - const treeImportPath = `./lib/ui-types.gen/${providerRelFromRoot}/src/components/index`; + const treeImportPath = `./lib/ui-types.gen/${providerRelFromRoot}/src/components/expose`; if ( writeIfChanged(facadePath, facadeContent(treeImportPath, facadeSurface(consumerSrcInTree))) ) { diff --git a/packages/everything-dev/src/services/scaffold/prune.ts b/packages/everything-dev/src/services/scaffold/prune.ts index a0569127b..107e85403 100644 --- a/packages/everything-dev/src/services/scaffold/prune.ts +++ b/packages/everything-dev/src/services/scaffold/prune.ts @@ -153,10 +153,11 @@ function listFilesRecursive(dir: string, out: string[] = []): string[] { function isProtected(relPath: string, srcDir: string): boolean { const withinSrc = relative(srcDir, relPath); if (withinSrc.startsWith("..") || isAbsolute(withinSrc)) return true; - // Root-level src files are the framework's entry surface — never pruned. if (!withinSrc.includes("/")) return true; if (withinSrc.startsWith("routes/")) return true; if (/\.gen\.(ts|tsx|json)$/.test(withinSrc)) return true; + // The expose file is the provider capability surface (ADR 0059 §4). + if (withinSrc === "components/expose.ts") return true; if (isFrameworkOwnedSyncFile(join("ui/src", withinSrc))) return true; return false; } diff --git a/packages/everything-dev/src/ui/head.ts b/packages/everything-dev/src/ui/head.ts index 72d5900d4..6fcb88609 100644 --- a/packages/everything-dev/src/ui/head.ts +++ b/packages/everything-dev/src/ui/head.ts @@ -127,6 +127,16 @@ export function getRemotePreloadLinks( fetchPriority: "high", }); } + for (const href of remote.preload ?? []) { + if (seen.has(href)) continue; + seen.add(href); + links.push({ + rel: "preload", + href, + as: "script", + fetchPriority: "low", + }); + } } return links; } diff --git a/packages/everything-dev/src/ui/manifest/index.ts b/packages/everything-dev/src/ui/manifest/index.ts index a7c7e385e..c2359ff40 100644 --- a/packages/everything-dev/src/ui/manifest/index.ts +++ b/packages/everything-dev/src/ui/manifest/index.ts @@ -33,6 +33,7 @@ export type { RouteConfigRef, RouteOptionsBundle, RouteRecord, + SsrExposeResolver, } from "every-plugin/ui/manifest"; // every-plugin manifest engine export { diff --git a/packages/everything-dev/src/ui/remote.tsx b/packages/everything-dev/src/ui/remote.tsx index 31848fe45..fb95fe83b 100644 --- a/packages/everything-dev/src/ui/remote.tsx +++ b/packages/everything-dev/src/ui/remote.tsx @@ -1,6 +1,7 @@ import { UI_REMOTE_ENTRY_FILENAME } from "every-plugin/ui/manifest/contract"; import type { ComponentType, FunctionComponent } from "react"; -import { createElement, lazy, Suspense, useSyncExternalStore } from "react"; +import { createElement, lazy, Suspense } from "react"; +import { currentSsrExposeResolver } from "./ssr-registry"; const MF_MANIFEST_FILENAME = "mf-manifest.json"; @@ -54,14 +55,33 @@ async function ensureProviderRegistered(providerName: string): Promise { registeredProviders.add(providerName); } -export async function remoteModule(providerName: string, expose: string): Promise { - if (typeof window === "undefined") { +async function resolveServerModule( + providerName: string, + expose: string, +): Promise { + const resolver = currentSsrExposeResolver(); + if (!resolver) return undefined; + const loaded = await resolver(providerName, expose); + if (loaded === undefined || loaded === null) { throw new Error( - `remote module "${providerName}/${normalizeExpose(expose)}" cannot load on the server — remote exposes are client-loaded; read non-component values in a client effect`, + `remote module "${providerName}/${normalizeExpose(expose)}" resolved empty on the server — expose "${expose}" has no value in the SSR container`, ); } - const { loadRemote } = await import("@module-federation/enhanced/runtime"); + return loaded as T; +} + +export async function remoteModule(providerName: string, expose: string): Promise { const moduleId = `${providerName}/${normalizeExpose(expose)}`; + if (typeof window === "undefined") { + const loaded = await resolveServerModule(providerName, expose); + if (loaded === undefined) { + throw new Error( + `remote module "${moduleId}" cannot load on the server — no SSR compose session is registered; read non-component values in a client effect`, + ); + } + return loaded; + } + const { loadRemote } = await import("@module-federation/enhanced/runtime"); try { await ensureProviderRegistered(providerName); const loaded = await loadRemote(moduleId, { from: "build" }); @@ -84,7 +104,17 @@ export function remoteComponentLoader( ): () => Promise<{ default: ComponentType }> { return async () => { if (typeof window === "undefined") { - return new Promise<{ default: ComponentType }>(() => {}); + const loaded = await resolveServerModule>(providerName, expose); + if (loaded === undefined) { + return new Promise<{ default: ComponentType }>(() => {}); + } + const Component = loaded[namedExport]; + if (typeof Component !== "function") { + throw new Error( + `remote module "${providerName}/${normalizeExpose(expose)}" has no export "${namedExport}"`, + ); + } + return { default: Component as ComponentType }; } const mod = await remoteModule>(providerName, expose); const Component = mod[namedExport]; @@ -97,16 +127,6 @@ export function remoteComponentLoader( }; } -const clientOnlySubscribe = () => () => {}; - -function useClientOnly(): boolean { - return useSyncExternalStore( - clientOnlySubscribe, - () => true, - () => false, - ); -} - export function remoteComponent( providerName: string, expose: string, @@ -116,7 +136,6 @@ export function remoteComponent( remoteComponentLoader(providerName, expose, namedExport), ) as FunctionComponent; return function RemoteComponent(props: TProps) { - if (!useClientOnly()) return null; return createElement(Suspense, { fallback: null }, createElement(Inner, props)); }; } diff --git a/packages/everything-dev/src/ui/ssr-registry.ts b/packages/everything-dev/src/ui/ssr-registry.ts new file mode 100644 index 000000000..ab220686d --- /dev/null +++ b/packages/everything-dev/src/ui/ssr-registry.ts @@ -0,0 +1,11 @@ +import type { SsrExposeResolver } from "every-plugin/ui/manifest/contract"; + +let ssrExposeResolver: SsrExposeResolver | undefined; + +export function registerSsrExposeResolver(resolver: SsrExposeResolver | undefined): void { + ssrExposeResolver = resolver; +} + +export function currentSsrExposeResolver(): SsrExposeResolver | undefined { + return ssrExposeResolver; +} diff --git a/packages/everything-dev/tests/integration/init.matrix.test.ts b/packages/everything-dev/tests/integration/init.matrix.test.ts index c382568fa..b8af8312a 100644 --- a/packages/everything-dev/tests/integration/init.matrix.test.ts +++ b/packages/everything-dev/tests/integration/init.matrix.test.ts @@ -335,7 +335,9 @@ describe.each(LEVELS)("init %s — structure matrix", (level: Level) => { listFiles(join(child.dir, "ui", "src", "components", "ui")).length, ).toBeGreaterThanOrEqual(10); const barrel = readFileSync(join(child.dir, "ui", "src", "components", "index.ts"), "utf-8"); - expect(barrel).toContain('from "./ui/button"'); + expect(barrel).toContain('export * from "./expose"'); + const expose = readFileSync(join(child.dir, "ui", "src", "components", "expose.ts"), "utf-8"); + expect(expose).toContain('from "./ui/button"'); const before = listFiles(join(child.dir, "ui", "src")); pruneUnusedUiFiles(child.dir); diff --git a/packages/everything-dev/tests/ui/manifest-generator.test.ts b/packages/everything-dev/tests/ui/manifest-generator.test.ts index 84c3e48d7..ce72bb888 100644 --- a/packages/everything-dev/tests/ui/manifest-generator.test.ts +++ b/packages/everything-dev/tests/ui/manifest-generator.test.ts @@ -97,10 +97,13 @@ describe("generateUiManifest", () => { expect(manifestFile).toEqual(goldenManifest); const routeConfig = await readFile(path.join(dir, "src/routeConfig.gen.ts"), "utf8"); - expect(routeConfig).toContain('"_public/login": () => import("./routes/_public/login")'); - expect(routeConfig).toContain( - '"_authenticated/settings/": () => import("./routes/_authenticated/settings/index")', - ); + expect(routeConfig).toContain('await import("everything-dev/ui/ssr-registry")'); + expect(routeConfig).toContain("registerSsrExposeResolver(ssr)"); + expect(routeConfig).not.toContain("import { registerSsrExposeResolver }"); + expect(routeConfig).toContain('"_public/login": async (ssr) => {'); + expect(routeConfig).toContain("registerSsrExposeResolver(ssr);"); + expect(routeConfig).toContain('return import("./routes/_public/login")'); + expect(routeConfig).toContain('return import("./routes/_authenticated/settings/index")'); expect(routeConfig).toContain('import { Route as __rootRoute } from "./routes/__root"'); expect(routeConfig).toContain( 'import type { RouteConfigModule, RouteOptionsBundle } from "everything-dev/ui/manifest"', diff --git a/packages/everything-dev/tests/unit/__snapshots__/public-surface.test.ts.snap b/packages/everything-dev/tests/unit/__snapshots__/public-surface.test.ts.snap index 9e2214fb3..3f75750f8 100644 --- a/packages/everything-dev/tests/unit/__snapshots__/public-surface.test.ts.snap +++ b/packages/everything-dev/tests/unit/__snapshots__/public-surface.test.ts.snap @@ -2028,6 +2028,10 @@ exports[`public-surface guard > symbol list per entry matches the snapshot (upda "kind": "reexport", "name": "sanitizeContainerName", }, + { + "kind": "reexport-type", + "name": "SsrExposeResolver", + }, { "kind": "reexport", "name": "SUPPORTED_MANIFEST_VERSION", @@ -2154,6 +2158,19 @@ exports[`public-surface guard > symbol list per entry matches the snapshot (upda ] `; +exports[`public-surface guard > symbol list per entry matches the snapshot (update it in the same PR as the export change) > ./ui/ssr-registry 1`] = ` +[ + { + "kind": "function", + "name": "currentSsrExposeResolver", + }, + { + "kind": "function", + "name": "registerSsrExposeResolver", + }, +] +`; + exports[`public-surface guard > symbol list per entry matches the snapshot (update it in the same PR as the export change) > ./ui/tenant 1`] = ` [ { diff --git a/packages/everything-dev/tests/unit/ui-expose-surface.test.ts b/packages/everything-dev/tests/unit/ui-expose-surface.test.ts new file mode 100644 index 000000000..bc3742954 --- /dev/null +++ b/packages/everything-dev/tests/unit/ui-expose-surface.test.ts @@ -0,0 +1,53 @@ +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +const COMPONENTS_DIR = join( + dirname(fileURLToPath(import.meta.url)), + "..", + "..", + "..", + "..", + "ui", + "src", + "components", +); + +const read = (file: string): string => readFileSync(join(COMPONENTS_DIR, file), "utf8"); + +const exportSourcesOf = (content: string): string[] => + [...content.matchAll(/from "([^"]+)";/g)].map((match) => match[1] ?? ""); + +describe("the ./components expose surface (ADR 0059 §4)", () => { + it("ships shadcn primitives only — every export comes from ./ui/*", () => { + const sources = exportSourcesOf(read("expose.ts")); + expect(sources.length).toBeGreaterThan(0); + const foreign = sources.filter((source) => !source.startsWith("./ui/")); + expect(foreign).toEqual([]); + }); + + it("is re-exported wholesale by the core barrel — no drifted copies", () => { + expect(read("index.ts")).toContain('export * from "./expose";'); + }); + + it("does not leak app-flavored components into the expose", () => { + const expose = read("expose.ts"); + for (const appFlavored of [ + "confirm-dialog", + "document-fallback", + "empty-state", + "info-popover", + "info-row", + "local-date", + "markdown", + "root-error", + "root-not-found", + "router-error", + "stepper", + "under-construction", + ]) { + expect(expose).not.toContain(`from "./${appFlavored}"`); + } + }); +}); diff --git a/packages/everything-dev/tests/unit/ui-remote.test.ts b/packages/everything-dev/tests/unit/ui-remote.test.ts index dd5f1d24c..d4344152f 100644 --- a/packages/everything-dev/tests/unit/ui-remote.test.ts +++ b/packages/everything-dev/tests/unit/ui-remote.test.ts @@ -9,6 +9,7 @@ vi.mock("@module-federation/enhanced/runtime", () => ({ })); import { remoteComponentLoader, remoteModule } from "../../src/ui/remote"; +import { registerSsrExposeResolver } from "../../src/ui/ssr-registry"; type RemoteModule = { default: unknown }; @@ -23,6 +24,7 @@ describe("remoteModule", () => { loadRemote.mockReset(); registerRemotes.mockReset(); vi.unstubAllGlobals(); + registerSsrExposeResolver(undefined); }); it("registers the provider from the compose payload, then loads the module", async () => { @@ -99,14 +101,38 @@ describe("remoteModule", () => { ]); }); - it("fails with a named error on the server instead of reading window", async () => { + it("fails with a named error on the server when no SSR session is registered", async () => { vi.unstubAllGlobals(); await expect(remoteModule("ui", "./components")).rejects.toThrow( - "cannot load on the server — remote exposes are client-loaded", + "cannot load on the server — no SSR compose session is registered", ); expect(loadRemote).not.toHaveBeenCalled(); }); + + it("resolves through the SSR session's resolver when one is registered", async () => { + vi.unstubAllGlobals(); + const resolver = vi.fn(async (_key: string, expose: string) => { + expect(expose).toBe("./components"); + return { Button: () => null }; + }); + registerSsrExposeResolver(resolver); + + const mod = await remoteModule<{ Button: unknown }>("ui", "./components"); + + expect(mod.Button).toBeDefined(); + expect(resolver).toHaveBeenCalledWith("ui", "./components"); + expect(loadRemote).not.toHaveBeenCalled(); + }); + + it("fails loud when the SSR session resolves an empty expose", async () => { + vi.unstubAllGlobals(); + registerSsrExposeResolver(async () => null); + + await expect(remoteModule("ui", "./components")).rejects.toThrow( + "resolved empty on the server", + ); + }); }); describe("remoteComponent", () => { @@ -114,9 +140,10 @@ describe("remoteComponent", () => { loadRemote.mockReset(); registerRemotes.mockReset(); vi.unstubAllGlobals(); + registerSsrExposeResolver(undefined); }); - it("renders nothing on the server and never suspends — the gate is the SSR shape", async () => { + it("renders nothing on the server when no SSR session is registered", async () => { vi.unstubAllGlobals(); const { renderToStaticMarkup } = await import("react-dom/server"); const { createElement } = await import("react"); @@ -128,6 +155,29 @@ describe("remoteComponent", () => { expect(html).toBe(""); expect(loadRemote).not.toHaveBeenCalled(); }); + + it("renders real markup on the server through the SSR session's resolver", async () => { + vi.unstubAllGlobals(); + const { renderToReadableStream } = await import("react-dom/server"); + const { createElement } = await import("react"); + const { remoteComponent } = await import("../../src/ui/remote"); + + registerSsrExposeResolver(async () => ({ + Button: ({ label }: { label: string }) => + createElement("button", { "data-testid": "facade-button" }, label), + })); + + const Button = remoteComponent<{ label: string }>("ui", "./components", "Button"); + const stream = await renderToReadableStream(createElement(Button, { label: "hi" })); + let html = ""; + for await (const chunk of stream as unknown as AsyncIterable) { + html += new TextDecoder().decode(chunk); + } + + expect(html).toContain('data-testid="facade-button"'); + expect(html).toContain("hi"); + expect(loadRemote).not.toHaveBeenCalled(); + }); }); describe("remoteComponentLoader", () => { @@ -135,6 +185,7 @@ describe("remoteComponentLoader", () => { loadRemote.mockReset(); registerRemotes.mockReset(); vi.unstubAllGlobals(); + registerSsrExposeResolver(undefined); }); it("resolves the named export", async () => { diff --git a/packages/everything-dev/tsdown.config.ts b/packages/everything-dev/tsdown.config.ts index f2f2df7a8..798e55daa 100644 --- a/packages/everything-dev/tsdown.config.ts +++ b/packages/everything-dev/tsdown.config.ts @@ -119,6 +119,7 @@ export default defineConfig({ "src/descriptor/index.ts", "src/config.ts", "src/ui/remote.tsx", + "src/ui/ssr-registry.ts", "src/services/resolution/session.ts", "src/services/registry/index.ts", "src/services/registry/dag.ts", diff --git a/tests/regression/browser/specs/ui-facade.spec.ts b/tests/regression/browser/specs/ui-facade.spec.ts new file mode 100644 index 000000000..8890d47aa --- /dev/null +++ b/tests/regression/browser/specs/ui-facade.spec.ts @@ -0,0 +1,59 @@ +import { expect, test } from "@playwright/test"; + +test.describe("ui facade", () => { + test("the docs index is server-rendered with the remote Input's markup", async ({ request }) => { + const response = await request.get("/docs"); + expect(response.status()).toBe(200); + const html = await response.text(); + + expect(html, "page must be server-rendered").toContain("data-everything-ssr"); + expect(html, "the docs search row must be server-rendered").toContain("docs.search"); + expect(html, "the @/ui Input must render real markup server-side").toContain( + 'data-slot="input"', + ); + }); + + test("the SSR document preloads the components expose's static chunks", async ({ request }) => { + const response = await request.get("/docs"); + const html = await response.text(); + + const configMatch = html.match(/window\.__RUNTIME_CONFIG__=(\{.*?\});\s*function __hydrate/s); + expect(configMatch, "runtime config must be embedded for hydration").toBeTruthy(); + const config = JSON.parse(configMatch![1]) as { + ui?: { compose?: { remotes?: Array<{ key: string; preload?: string[] }> } }; + }; + const core = config.ui?.compose?.remotes?.find((remote) => remote.key === "ui"); + expect(core, "compose payload must include the core ui remote").toBeTruthy(); + expect( + core?.preload?.length ?? 0, + "the core remote must carry facade preload chunk URLs resolved from its mf-manifest", + ).toBeGreaterThan(0); + for (const href of core?.preload ?? []) { + expect(href).toMatch(/\.js$/); + } + }); + + test("the expose is fetched once per session and reused across navigations", async ({ page }) => { + const exposeRequests: string[] = []; + page.on("request", (request) => { + if (request.url().includes("__federation_expose_components")) { + exposeRequests.push(request.url()); + } + }); + + await page.goto("/docs", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("docs.search")).toBeVisible(); + expect(exposeRequests.length, "the facade fetch starts on the facade page").toBeGreaterThan(0); + + await page.goto("/about", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("about.open-skill-link")).toBeVisible(); + + await page.goBack({ waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("docs.search")).toBeVisible(); + + expect( + new Set(exposeRequests).size, + "one expose chunk URL per session — the coarse one-request load, browser/module-cached across routes (cache revalidations may repeat the request event)", + ).toBe(1); + }); +}); diff --git a/ui/src/components/expose.ts b/ui/src/components/expose.ts new file mode 100644 index 000000000..750f35091 --- /dev/null +++ b/ui/src/components/expose.ts @@ -0,0 +1,122 @@ +export { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"; +export { Badge } from "./ui/badge"; +export { + Breadcrumb, + BreadcrumbEllipsis, + BreadcrumbItem, + BreadcrumbLink, + BreadcrumbList, + BreadcrumbPage, + BreadcrumbSeparator, +} from "./ui/breadcrumb"; +export { Button } from "./ui/button"; +export { + Card, + CardAction, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "./ui/card"; +export { Checkbox } from "./ui/checkbox"; +export { Chip } from "./ui/chip"; +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} from "./ui/dialog"; +export { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuPortal, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "./ui/dropdown-menu"; +export { + Field, + FieldDescription, + FieldError, + FieldLabel, +} from "./ui/field"; +export { Input } from "./ui/input"; +export { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupInput, + InputGroupText, + InputGroupTextarea, +} from "./ui/input-group"; +export { + Item, + ItemActions, + ItemContent, + ItemDescription, + ItemFooter, + ItemGroup, + ItemHeader, + ItemMedia, + ItemSeparator, + ItemTitle, +} from "./ui/item"; +export { Label } from "./ui/label"; +export { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; +export { ScrollArea, ScrollBar } from "./ui/scroll-area"; +export { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectScrollDownButton, + SelectScrollUpButton, + SelectSeparator, + SelectTrigger, + SelectValue, +} from "./ui/select"; +export { Separator } from "./ui/separator"; +export { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, + SheetTrigger, +} from "./ui/sheet"; +export { Skeleton } from "./ui/skeleton"; +export { Spinner } from "./ui/spinner"; +export { + Table, + TableBody, + TableCaption, + TableCell, + TableFooter, + TableHead, + TableHeader, + TableRow, +} from "./ui/table"; +export { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs"; +export { Textarea } from "./ui/textarea"; +export { Toggle, toggleVariants } from "./ui/toggle"; +export { ToggleGroup, ToggleGroupItem } from "./ui/toggle-group"; +export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; diff --git a/ui/src/components/index.ts b/ui/src/components/index.ts index 1bb806922..476892acd 100644 --- a/ui/src/components/index.ts +++ b/ui/src/components/index.ts @@ -1,6 +1,7 @@ export { ConfirmDialog } from "./confirm-dialog"; export { DocumentFallback } from "./document-fallback"; export { EmptyState } from "./empty-state"; +export * from "./expose"; export { InfoPopover, type InfoPopoverLink } from "./info-popover"; export { InfoRow } from "./info-row"; export { formatLocalDate, LocalDate, useLocalDate } from "./local-date"; @@ -14,126 +15,4 @@ export { type StepState, useStepper, } from "./stepper"; -export { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"; -export { Badge } from "./ui/badge"; -export { - Breadcrumb, - BreadcrumbEllipsis, - BreadcrumbItem, - BreadcrumbLink, - BreadcrumbList, - BreadcrumbPage, - BreadcrumbSeparator, -} from "./ui/breadcrumb"; -export { Button } from "./ui/button"; -export { - Card, - CardAction, - CardContent, - CardDescription, - CardFooter, - CardHeader, - CardTitle, -} from "./ui/card"; -export { Checkbox } from "./ui/checkbox"; -export { Chip } from "./ui/chip"; -export { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogOverlay, - DialogPortal, - DialogTitle, - DialogTrigger, -} from "./ui/dialog"; -export { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuGroup, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuPortal, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuSeparator, - DropdownMenuShortcut, - DropdownMenuSub, - DropdownMenuSubContent, - DropdownMenuSubTrigger, - DropdownMenuTrigger, -} from "./ui/dropdown-menu"; -export { - Field, - FieldDescription, - FieldError, - FieldLabel, -} from "./ui/field"; -export { Input } from "./ui/input"; -export { - InputGroup, - InputGroupAddon, - InputGroupButton, - InputGroupInput, - InputGroupText, - InputGroupTextarea, -} from "./ui/input-group"; -export { - Item, - ItemActions, - ItemContent, - ItemDescription, - ItemFooter, - ItemGroup, - ItemHeader, - ItemMedia, - ItemSeparator, - ItemTitle, -} from "./ui/item"; -export { Label } from "./ui/label"; -export { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; -export { ScrollArea, ScrollBar } from "./ui/scroll-area"; -export { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectLabel, - SelectScrollDownButton, - SelectScrollUpButton, - SelectSeparator, - SelectTrigger, - SelectValue, -} from "./ui/select"; -export { Separator } from "./ui/separator"; -export { - Sheet, - SheetClose, - SheetContent, - SheetDescription, - SheetFooter, - SheetHeader, - SheetTitle, - SheetTrigger, -} from "./ui/sheet"; -export { Skeleton } from "./ui/skeleton"; -export { Spinner } from "./ui/spinner"; -export { - Table, - TableBody, - TableCaption, - TableCell, - TableFooter, - TableHead, - TableHeader, - TableRow, -} from "./ui/table"; -export { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs"; -export { Textarea } from "./ui/textarea"; -export { Toggle, toggleVariants } from "./ui/toggle"; -export { ToggleGroup, ToggleGroupItem } from "./ui/toggle-group"; -export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; export { UnderConstruction } from "./under-construction";